src/platform/qt/Window.cpp (view raw)
1/* Copyright (c) 2013-2016 Jeffrey Pfau
2 *
3 * This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6#include "Window.h"
7
8#include <QDesktopWidget>
9#include <QKeyEvent>
10#include <QKeySequence>
11#include <QMenuBar>
12#include <QMessageBox>
13#include <QMimeData>
14#include <QPainter>
15#include <QStackedLayout>
16
17#include "AboutScreen.h"
18#ifdef USE_SQLITE3
19#include "ArchiveInspector.h"
20#endif
21#include "CheatsView.h"
22#include "ConfigController.h"
23#include "DebuggerConsole.h"
24#include "DebuggerConsoleController.h"
25#include "Display.h"
26#include "GameController.h"
27#include "GBAApp.h"
28#include "GDBController.h"
29#include "GDBWindow.h"
30#include "GIFView.h"
31#include "IOViewer.h"
32#include "LoadSaveState.h"
33#include "LogView.h"
34#include "MultiplayerController.h"
35#include "MemoryView.h"
36#include "OverrideView.h"
37#include "ObjView.h"
38#include "PaletteView.h"
39#include "ROMInfo.h"
40#include "SensorView.h"
41#include "SettingsView.h"
42#include "ShaderSelector.h"
43#include "ShortcutController.h"
44#include "TileView.h"
45#include "VideoView.h"
46
47#include <mgba/core/version.h>
48#ifdef M_CORE_GB
49#include <mgba/internal/gb/gb.h>
50#include <mgba/internal/gb/video.h>
51#endif
52#include "feature/commandline.h"
53#include "feature/sqlite3/no-intro.h"
54#include <mgba-util/vfs.h>
55
56using namespace QGBA;
57
58Window::Window(ConfigController* config, int playerId, QWidget* parent)
59 : QMainWindow(parent)
60 , m_log(0)
61 , m_logView(new LogView(&m_log))
62 , m_stateWindow(nullptr)
63 , m_screenWidget(new WindowBackground())
64 , m_logo(":/res/mgba-1024.png")
65 , m_config(config)
66 , m_inputController(playerId, this)
67#ifdef USE_FFMPEG
68 , m_videoView(nullptr)
69#endif
70#ifdef USE_MAGICK
71 , m_gifView(nullptr)
72#endif
73#ifdef USE_GDB_STUB
74 , m_gdbController(nullptr)
75#endif
76#ifdef USE_DEBUGGERS
77 , m_console(nullptr)
78#endif
79 , m_mruMenu(nullptr)
80 , m_shortcutController(new ShortcutController(this))
81 , m_fullscreenOnStart(false)
82 , m_autoresume(false)
83 , m_wasOpened(false)
84{
85 setFocusPolicy(Qt::StrongFocus);
86 setAcceptDrops(true);
87 setAttribute(Qt::WA_DeleteOnClose);
88 m_controller = new GameController(this);
89 m_controller->setInputController(&m_inputController);
90 updateTitle();
91
92 m_display = Display::create(this);
93 m_shaderView = new ShaderSelector(m_display, m_config);
94
95 m_logo.setDevicePixelRatio(m_screenWidget->devicePixelRatio());
96 m_logo = m_logo; // Free memory left over in old pixmap
97
98 m_screenWidget->setMinimumSize(m_display->minimumSize());
99 m_screenWidget->setSizePolicy(m_display->sizePolicy());
100 int i = 2;
101 QVariant multiplier = m_config->getOption("scaleMultiplier");
102 if (!multiplier.isNull()) {
103 m_savedScale = multiplier.toInt();
104 i = m_savedScale;
105 }
106#ifdef USE_SQLITE3
107 m_libraryView = new LibraryView(this);
108 ConfigOption* showLibrary = m_config->addOption("showLibrary");
109 showLibrary->connect([this](const QVariant& value) {
110 if (value.toBool()) {
111 if (m_controller->isLoaded()) {
112 m_screenWidget->layout()->addWidget(m_libraryView);
113 } else {
114 attachWidget(m_libraryView);
115 }
116 } else {
117 detachWidget(m_libraryView);
118 }
119 }, this);
120 m_config->updateOption("showLibrary");
121
122 connect(m_libraryView, &LibraryView::accepted, [this]() {
123 VFile* output = m_libraryView->selectedVFile();
124 QPair<QString, QString> path = m_libraryView->selectedPath();
125 if (output) {
126 m_controller->loadGame(output, path.first, path.second);
127 }
128 });
129#elif defined(M_CORE_GBA)
130 m_screenWidget->setSizeHint(QSize(VIDEO_HORIZONTAL_PIXELS * i, VIDEO_VERTICAL_PIXELS * i));
131#endif
132 m_screenWidget->setPixmap(m_logo);
133 m_screenWidget->setLockAspectRatio(m_logo.width(), m_logo.height());
134 setCentralWidget(m_screenWidget);
135
136 connect(m_controller, SIGNAL(gameStarted(mCoreThread*, const QString&)), this, SLOT(gameStarted(mCoreThread*, const QString&)));
137 connect(m_controller, SIGNAL(gameStarted(mCoreThread*, const QString&)), &m_inputController, SLOT(suspendScreensaver()));
138 connect(m_controller, SIGNAL(gameStopped(mCoreThread*)), m_display, SLOT(stopDrawing()));
139 connect(m_controller, SIGNAL(gameStopped(mCoreThread*)), this, SLOT(gameStopped()));
140 connect(m_controller, SIGNAL(gameStopped(mCoreThread*)), &m_inputController, SLOT(resumeScreensaver()));
141 connect(m_controller, SIGNAL(stateLoaded(mCoreThread*)), m_display, SLOT(forceDraw()));
142 connect(m_controller, SIGNAL(rewound(mCoreThread*)), m_display, SLOT(forceDraw()));
143 connect(m_controller, &GameController::gamePaused, [this](mCoreThread* context) {
144 unsigned width, height;
145 context->core->desiredVideoDimensions(context->core, &width, &height);
146 QImage currentImage(reinterpret_cast<const uchar*>(m_controller->drawContext()), width, height,
147 width * BYTES_PER_PIXEL, QImage::Format_RGBX8888);
148 QPixmap pixmap;
149 pixmap.convertFromImage(currentImage);
150 m_screenWidget->setPixmap(pixmap);
151 m_screenWidget->setLockAspectRatio(width, height);
152 });
153 connect(m_controller, SIGNAL(gamePaused(mCoreThread*)), m_display, SLOT(pauseDrawing()));
154#ifndef Q_OS_MAC
155 connect(m_controller, SIGNAL(gamePaused(mCoreThread*)), menuBar(), SLOT(show()));
156 connect(m_controller, &GameController::gameUnpaused, [this]() {
157 if(isFullScreen()) {
158 menuBar()->hide();
159 }
160 });
161#endif
162 connect(m_controller, SIGNAL(gamePaused(mCoreThread*)), &m_inputController, SLOT(resumeScreensaver()));
163 connect(m_controller, SIGNAL(gameUnpaused(mCoreThread*)), m_display, SLOT(unpauseDrawing()));
164 connect(m_controller, SIGNAL(gameUnpaused(mCoreThread*)), &m_inputController, SLOT(suspendScreensaver()));
165 connect(m_controller, SIGNAL(postLog(int, int, const QString&)), &m_log, SLOT(postLog(int, int, const QString&)));
166 connect(m_controller, SIGNAL(frameAvailable(const uint32_t*)), this, SLOT(recordFrame()));
167 connect(m_controller, SIGNAL(frameAvailable(const uint32_t*)), m_display, SLOT(framePosted(const uint32_t*)));
168 connect(m_controller, SIGNAL(gameCrashed(const QString&)), this, SLOT(gameCrashed(const QString&)));
169 connect(m_controller, SIGNAL(gameFailed()), this, SLOT(gameFailed()));
170 connect(m_controller, SIGNAL(unimplementedBiosCall(int)), this, SLOT(unimplementedBiosCall(int)));
171 connect(m_controller, SIGNAL(statusPosted(const QString&)), m_display, SLOT(showMessage(const QString&)));
172 connect(&m_log, SIGNAL(levelsSet(int)), m_controller, SLOT(setLogLevel(int)));
173 connect(&m_log, SIGNAL(levelsEnabled(int)), m_controller, SLOT(enableLogLevel(int)));
174 connect(&m_log, SIGNAL(levelsDisabled(int)), m_controller, SLOT(disableLogLevel(int)));
175 connect(this, SIGNAL(startDrawing(mCoreThread*)), m_display, SLOT(startDrawing(mCoreThread*)), Qt::QueuedConnection);
176 connect(this, SIGNAL(shutdown()), m_display, SLOT(stopDrawing()));
177 connect(this, SIGNAL(shutdown()), m_controller, SLOT(closeGame()));
178 connect(this, SIGNAL(shutdown()), m_logView, SLOT(hide()));
179 connect(this, SIGNAL(shutdown()), m_shaderView, SLOT(hide()));
180 connect(this, SIGNAL(audioBufferSamplesChanged(int)), m_controller, SLOT(setAudioBufferSamples(int)));
181 connect(this, SIGNAL(sampleRateChanged(unsigned)), m_controller, SLOT(setAudioSampleRate(unsigned)));
182 connect(this, SIGNAL(fpsTargetChanged(float)), m_controller, SLOT(setFPSTarget(float)));
183 connect(&m_fpsTimer, SIGNAL(timeout()), this, SLOT(showFPS()));
184 connect(&m_focusCheck, SIGNAL(timeout()), this, SLOT(focusCheck()));
185 connect(m_display, &Display::hideCursor, [this]() {
186 if (static_cast<QStackedLayout*>(m_screenWidget->layout())->currentWidget() == m_display) {
187 m_screenWidget->setCursor(Qt::BlankCursor);
188 }
189 });
190 connect(m_display, &Display::showCursor, [this]() {
191 m_screenWidget->unsetCursor();
192 });
193 connect(&m_inputController, SIGNAL(profileLoaded(const QString&)), m_shortcutController, SLOT(loadProfile(const QString&)));
194
195 m_log.setLevels(mLOG_WARN | mLOG_ERROR | mLOG_FATAL);
196 m_fpsTimer.setInterval(FPS_TIMER_INTERVAL);
197 m_focusCheck.setInterval(200);
198
199 m_shortcutController->setConfigController(m_config);
200 setupMenu(menuBar());
201}
202
203Window::~Window() {
204 delete m_logView;
205
206#ifdef USE_FFMPEG
207 delete m_videoView;
208#endif
209
210#ifdef USE_MAGICK
211 delete m_gifView;
212#endif
213}
214
215void Window::argumentsPassed(mArguments* args) {
216 loadConfig();
217
218 if (args->patch) {
219 m_controller->loadPatch(args->patch);
220 }
221
222 if (args->fname) {
223 m_controller->loadGame(args->fname);
224 }
225
226#ifdef USE_GDB_STUB
227 if (args->debuggerType == DEBUGGER_GDB) {
228 if (!m_gdbController) {
229 m_gdbController = new GDBController(m_controller, this);
230 m_gdbController->listen();
231 }
232 }
233#endif
234}
235
236void Window::resizeFrame(const QSize& size) {
237 QSize newSize(size);
238#if (QT_VERSION >= QT_VERSION_CHECK(5, 6, 0))
239 newSize /= m_screenWidget->devicePixelRatioF();
240#endif
241 m_screenWidget->setSizeHint(newSize);
242 newSize -= m_screenWidget->size();
243 newSize += this->size();
244 resize(newSize);
245}
246
247void Window::setConfig(ConfigController* config) {
248 m_config = config;
249}
250
251void Window::loadConfig() {
252 const mCoreOptions* opts = m_config->options();
253 reloadConfig();
254
255 // TODO: Move these to ConfigController
256 if (opts->fpsTarget) {
257 emit fpsTargetChanged(opts->fpsTarget);
258 }
259
260 if (opts->audioBuffers) {
261 emit audioBufferSamplesChanged(opts->audioBuffers);
262 }
263
264 if (opts->sampleRate) {
265 emit sampleRateChanged(opts->sampleRate);
266 }
267
268 if (opts->width && opts->height) {
269 resizeFrame(QSize(opts->width, opts->height));
270 }
271
272 if (opts->fullscreen) {
273 enterFullScreen();
274 }
275
276 if (opts->shader) {
277 struct VDir* shader = VDirOpen(opts->shader);
278 if (shader) {
279 m_display->setShaders(shader);
280 m_shaderView->refreshShaders();
281 shader->close(shader);
282 }
283 }
284
285 m_mruFiles = m_config->getMRU();
286 updateMRU();
287
288 m_inputController.setConfiguration(m_config);
289 m_controller->setUseBIOS(opts->useBios);
290}
291
292void Window::reloadConfig() {
293 const mCoreOptions* opts = m_config->options();
294
295 m_log.setLevels(opts->logLevel);
296
297 QString saveStateExtdata = m_config->getOption("saveStateExtdata");
298 bool ok;
299 int flags = saveStateExtdata.toInt(&ok);
300 if (ok) {
301 m_controller->setSaveStateExtdata(flags);
302 }
303
304 QString loadStateExtdata = m_config->getOption("loadStateExtdata");
305 flags = loadStateExtdata.toInt(&ok);
306 if (ok) {
307 m_controller->setLoadStateExtdata(flags);
308 }
309
310 m_controller->setConfig(m_config->config());
311 m_display->lockAspectRatio(opts->lockAspectRatio);
312 m_display->filter(opts->resampleVideo);
313
314 m_inputController.setScreensaverSuspendable(opts->suspendScreensaver);
315}
316
317void Window::saveConfig() {
318 m_inputController.saveConfiguration();
319 m_config->write();
320}
321
322QString Window::getFilters() const {
323 QStringList filters;
324 QStringList formats;
325
326#ifdef M_CORE_GBA
327 QStringList gbaFormats{
328 "*.gba",
329#if defined(USE_LIBZIP) || defined(USE_ZLIB)
330 "*.zip",
331#endif
332#ifdef USE_LZMA
333 "*.7z",
334#endif
335 "*.agb",
336 "*.mb",
337 "*.rom",
338 "*.bin"};
339 formats.append(gbaFormats);
340 filters.append(tr("Game Boy Advance ROMs (%1)").arg(gbaFormats.join(QChar(' '))));
341#endif
342
343#ifdef M_CORE_DS
344 QStringList dsFormats{
345 "*.nds",
346#if defined(USE_LIBZIP) || defined(USE_ZLIB)
347 "*.zip",
348#endif
349#ifdef USE_LZMA
350 "*.7z",
351#endif
352 "*.rom",
353 "*.bin"};
354 formats.append(dsFormats);
355 filters.append(tr("DS ROMs (%1)").arg(gbaFormats.join(QChar(' '))));
356#endif
357
358#ifdef M_CORE_GB
359 QStringList gbFormats{
360 "*.gb",
361 "*.gbc",
362#if defined(USE_LIBZIP) || defined(USE_ZLIB)
363 "*.zip",
364#endif
365#ifdef USE_LZMA
366 "*.7z",
367#endif
368 "*.rom",
369 "*.bin"};
370 formats.append(gbFormats);
371 filters.append(tr("Game Boy ROMs (%1)").arg(gbFormats.join(QChar(' '))));
372#endif
373
374 formats.removeDuplicates();
375 filters.prepend(tr("All ROMs (%1)").arg(formats.join(QChar(' '))));
376 return filters.join(";;");
377}
378
379QString Window::getFiltersArchive() const {
380 QStringList filters;
381
382 QStringList formats{
383#if defined(USE_LIBZIP) || defined(USE_ZLIB)
384 "*.zip",
385#endif
386#ifdef USE_LZMA
387 "*.7z",
388#endif
389 };
390 filters.append(tr("Archives (%1)").arg(formats.join(QChar(' '))));
391 return filters.join(";;");
392}
393
394void Window::selectROM() {
395 QString filename = GBAApp::app()->getOpenFileName(this, tr("Select ROM"), getFilters());
396 if (!filename.isEmpty()) {
397 m_controller->loadGame(filename);
398 }
399}
400
401#ifdef USE_SQLITE3
402void Window::selectROMInArchive() {
403 QString filename = GBAApp::app()->getOpenFileName(this, tr("Select ROM"), getFiltersArchive());
404 if (filename.isEmpty()) {
405 return;
406 }
407 ArchiveInspector* archiveInspector = new ArchiveInspector(filename);
408 connect(archiveInspector, &QDialog::accepted, [this, archiveInspector]() {
409 VFile* output = archiveInspector->selectedVFile();
410 QPair<QString, QString> path = archiveInspector->selectedPath();
411 if (output) {
412 m_controller->loadGame(output, path.second, path.first);
413 }
414 archiveInspector->close();
415 });
416 archiveInspector->setAttribute(Qt::WA_DeleteOnClose);
417 archiveInspector->show();
418}
419
420void Window::addDirToLibrary() {
421 QString filename = GBAApp::app()->getOpenDirectoryName(this, tr("Select folder"));
422 if (filename.isEmpty()) {
423 return;
424 }
425 m_libraryView->addDirectory(filename);
426}
427#endif
428
429void Window::replaceROM() {
430 QString filename = GBAApp::app()->getOpenFileName(this, tr("Select ROM"), getFilters());
431 if (!filename.isEmpty()) {
432 m_controller->replaceGame(filename);
433 }
434}
435
436void Window::selectSave(bool temporary) {
437 QStringList formats{"*.sav"};
438 QString filter = tr("Game Boy Advance save files (%1)").arg(formats.join(QChar(' ')));
439 QString filename = GBAApp::app()->getOpenFileName(this, tr("Select save"), filter);
440 if (!filename.isEmpty()) {
441 m_controller->loadSave(filename, temporary);
442 }
443}
444
445void Window::multiplayerChanged() {
446 int attached = 1;
447 MultiplayerController* multiplayer = m_controller->multiplayerController();
448 if (multiplayer) {
449 attached = multiplayer->attached();
450 }
451 if (m_controller->isLoaded()) {
452 for (QAction* action : m_nonMpActions) {
453 action->setDisabled(attached > 1);
454 }
455 }
456}
457
458void Window::selectPatch() {
459 QString filename = GBAApp::app()->getOpenFileName(this, tr("Select patch"), tr("Patches (*.ips *.ups *.bps)"));
460 if (!filename.isEmpty()) {
461 m_controller->loadPatch(filename);
462 }
463}
464
465void Window::openView(QWidget* widget) {
466 connect(this, SIGNAL(shutdown()), widget, SLOT(close()));
467 widget->setAttribute(Qt::WA_DeleteOnClose);
468 widget->show();
469}
470
471void Window::importSharkport() {
472 QString filename = GBAApp::app()->getOpenFileName(this, tr("Select save"), tr("GameShark saves (*.sps *.xps)"));
473 if (!filename.isEmpty()) {
474 m_controller->importSharkport(filename);
475 }
476}
477
478void Window::exportSharkport() {
479 QString filename = GBAApp::app()->getSaveFileName(this, tr("Select save"), tr("GameShark saves (*.sps *.xps)"));
480 if (!filename.isEmpty()) {
481 m_controller->exportSharkport(filename);
482 }
483}
484
485void Window::openSettingsWindow() {
486 SettingsView* settingsWindow = new SettingsView(m_config, &m_inputController, m_shortcutController);
487 connect(settingsWindow, SIGNAL(biosLoaded(int, const QString&)), m_controller, SLOT(loadBIOS(int, const QString&)));
488 connect(settingsWindow, SIGNAL(audioDriverChanged()), m_controller, SLOT(reloadAudioDriver()));
489 connect(settingsWindow, SIGNAL(displayDriverChanged()), this, SLOT(mustRestart()));
490 connect(settingsWindow, SIGNAL(pathsChanged()), this, SLOT(reloadConfig()));
491 openView(settingsWindow);
492}
493
494void Window::openAboutScreen() {
495 AboutScreen* about = new AboutScreen();
496 openView(about);
497}
498
499template <typename T, typename A>
500std::function<void()> Window::openTView(A arg) {
501 return [=]() {
502 T* view = new T(m_controller, arg);
503 openView(view);
504 };
505}
506
507template <typename T>
508std::function<void()> Window::openTView() {
509 return [=]() {
510 T* view = new T(m_controller);
511 openView(view);
512 };
513}
514
515#ifdef USE_FFMPEG
516void Window::openVideoWindow() {
517 if (!m_videoView) {
518 m_videoView = new VideoView();
519 connect(m_videoView, SIGNAL(recordingStarted(mAVStream*)), m_controller, SLOT(setAVStream(mAVStream*)));
520 connect(m_videoView, SIGNAL(recordingStopped()), m_controller, SLOT(clearAVStream()), Qt::DirectConnection);
521 connect(m_controller, SIGNAL(gameStopped(mCoreThread*)), m_videoView, SLOT(stopRecording()));
522 connect(m_controller, SIGNAL(gameStopped(mCoreThread*)), m_videoView, SLOT(close()));
523 connect(m_controller, &GameController::gameStarted, [this]() {
524 m_videoView->setNativeResolution(m_controller->screenDimensions());
525 });
526 if (m_controller->isLoaded()) {
527 m_videoView->setNativeResolution(m_controller->screenDimensions());
528 }
529 connect(this, SIGNAL(shutdown()), m_videoView, SLOT(close()));
530 }
531 m_videoView->show();
532}
533#endif
534
535#ifdef USE_MAGICK
536void Window::openGIFWindow() {
537 if (!m_gifView) {
538 m_gifView = new GIFView();
539 connect(m_gifView, SIGNAL(recordingStarted(mAVStream*)), m_controller, SLOT(setAVStream(mAVStream*)));
540 connect(m_gifView, SIGNAL(recordingStopped()), m_controller, SLOT(clearAVStream()), Qt::DirectConnection);
541 connect(m_controller, SIGNAL(gameStopped(mCoreThread*)), m_gifView, SLOT(stopRecording()));
542 connect(m_controller, SIGNAL(gameStopped(mCoreThread*)), m_gifView, SLOT(close()));
543 connect(this, SIGNAL(shutdown()), m_gifView, SLOT(close()));
544 }
545 m_gifView->show();
546}
547#endif
548
549#ifdef USE_GDB_STUB
550void Window::gdbOpen() {
551 if (!m_gdbController) {
552 m_gdbController = new GDBController(m_controller, this);
553 }
554 GDBWindow* window = new GDBWindow(m_gdbController);
555 openView(window);
556}
557#endif
558
559#ifdef USE_DEBUGGERS
560void Window::consoleOpen() {
561 if (!m_console) {
562 m_console = new DebuggerConsoleController(m_controller, this);
563 }
564 DebuggerConsole* window = new DebuggerConsole(m_console);
565 openView(window);
566}
567#endif
568
569void Window::keyPressEvent(QKeyEvent* event) {
570 if (event->isAutoRepeat()) {
571 QWidget::keyPressEvent(event);
572 return;
573 }
574 GBAKey key = m_inputController.mapKeyboard(event->key());
575 if (key == GBA_KEY_NONE) {
576 QWidget::keyPressEvent(event);
577 return;
578 }
579 m_controller->keyPressed(key);
580 event->accept();
581}
582
583void Window::keyReleaseEvent(QKeyEvent* event) {
584 if (event->isAutoRepeat()) {
585 QWidget::keyReleaseEvent(event);
586 return;
587 }
588 GBAKey key = m_inputController.mapKeyboard(event->key());
589 if (key == GBA_KEY_NONE) {
590 QWidget::keyPressEvent(event);
591 return;
592 }
593 m_controller->keyReleased(key);
594 event->accept();
595}
596
597void Window::resizeEvent(QResizeEvent* event) {
598 if (!isFullScreen()) {
599 m_config->setOption("height", m_screenWidget->height());
600 m_config->setOption("width", m_screenWidget->width());
601 }
602
603 int factor = 0;
604 QSize size(VIDEO_HORIZONTAL_PIXELS, VIDEO_VERTICAL_PIXELS);
605 if (m_controller->isLoaded()) {
606 size = m_controller->screenDimensions();
607 }
608 if (m_screenWidget->width() % size.width() == 0 && m_screenWidget->height() % size.height() == 0 &&
609 m_screenWidget->width() / size.width() == m_screenWidget->height() / size.height()) {
610 factor = m_screenWidget->width() / size.width();
611 } else {
612 m_savedScale = 0;
613 }
614 for (QMap<int, QAction*>::iterator iter = m_frameSizes.begin(); iter != m_frameSizes.end(); ++iter) {
615 bool enableSignals = iter.value()->blockSignals(true);
616 iter.value()->setChecked(iter.key() == factor);
617 iter.value()->blockSignals(enableSignals);
618 }
619
620 m_config->setOption("fullscreen", isFullScreen());
621}
622
623void Window::showEvent(QShowEvent* event) {
624 if (m_wasOpened) {
625 return;
626 }
627 m_wasOpened = true;
628 resizeFrame(m_screenWidget->sizeHint());
629 QVariant windowPos = m_config->getQtOption("windowPos");
630 if (!windowPos.isNull()) {
631 move(windowPos.toPoint());
632 } else {
633 QRect rect = frameGeometry();
634 rect.moveCenter(QApplication::desktop()->availableGeometry().center());
635 move(rect.topLeft());
636 }
637 if (m_fullscreenOnStart) {
638 enterFullScreen();
639 m_fullscreenOnStart = false;
640 }
641}
642
643void Window::closeEvent(QCloseEvent* event) {
644 emit shutdown();
645 m_config->setQtOption("windowPos", pos());
646
647 if (m_savedScale > 0) {
648 m_config->setOption("height", VIDEO_VERTICAL_PIXELS * m_savedScale);
649 m_config->setOption("width", VIDEO_HORIZONTAL_PIXELS * m_savedScale);
650 }
651 saveConfig();
652 QMainWindow::closeEvent(event);
653}
654
655void Window::focusInEvent(QFocusEvent*) {
656 m_display->forceDraw();
657}
658
659void Window::focusOutEvent(QFocusEvent*) {
660 m_controller->setTurbo(false, false);
661 m_controller->stopRewinding();
662 m_controller->clearKeys();
663}
664
665void Window::dragEnterEvent(QDragEnterEvent* event) {
666 if (event->mimeData()->hasFormat("text/uri-list")) {
667 event->acceptProposedAction();
668 }
669}
670
671void Window::dropEvent(QDropEvent* event) {
672 QString uris = event->mimeData()->data("text/uri-list");
673 uris = uris.trimmed();
674 if (uris.contains("\n")) {
675 // Only one file please
676 return;
677 }
678 QUrl url(uris);
679 if (!url.isLocalFile()) {
680 // No remote loading
681 return;
682 }
683 event->accept();
684 m_controller->loadGame(url.toLocalFile());
685}
686
687void Window::mouseDoubleClickEvent(QMouseEvent* event) {
688 if (event->button() != Qt::LeftButton) {
689 return;
690 }
691 toggleFullScreen();
692}
693
694void Window::enterFullScreen() {
695 if (!isVisible()) {
696 m_fullscreenOnStart = true;
697 return;
698 }
699 if (isFullScreen()) {
700 return;
701 }
702 showFullScreen();
703#ifndef Q_OS_MAC
704 if (m_controller->isLoaded() && !m_controller->isPaused()) {
705 menuBar()->hide();
706 }
707#endif
708}
709
710void Window::exitFullScreen() {
711 if (!isFullScreen()) {
712 return;
713 }
714 m_screenWidget->unsetCursor();
715 menuBar()->show();
716 showNormal();
717}
718
719void Window::toggleFullScreen() {
720 if (isFullScreen()) {
721 exitFullScreen();
722 } else {
723 enterFullScreen();
724 }
725}
726
727void Window::gameStarted(mCoreThread* context, const QString& fname) {
728 MutexLock(&context->stateMutex);
729 if (context->state < THREAD_EXITING) {
730 emit startDrawing(context);
731 } else {
732 MutexUnlock(&context->stateMutex);
733 return;
734 }
735 MutexUnlock(&context->stateMutex);
736 foreach (QAction* action, m_gameActions) {
737 action->setDisabled(false);
738 }
739#ifdef M_CORE_GBA
740 foreach (QAction* action, m_gbaActions) {
741 action->setDisabled(context->core->platform(context->core) != PLATFORM_GBA);
742 }
743#endif
744 multiplayerChanged();
745 if (!fname.isEmpty()) {
746 setWindowFilePath(fname);
747 appendMRU(fname);
748 }
749 updateTitle();
750 unsigned width, height;
751 context->core->desiredVideoDimensions(context->core, &width, &height);
752 m_display->setMinimumSize(width, height);
753 m_screenWidget->setMinimumSize(m_display->minimumSize());
754 if (m_savedScale > 0) {
755 resizeFrame(QSize(width, height) * m_savedScale);
756 }
757 attachWidget(m_display);
758
759#ifndef Q_OS_MAC
760 if (isFullScreen()) {
761 menuBar()->hide();
762 }
763#endif
764
765 m_hitUnimplementedBiosCall = false;
766 m_fpsTimer.start();
767 m_focusCheck.start();
768}
769
770void Window::gameStopped() {
771#ifdef M_CORE_GBA
772 foreach (QAction* action, m_gbaActions) {
773 action->setDisabled(false);
774 }
775#endif
776 foreach (QAction* action, m_gameActions) {
777 action->setDisabled(true);
778 }
779 setWindowFilePath(QString());
780 updateTitle();
781 detachWidget(m_display);
782 m_screenWidget->setLockAspectRatio(m_logo.width(), m_logo.height());
783 m_screenWidget->setPixmap(m_logo);
784 m_screenWidget->unsetCursor();
785#ifdef M_CORE_GB
786 m_display->setMinimumSize(GB_VIDEO_HORIZONTAL_PIXELS, GB_VIDEO_VERTICAL_PIXELS);
787#elif defined(M_CORE_GBA)
788 m_display->setMinimumSize(VIDEO_HORIZONTAL_PIXELS, VIDEO_VERTICAL_PIXELS);
789#endif
790 m_screenWidget->setMinimumSize(m_display->minimumSize());
791
792 m_fpsTimer.stop();
793 m_focusCheck.stop();
794}
795
796void Window::gameCrashed(const QString& errorMessage) {
797 QMessageBox* crash = new QMessageBox(QMessageBox::Critical, tr("Crash"),
798 tr("The game has crashed with the following error:\n\n%1").arg(errorMessage),
799 QMessageBox::Ok, this, Qt::Sheet);
800 crash->setAttribute(Qt::WA_DeleteOnClose);
801 crash->show();
802}
803
804void Window::gameFailed() {
805 QMessageBox* fail = new QMessageBox(QMessageBox::Warning, tr("Couldn't Load"),
806 tr("Could not load game. Are you sure it's in the correct format?"),
807 QMessageBox::Ok, this, Qt::Sheet);
808 fail->setAttribute(Qt::WA_DeleteOnClose);
809 fail->show();
810}
811
812void Window::unimplementedBiosCall(int call) {
813 if (m_hitUnimplementedBiosCall) {
814 return;
815 }
816 m_hitUnimplementedBiosCall = true;
817
818 QMessageBox* fail = new QMessageBox(
819 QMessageBox::Warning, tr("Unimplemented BIOS call"),
820 tr("This game uses a BIOS call that is not implemented. Please use the official BIOS for best experience."),
821 QMessageBox::Ok, this, Qt::Sheet);
822 fail->setAttribute(Qt::WA_DeleteOnClose);
823 fail->show();
824}
825
826void Window::tryMakePortable() {
827 QMessageBox* confirm = new QMessageBox(QMessageBox::Question, tr("Really make portable?"),
828 tr("This will make the emulator load its configuration from the same directory as the executable. Do you want to continue?"),
829 QMessageBox::Yes | QMessageBox::Cancel, this, Qt::Sheet);
830 confirm->setAttribute(Qt::WA_DeleteOnClose);
831 connect(confirm->button(QMessageBox::Yes), SIGNAL(clicked()), m_config, SLOT(makePortable()));
832 confirm->show();
833}
834
835void Window::mustRestart() {
836 QMessageBox* dialog = new QMessageBox(QMessageBox::Warning, tr("Restart needed"),
837 tr("Some changes will not take effect until the emulator is restarted."),
838 QMessageBox::Ok, this, Qt::Sheet);
839 dialog->setAttribute(Qt::WA_DeleteOnClose);
840 dialog->show();
841}
842
843void Window::recordFrame() {
844 m_frameList.append(QDateTime::currentDateTime());
845 while (m_frameList.count() > FRAME_LIST_SIZE) {
846 m_frameList.removeFirst();
847 }
848}
849
850void Window::showFPS() {
851 if (m_frameList.isEmpty()) {
852 updateTitle();
853 return;
854 }
855 qint64 interval = m_frameList.first().msecsTo(m_frameList.last());
856 float fps = (m_frameList.count() - 1) * 10000.f / interval;
857 fps = round(fps) / 10.f;
858 updateTitle(fps);
859}
860
861void Window::updateTitle(float fps) {
862 QString title;
863
864 m_controller->threadInterrupt();
865 if (m_controller->isLoaded()) {
866 const NoIntroDB* db = GBAApp::app()->gameDB();
867 NoIntroGame game{};
868 uint32_t crc32 = 0;
869 m_controller->thread()->core->checksum(m_controller->thread()->core, &crc32, CHECKSUM_CRC32);
870
871 char gameTitle[17] = { '\0' };
872 mCore* core = m_controller->thread()->core;
873 core->getGameTitle(core, gameTitle);
874 title = gameTitle;
875
876#ifdef USE_SQLITE3
877 if (db && crc32 && NoIntroDBLookupGameByCRC(db, crc32, &game)) {
878 title = QLatin1String(game.name);
879 }
880#endif
881 }
882 MultiplayerController* multiplayer = m_controller->multiplayerController();
883 if (multiplayer && multiplayer->attached() > 1) {
884 title += tr(" - Player %1 of %2").arg(multiplayer->playerId(m_controller) + 1).arg(multiplayer->attached());
885 for (QAction* action : m_nonMpActions) {
886 action->setDisabled(true);
887 }
888 } else if (m_controller->isLoaded()) {
889 for (QAction* action : m_nonMpActions) {
890 action->setDisabled(false);
891 }
892 }
893 m_controller->threadContinue();
894 if (title.isNull()) {
895 setWindowTitle(tr("%1 - %2").arg(projectName).arg(projectVersion));
896 } else if (fps < 0) {
897 setWindowTitle(tr("%1 - %2 - %3").arg(projectName).arg(title).arg(projectVersion));
898 } else {
899 setWindowTitle(tr("%1 - %2 (%3 fps) - %4").arg(projectName).arg(title).arg(fps).arg(projectVersion));
900 }
901}
902
903void Window::openStateWindow(LoadSave ls) {
904 if (m_stateWindow) {
905 return;
906 }
907 MultiplayerController* multiplayer = m_controller->multiplayerController();
908 if (multiplayer && multiplayer->attached() > 1) {
909 return;
910 }
911 bool wasPaused = m_controller->isPaused();
912 m_stateWindow = new LoadSaveState(m_controller);
913 connect(this, SIGNAL(shutdown()), m_stateWindow, SLOT(close()));
914 connect(m_controller, SIGNAL(gameStopped(mCoreThread*)), m_stateWindow, SLOT(close()));
915 connect(m_stateWindow, &LoadSaveState::closed, [this]() {
916 detachWidget(m_stateWindow);
917 m_stateWindow = nullptr;
918 QMetaObject::invokeMethod(this, "setFocus", Qt::QueuedConnection);
919 });
920 if (!wasPaused) {
921 m_controller->setPaused(true);
922 connect(m_stateWindow, &LoadSaveState::closed, [this]() { m_controller->setPaused(false); });
923 }
924 m_stateWindow->setAttribute(Qt::WA_DeleteOnClose);
925 m_stateWindow->setMode(ls);
926 attachWidget(m_stateWindow);
927}
928
929void Window::setupMenu(QMenuBar* menubar) {
930 menubar->clear();
931 QMenu* fileMenu = menubar->addMenu(tr("&File"));
932 m_shortcutController->addMenu(fileMenu);
933 installEventFilter(m_shortcutController);
934 addControlledAction(fileMenu, fileMenu->addAction(tr("Load &ROM..."), this, SLOT(selectROM()), QKeySequence::Open),
935 "loadROM");
936#ifdef USE_SQLITE3
937 addControlledAction(fileMenu, fileMenu->addAction(tr("Load ROM in archive..."), this, SLOT(selectROMInArchive())),
938 "loadROMInArchive");
939 addControlledAction(fileMenu, fileMenu->addAction(tr("Add folder to library..."), this, SLOT(addDirToLibrary())),
940 "addDirToLibrary");
941#endif
942
943 QAction* loadTemporarySave = new QAction(tr("Load temporary save..."), fileMenu);
944 connect(loadTemporarySave, &QAction::triggered, [this]() { this->selectSave(true); });
945 m_gameActions.append(loadTemporarySave);
946 addControlledAction(fileMenu, loadTemporarySave, "loadTemporarySave");
947
948 addControlledAction(fileMenu, fileMenu->addAction(tr("Load &patch..."), this, SLOT(selectPatch())), "loadPatch");
949
950 QAction* bootBIOS = new QAction(tr("Boot BIOS"), fileMenu);
951 connect(bootBIOS, &QAction::triggered, [this]() {
952 m_controller->loadBIOS(PLATFORM_GBA, m_config->getOption("gba.bios"));
953 m_controller->bootBIOS();
954 });
955 addControlledAction(fileMenu, bootBIOS, "bootBIOS");
956
957 addControlledAction(fileMenu, fileMenu->addAction(tr("Replace ROM..."), this, SLOT(replaceROM())), "replaceROM");
958
959 QAction* romInfo = new QAction(tr("ROM &info..."), fileMenu);
960 connect(romInfo, &QAction::triggered, openTView<ROMInfo>());
961 m_gameActions.append(romInfo);
962 addControlledAction(fileMenu, romInfo, "romInfo");
963
964 m_mruMenu = fileMenu->addMenu(tr("Recent"));
965
966 fileMenu->addSeparator();
967
968 addControlledAction(fileMenu, fileMenu->addAction(tr("Make portable"), this, SLOT(tryMakePortable())), "makePortable");
969
970 fileMenu->addSeparator();
971
972 QAction* loadState = new QAction(tr("&Load state"), fileMenu);
973 loadState->setShortcut(tr("F10"));
974 connect(loadState, &QAction::triggered, [this]() { this->openStateWindow(LoadSave::LOAD); });
975 m_gameActions.append(loadState);
976 m_nonMpActions.append(loadState);
977 addControlledAction(fileMenu, loadState, "loadState");
978
979 QAction* saveState = new QAction(tr("&Save state"), fileMenu);
980 saveState->setShortcut(tr("Shift+F10"));
981 connect(saveState, &QAction::triggered, [this]() { this->openStateWindow(LoadSave::SAVE); });
982 m_gameActions.append(saveState);
983 m_nonMpActions.append(saveState);
984 addControlledAction(fileMenu, saveState, "saveState");
985
986 QMenu* quickLoadMenu = fileMenu->addMenu(tr("Quick load"));
987 QMenu* quickSaveMenu = fileMenu->addMenu(tr("Quick save"));
988 m_shortcutController->addMenu(quickLoadMenu);
989 m_shortcutController->addMenu(quickSaveMenu);
990
991 QAction* quickLoad = new QAction(tr("Load recent"), quickLoadMenu);
992 connect(quickLoad, SIGNAL(triggered()), m_controller, SLOT(loadState()));
993 m_gameActions.append(quickLoad);
994 m_nonMpActions.append(quickLoad);
995 addControlledAction(quickLoadMenu, quickLoad, "quickLoad");
996
997 QAction* quickSave = new QAction(tr("Save recent"), quickSaveMenu);
998 connect(quickSave, SIGNAL(triggered()), m_controller, SLOT(saveState()));
999 m_gameActions.append(quickSave);
1000 m_nonMpActions.append(quickSave);
1001 addControlledAction(quickSaveMenu, quickSave, "quickSave");
1002
1003 quickLoadMenu->addSeparator();
1004 quickSaveMenu->addSeparator();
1005
1006 QAction* undoLoadState = new QAction(tr("Undo load state"), quickLoadMenu);
1007 undoLoadState->setShortcut(tr("F11"));
1008 connect(undoLoadState, SIGNAL(triggered()), m_controller, SLOT(loadBackupState()));
1009 m_gameActions.append(undoLoadState);
1010 m_nonMpActions.append(undoLoadState);
1011 addControlledAction(quickLoadMenu, undoLoadState, "undoLoadState");
1012
1013 QAction* undoSaveState = new QAction(tr("Undo save state"), quickSaveMenu);
1014 undoSaveState->setShortcut(tr("Shift+F11"));
1015 connect(undoSaveState, SIGNAL(triggered()), m_controller, SLOT(saveBackupState()));
1016 m_gameActions.append(undoSaveState);
1017 m_nonMpActions.append(undoSaveState);
1018 addControlledAction(quickSaveMenu, undoSaveState, "undoSaveState");
1019
1020 quickLoadMenu->addSeparator();
1021 quickSaveMenu->addSeparator();
1022
1023 int i;
1024 for (i = 1; i < 10; ++i) {
1025 quickLoad = new QAction(tr("State &%1").arg(i), quickLoadMenu);
1026 quickLoad->setShortcut(tr("F%1").arg(i));
1027 connect(quickLoad, &QAction::triggered, [this, i]() { m_controller->loadState(i); });
1028 m_gameActions.append(quickLoad);
1029 m_nonMpActions.append(quickLoad);
1030 addControlledAction(quickLoadMenu, quickLoad, QString("quickLoad.%1").arg(i));
1031
1032 quickSave = new QAction(tr("State &%1").arg(i), quickSaveMenu);
1033 quickSave->setShortcut(tr("Shift+F%1").arg(i));
1034 connect(quickSave, &QAction::triggered, [this, i]() { m_controller->saveState(i); });
1035 m_gameActions.append(quickSave);
1036 m_nonMpActions.append(quickSave);
1037 addControlledAction(quickSaveMenu, quickSave, QString("quickSave.%1").arg(i));
1038 }
1039
1040#ifdef M_CORE_GBA
1041 fileMenu->addSeparator();
1042 QAction* importShark = new QAction(tr("Import GameShark Save"), fileMenu);
1043 connect(importShark, SIGNAL(triggered()), this, SLOT(importSharkport()));
1044 m_gameActions.append(importShark);
1045 m_gbaActions.append(importShark);
1046 addControlledAction(fileMenu, importShark, "importShark");
1047
1048 QAction* exportShark = new QAction(tr("Export GameShark Save"), fileMenu);
1049 connect(exportShark, SIGNAL(triggered()), this, SLOT(exportSharkport()));
1050 m_gameActions.append(exportShark);
1051 m_gbaActions.append(exportShark);
1052 addControlledAction(fileMenu, exportShark, "exportShark");
1053#endif
1054
1055 fileMenu->addSeparator();
1056 QAction* multiWindow = new QAction(tr("New multiplayer window"), fileMenu);
1057 connect(multiWindow, &QAction::triggered, [this]() {
1058 GBAApp::app()->newWindow();
1059 });
1060 addControlledAction(fileMenu, multiWindow, "multiWindow");
1061
1062#ifndef Q_OS_MAC
1063 fileMenu->addSeparator();
1064#endif
1065
1066 QAction* about = new QAction(tr("About"), fileMenu);
1067 connect(about, SIGNAL(triggered()), this, SLOT(openAboutScreen()));
1068 fileMenu->addAction(about);
1069
1070#ifndef Q_OS_MAC
1071 addControlledAction(fileMenu, fileMenu->addAction(tr("E&xit"), this, SLOT(close()), QKeySequence::Quit), "quit");
1072#endif
1073
1074 QMenu* emulationMenu = menubar->addMenu(tr("&Emulation"));
1075 m_shortcutController->addMenu(emulationMenu);
1076 QAction* reset = new QAction(tr("&Reset"), emulationMenu);
1077 reset->setShortcut(tr("Ctrl+R"));
1078 connect(reset, SIGNAL(triggered()), m_controller, SLOT(reset()));
1079 m_gameActions.append(reset);
1080 addControlledAction(emulationMenu, reset, "reset");
1081
1082 QAction* shutdown = new QAction(tr("Sh&utdown"), emulationMenu);
1083 connect(shutdown, SIGNAL(triggered()), m_controller, SLOT(closeGame()));
1084 m_gameActions.append(shutdown);
1085 addControlledAction(emulationMenu, shutdown, "shutdown");
1086
1087#ifdef M_CORE_GBA
1088 QAction* yank = new QAction(tr("Yank game pak"), emulationMenu);
1089 connect(yank, SIGNAL(triggered()), m_controller, SLOT(yankPak()));
1090 m_gameActions.append(yank);
1091 m_gbaActions.append(yank);
1092 addControlledAction(emulationMenu, yank, "yank");
1093#endif
1094 emulationMenu->addSeparator();
1095
1096 QAction* pause = new QAction(tr("&Pause"), emulationMenu);
1097 pause->setChecked(false);
1098 pause->setCheckable(true);
1099 pause->setShortcut(tr("Ctrl+P"));
1100 connect(pause, SIGNAL(triggered(bool)), m_controller, SLOT(setPaused(bool)));
1101 connect(m_controller, &GameController::gamePaused, [this, pause]() {
1102 pause->setChecked(true);
1103 });
1104 connect(m_controller, &GameController::gameUnpaused, [pause]() { pause->setChecked(false); });
1105 m_gameActions.append(pause);
1106 addControlledAction(emulationMenu, pause, "pause");
1107
1108 QAction* frameAdvance = new QAction(tr("&Next frame"), emulationMenu);
1109 frameAdvance->setShortcut(tr("Ctrl+N"));
1110 connect(frameAdvance, SIGNAL(triggered()), m_controller, SLOT(frameAdvance()));
1111 m_gameActions.append(frameAdvance);
1112 addControlledAction(emulationMenu, frameAdvance, "frameAdvance");
1113
1114 emulationMenu->addSeparator();
1115
1116 m_shortcutController->addFunctions(emulationMenu, [this]() {
1117 m_controller->setTurbo(true, false);
1118 }, [this]() {
1119 m_controller->setTurbo(false, false);
1120 }, QKeySequence(Qt::Key_Tab), tr("Fast forward (held)"), "holdFastForward");
1121
1122 QAction* turbo = new QAction(tr("&Fast forward"), emulationMenu);
1123 turbo->setCheckable(true);
1124 turbo->setChecked(false);
1125 turbo->setShortcut(tr("Shift+Tab"));
1126 connect(turbo, SIGNAL(triggered(bool)), m_controller, SLOT(setTurbo(bool)));
1127 addControlledAction(emulationMenu, turbo, "fastForward");
1128
1129 QMenu* ffspeedMenu = emulationMenu->addMenu(tr("Fast forward speed"));
1130 ConfigOption* ffspeed = m_config->addOption("fastForwardRatio");
1131 ffspeed->connect([this](const QVariant& value) {
1132 m_controller->setTurboSpeed(value.toFloat());
1133 }, this);
1134 ffspeed->addValue(tr("Unbounded"), -1.0f, ffspeedMenu);
1135 ffspeed->setValue(QVariant(-1.0f));
1136 ffspeedMenu->addSeparator();
1137 for (i = 2; i < 11; ++i) {
1138 ffspeed->addValue(tr("%0x").arg(i), i, ffspeedMenu);
1139 }
1140 m_config->updateOption("fastForwardRatio");
1141
1142 m_shortcutController->addFunctions(emulationMenu, [this]() {
1143 m_controller->startRewinding();
1144 }, [this]() {
1145 m_controller->stopRewinding();
1146 }, QKeySequence("`"), tr("Rewind (held)"), "holdRewind");
1147
1148 QAction* rewind = new QAction(tr("Re&wind"), emulationMenu);
1149 rewind->setShortcut(tr("~"));
1150 connect(rewind, SIGNAL(triggered()), m_controller, SLOT(rewind()));
1151 m_gameActions.append(rewind);
1152 m_nonMpActions.append(rewind);
1153 addControlledAction(emulationMenu, rewind, "rewind");
1154
1155 QAction* frameRewind = new QAction(tr("Step backwards"), emulationMenu);
1156 frameRewind->setShortcut(tr("Ctrl+B"));
1157 connect(frameRewind, &QAction::triggered, [this] () {
1158 m_controller->rewind(1);
1159 });
1160 m_gameActions.append(frameRewind);
1161 m_nonMpActions.append(frameRewind);
1162 addControlledAction(emulationMenu, frameRewind, "frameRewind");
1163
1164 ConfigOption* videoSync = m_config->addOption("videoSync");
1165 videoSync->addBoolean(tr("Sync to &video"), emulationMenu);
1166 videoSync->connect([this](const QVariant& value) {
1167 reloadConfig();
1168 }, this);
1169 m_config->updateOption("videoSync");
1170
1171 ConfigOption* audioSync = m_config->addOption("audioSync");
1172 audioSync->addBoolean(tr("Sync to &audio"), emulationMenu);
1173 audioSync->connect([this](const QVariant& value) {
1174 reloadConfig();
1175 }, this);
1176 m_config->updateOption("audioSync");
1177
1178 emulationMenu->addSeparator();
1179
1180 QMenu* solarMenu = emulationMenu->addMenu(tr("Solar sensor"));
1181 m_shortcutController->addMenu(solarMenu);
1182 QAction* solarIncrease = new QAction(tr("Increase solar level"), solarMenu);
1183 connect(solarIncrease, SIGNAL(triggered()), m_controller, SLOT(increaseLuminanceLevel()));
1184 addControlledAction(solarMenu, solarIncrease, "increaseLuminanceLevel");
1185
1186 QAction* solarDecrease = new QAction(tr("Decrease solar level"), solarMenu);
1187 connect(solarDecrease, SIGNAL(triggered()), m_controller, SLOT(decreaseLuminanceLevel()));
1188 addControlledAction(solarMenu, solarDecrease, "decreaseLuminanceLevel");
1189
1190 QAction* maxSolar = new QAction(tr("Brightest solar level"), solarMenu);
1191 connect(maxSolar, &QAction::triggered, [this]() { m_controller->setLuminanceLevel(10); });
1192 addControlledAction(solarMenu, maxSolar, "maxLuminanceLevel");
1193
1194 QAction* minSolar = new QAction(tr("Darkest solar level"), solarMenu);
1195 connect(minSolar, &QAction::triggered, [this]() { m_controller->setLuminanceLevel(0); });
1196 addControlledAction(solarMenu, minSolar, "minLuminanceLevel");
1197
1198 solarMenu->addSeparator();
1199 for (int i = 0; i <= 10; ++i) {
1200 QAction* setSolar = new QAction(tr("Brightness %1").arg(QString::number(i)), solarMenu);
1201 connect(setSolar, &QAction::triggered, [this, i]() {
1202 m_controller->setLuminanceLevel(i);
1203 });
1204 addControlledAction(solarMenu, setSolar, QString("luminanceLevel.%1").arg(QString::number(i)));
1205 }
1206
1207 QMenu* avMenu = menubar->addMenu(tr("Audio/&Video"));
1208 m_shortcutController->addMenu(avMenu);
1209 QMenu* frameMenu = avMenu->addMenu(tr("Frame size"));
1210 m_shortcutController->addMenu(frameMenu, avMenu);
1211 for (int i = 1; i <= 6; ++i) {
1212 QAction* setSize = new QAction(tr("%1x").arg(QString::number(i)), avMenu);
1213 setSize->setCheckable(true);
1214 if (m_savedScale == i) {
1215 setSize->setChecked(true);
1216 }
1217 connect(setSize, &QAction::triggered, [this, i, setSize]() {
1218 showNormal();
1219 QSize size(VIDEO_HORIZONTAL_PIXELS, VIDEO_VERTICAL_PIXELS);
1220 if (m_controller->isLoaded()) {
1221 size = m_controller->screenDimensions();
1222 }
1223 size *= i;
1224 m_savedScale = i;
1225 m_config->setOption("scaleMultiplier", i); // TODO: Port to other
1226 resizeFrame(size);
1227 bool enableSignals = setSize->blockSignals(true);
1228 setSize->setChecked(true);
1229 setSize->blockSignals(enableSignals);
1230 });
1231 m_frameSizes[i] = setSize;
1232 addControlledAction(frameMenu, setSize, QString("frame%1x").arg(QString::number(i)));
1233 }
1234 QKeySequence fullscreenKeys;
1235#ifdef Q_OS_WIN
1236 fullscreenKeys = QKeySequence("Alt+Return");
1237#else
1238 fullscreenKeys = QKeySequence("Ctrl+F");
1239#endif
1240 addControlledAction(frameMenu, frameMenu->addAction(tr("Toggle fullscreen"), this, SLOT(toggleFullScreen()), fullscreenKeys), "fullscreen");
1241
1242 ConfigOption* lockAspectRatio = m_config->addOption("lockAspectRatio");
1243 lockAspectRatio->addBoolean(tr("Lock aspect ratio"), avMenu);
1244 lockAspectRatio->connect([this](const QVariant& value) {
1245 m_display->lockAspectRatio(value.toBool());
1246 }, this);
1247 m_config->updateOption("lockAspectRatio");
1248
1249 ConfigOption* resampleVideo = m_config->addOption("resampleVideo");
1250 resampleVideo->addBoolean(tr("Resample video"), avMenu);
1251 resampleVideo->connect([this](const QVariant& value) {
1252 m_display->filter(value.toBool());
1253 }, this);
1254 m_config->updateOption("resampleVideo");
1255
1256 QMenu* skipMenu = avMenu->addMenu(tr("Frame&skip"));
1257 ConfigOption* skip = m_config->addOption("frameskip");
1258 skip->connect([this](const QVariant& value) {
1259 reloadConfig();
1260 }, this);
1261 for (int i = 0; i <= 10; ++i) {
1262 skip->addValue(QString::number(i), i, skipMenu);
1263 }
1264 m_config->updateOption("frameskip");
1265
1266 QAction* shaderView = new QAction(tr("Shader options..."), avMenu);
1267 connect(shaderView, SIGNAL(triggered()), m_shaderView, SLOT(show()));
1268 if (!m_display->supportsShaders()) {
1269 shaderView->setEnabled(false);
1270 }
1271 addControlledAction(avMenu, shaderView, "shaderSelector");
1272
1273 avMenu->addSeparator();
1274
1275 ConfigOption* mute = m_config->addOption("mute");
1276 mute->addBoolean(tr("Mute"), avMenu);
1277 mute->connect([this](const QVariant& value) {
1278 reloadConfig();
1279 }, this);
1280 m_config->updateOption("mute");
1281
1282 QMenu* target = avMenu->addMenu(tr("FPS target"));
1283 ConfigOption* fpsTargetOption = m_config->addOption("fpsTarget");
1284 fpsTargetOption->connect([this](const QVariant& value) {
1285 emit fpsTargetChanged(value.toFloat());
1286 }, this);
1287 fpsTargetOption->addValue(tr("15"), 15, target);
1288 fpsTargetOption->addValue(tr("30"), 30, target);
1289 fpsTargetOption->addValue(tr("45"), 45, target);
1290 fpsTargetOption->addValue(tr("Native (59.7)"), float(GBA_ARM7TDMI_FREQUENCY) / float(VIDEO_TOTAL_LENGTH), target);
1291 fpsTargetOption->addValue(tr("60"), 60, target);
1292 fpsTargetOption->addValue(tr("90"), 90, target);
1293 fpsTargetOption->addValue(tr("120"), 120, target);
1294 fpsTargetOption->addValue(tr("240"), 240, target);
1295 m_config->updateOption("fpsTarget");
1296
1297#if defined(USE_PNG) || defined(USE_FFMPEG) || defined(USE_MAGICK)
1298 avMenu->addSeparator();
1299#endif
1300
1301#ifdef USE_PNG
1302 QAction* screenshot = new QAction(tr("Take &screenshot"), avMenu);
1303 screenshot->setShortcut(tr("F12"));
1304 connect(screenshot, SIGNAL(triggered()), m_controller, SLOT(screenshot()));
1305 m_gameActions.append(screenshot);
1306 addControlledAction(avMenu, screenshot, "screenshot");
1307#endif
1308
1309#ifdef USE_FFMPEG
1310 QAction* recordOutput = new QAction(tr("Record output..."), avMenu);
1311 connect(recordOutput, SIGNAL(triggered()), this, SLOT(openVideoWindow()));
1312 addControlledAction(avMenu, recordOutput, "recordOutput");
1313 m_gameActions.append(recordOutput);
1314#endif
1315
1316#ifdef USE_MAGICK
1317 QAction* recordGIF = new QAction(tr("Record GIF..."), avMenu);
1318 connect(recordGIF, SIGNAL(triggered()), this, SLOT(openGIFWindow()));
1319 addControlledAction(avMenu, recordGIF, "recordGIF");
1320#endif
1321
1322 avMenu->addSeparator();
1323 QMenu* videoLayers = avMenu->addMenu(tr("Video layers"));
1324 m_shortcutController->addMenu(videoLayers, avMenu);
1325
1326 for (int i = 0; i < 4; ++i) {
1327 QAction* enableBg = new QAction(tr("Background %0").arg(i), videoLayers);
1328 enableBg->setCheckable(true);
1329 enableBg->setChecked(true);
1330 connect(enableBg, &QAction::triggered, [this, i](bool enable) { m_controller->setVideoLayerEnabled(i, enable); });
1331 addControlledAction(videoLayers, enableBg, QString("enableBG%0").arg(i));
1332 }
1333
1334 QAction* enableObj = new QAction(tr("OBJ (sprites)"), videoLayers);
1335 enableObj->setCheckable(true);
1336 enableObj->setChecked(true);
1337 connect(enableObj, &QAction::triggered, [this](bool enable) { m_controller->setVideoLayerEnabled(4, enable); });
1338 addControlledAction(videoLayers, enableObj, "enableOBJ");
1339
1340 QMenu* audioChannels = avMenu->addMenu(tr("Audio channels"));
1341 m_shortcutController->addMenu(audioChannels, avMenu);
1342
1343 for (int i = 0; i < 4; ++i) {
1344 QAction* enableCh = new QAction(tr("Channel %0").arg(i + 1), audioChannels);
1345 enableCh->setCheckable(true);
1346 enableCh->setChecked(true);
1347 connect(enableCh, &QAction::triggered, [this, i](bool enable) { m_controller->setAudioChannelEnabled(i, enable); });
1348 addControlledAction(audioChannels, enableCh, QString("enableCh%0").arg(i + 1));
1349 }
1350
1351 QAction* enableChA = new QAction(tr("Channel A"), audioChannels);
1352 enableChA->setCheckable(true);
1353 enableChA->setChecked(true);
1354 connect(enableChA, &QAction::triggered, [this, i](bool enable) { m_controller->setAudioChannelEnabled(4, enable); });
1355 addControlledAction(audioChannels, enableChA, QString("enableChA"));
1356
1357 QAction* enableChB = new QAction(tr("Channel B"), audioChannels);
1358 enableChB->setCheckable(true);
1359 enableChB->setChecked(true);
1360 connect(enableChB, &QAction::triggered, [this, i](bool enable) { m_controller->setAudioChannelEnabled(5, enable); });
1361 addControlledAction(audioChannels, enableChB, QString("enableChB"));
1362
1363 QMenu* toolsMenu = menubar->addMenu(tr("&Tools"));
1364 m_shortcutController->addMenu(toolsMenu);
1365 QAction* viewLogs = new QAction(tr("View &logs..."), toolsMenu);
1366 connect(viewLogs, SIGNAL(triggered()), m_logView, SLOT(show()));
1367 addControlledAction(toolsMenu, viewLogs, "viewLogs");
1368
1369 QAction* overrides = new QAction(tr("Game &overrides..."), toolsMenu);
1370 connect(overrides, &QAction::triggered, openTView<OverrideView, ConfigController*>(m_config));
1371 addControlledAction(toolsMenu, overrides, "overrideWindow");
1372
1373 QAction* sensors = new QAction(tr("Game &Pak sensors..."), toolsMenu);
1374 connect(sensors, &QAction::triggered, openTView<SensorView, InputController*>(&m_inputController));
1375 addControlledAction(toolsMenu, sensors, "sensorWindow");
1376
1377 QAction* cheats = new QAction(tr("&Cheats..."), toolsMenu);
1378 connect(cheats, &QAction::triggered, openTView<CheatsView>());
1379 m_gameActions.append(cheats);
1380 addControlledAction(toolsMenu, cheats, "cheatsWindow");
1381
1382 toolsMenu->addSeparator();
1383 addControlledAction(toolsMenu, toolsMenu->addAction(tr("Settings..."), this, SLOT(openSettingsWindow())),
1384 "settings");
1385
1386 toolsMenu->addSeparator();
1387
1388#ifdef USE_DEBUGGERS
1389 QAction* consoleWindow = new QAction(tr("Open debugger console..."), toolsMenu);
1390 connect(consoleWindow, SIGNAL(triggered()), this, SLOT(consoleOpen()));
1391 addControlledAction(toolsMenu, consoleWindow, "debuggerWindow");
1392#endif
1393
1394#ifdef USE_GDB_STUB
1395 QAction* gdbWindow = new QAction(tr("Start &GDB server..."), toolsMenu);
1396 connect(gdbWindow, SIGNAL(triggered()), this, SLOT(gdbOpen()));
1397 m_gbaActions.append(gdbWindow);
1398 addControlledAction(toolsMenu, gdbWindow, "gdbWindow");
1399#endif
1400 toolsMenu->addSeparator();
1401
1402 QAction* paletteView = new QAction(tr("View &palette..."), toolsMenu);
1403 connect(paletteView, &QAction::triggered, openTView<PaletteView>());
1404 m_gameActions.append(paletteView);
1405 addControlledAction(toolsMenu, paletteView, "paletteWindow");
1406
1407 QAction* objView = new QAction(tr("View &sprites..."), toolsMenu);
1408 connect(objView, &QAction::triggered, openTView<ObjView>());
1409 m_gameActions.append(objView);
1410 addControlledAction(toolsMenu, objView, "spriteWindow");
1411
1412 QAction* tileView = new QAction(tr("View &tiles..."), toolsMenu);
1413 connect(tileView, &QAction::triggered, openTView<TileView>());
1414 m_gameActions.append(tileView);
1415 addControlledAction(toolsMenu, tileView, "tileWindow");
1416
1417 QAction* memoryView = new QAction(tr("View memory..."), toolsMenu);
1418 connect(memoryView, &QAction::triggered, openTView<MemoryView>());
1419 m_gameActions.append(memoryView);
1420 addControlledAction(toolsMenu, memoryView, "memoryView");
1421
1422#ifdef M_CORE_GBA
1423 QAction* ioViewer = new QAction(tr("View &I/O registers..."), toolsMenu);
1424 connect(ioViewer, &QAction::triggered, openTView<IOViewer>());
1425 m_gameActions.append(ioViewer);
1426 m_gbaActions.append(ioViewer);
1427 addControlledAction(toolsMenu, ioViewer, "ioViewer");
1428#endif
1429
1430 ConfigOption* skipBios = m_config->addOption("skipBios");
1431 skipBios->connect([this](const QVariant& value) {
1432 reloadConfig();
1433 }, this);
1434
1435 ConfigOption* useBios = m_config->addOption("useBios");
1436 useBios->connect([this](const QVariant& value) {
1437 m_controller->setUseBIOS(value.toBool());
1438 }, this);
1439
1440 ConfigOption* buffers = m_config->addOption("audioBuffers");
1441 buffers->connect([this](const QVariant& value) {
1442 emit audioBufferSamplesChanged(value.toInt());
1443 }, this);
1444
1445 ConfigOption* sampleRate = m_config->addOption("sampleRate");
1446 sampleRate->connect([this](const QVariant& value) {
1447 emit sampleRateChanged(value.toUInt());
1448 }, this);
1449
1450 ConfigOption* volume = m_config->addOption("volume");
1451 volume->connect([this](const QVariant& value) {
1452 reloadConfig();
1453 }, this);
1454
1455 ConfigOption* rewindEnable = m_config->addOption("rewindEnable");
1456 rewindEnable->connect([this](const QVariant& value) {
1457 m_controller->setRewind(value.toBool(), m_config->getOption("rewindBufferCapacity").toInt());
1458 }, this);
1459
1460 ConfigOption* rewindBufferCapacity = m_config->addOption("rewindBufferCapacity");
1461 rewindBufferCapacity->connect([this](const QVariant& value) {
1462 m_controller->setRewind(m_config->getOption("rewindEnable").toInt(), value.toInt());
1463 }, this);
1464
1465 ConfigOption* allowOpposingDirections = m_config->addOption("allowOpposingDirections");
1466 allowOpposingDirections->connect([this](const QVariant& value) {
1467 m_inputController.setAllowOpposing(value.toBool());
1468 }, this);
1469
1470 ConfigOption* saveStateExtdata = m_config->addOption("saveStateExtdata");
1471 saveStateExtdata->connect([this](const QVariant& value) {
1472 m_controller->setSaveStateExtdata(value.toInt());
1473 }, this);
1474
1475 ConfigOption* loadStateExtdata = m_config->addOption("loadStateExtdata");
1476 loadStateExtdata->connect([this](const QVariant& value) {
1477 m_controller->setLoadStateExtdata(value.toInt());
1478 }, this);
1479
1480 QAction* exitFullScreen = new QAction(tr("Exit fullscreen"), frameMenu);
1481 connect(exitFullScreen, SIGNAL(triggered()), this, SLOT(exitFullScreen()));
1482 exitFullScreen->setShortcut(QKeySequence("Esc"));
1483 addHiddenAction(frameMenu, exitFullScreen, "exitFullScreen");
1484
1485 QMenu* autofireMenu = new QMenu(tr("Autofire"), this);
1486 m_shortcutController->addMenu(autofireMenu);
1487
1488 m_shortcutController->addFunctions(autofireMenu, [this]() {
1489 m_controller->setAutofire(GBA_KEY_A, true);
1490 }, [this]() {
1491 m_controller->setAutofire(GBA_KEY_A, false);
1492 }, QKeySequence(), tr("Autofire A"), "autofireA");
1493
1494 m_shortcutController->addFunctions(autofireMenu, [this]() {
1495 m_controller->setAutofire(GBA_KEY_B, true);
1496 }, [this]() {
1497 m_controller->setAutofire(GBA_KEY_B, false);
1498 }, QKeySequence(), tr("Autofire B"), "autofireB");
1499
1500 m_shortcutController->addFunctions(autofireMenu, [this]() {
1501 m_controller->setAutofire(GBA_KEY_L, true);
1502 }, [this]() {
1503 m_controller->setAutofire(GBA_KEY_L, false);
1504 }, QKeySequence(), tr("Autofire L"), "autofireL");
1505
1506 m_shortcutController->addFunctions(autofireMenu, [this]() {
1507 m_controller->setAutofire(GBA_KEY_R, true);
1508 }, [this]() {
1509 m_controller->setAutofire(GBA_KEY_R, false);
1510 }, QKeySequence(), tr("Autofire R"), "autofireR");
1511
1512 m_shortcutController->addFunctions(autofireMenu, [this]() {
1513 m_controller->setAutofire(GBA_KEY_START, true);
1514 }, [this]() {
1515 m_controller->setAutofire(GBA_KEY_START, false);
1516 }, QKeySequence(), tr("Autofire Start"), "autofireStart");
1517
1518 m_shortcutController->addFunctions(autofireMenu, [this]() {
1519 m_controller->setAutofire(GBA_KEY_SELECT, true);
1520 }, [this]() {
1521 m_controller->setAutofire(GBA_KEY_SELECT, false);
1522 }, QKeySequence(), tr("Autofire Select"), "autofireSelect");
1523
1524 m_shortcutController->addFunctions(autofireMenu, [this]() {
1525 m_controller->setAutofire(GBA_KEY_UP, true);
1526 }, [this]() {
1527 m_controller->setAutofire(GBA_KEY_UP, false);
1528 }, QKeySequence(), tr("Autofire Up"), "autofireUp");
1529
1530 m_shortcutController->addFunctions(autofireMenu, [this]() {
1531 m_controller->setAutofire(GBA_KEY_RIGHT, true);
1532 }, [this]() {
1533 m_controller->setAutofire(GBA_KEY_RIGHT, false);
1534 }, QKeySequence(), tr("Autofire Right"), "autofireRight");
1535
1536 m_shortcutController->addFunctions(autofireMenu, [this]() {
1537 m_controller->setAutofire(GBA_KEY_DOWN, true);
1538 }, [this]() {
1539 m_controller->setAutofire(GBA_KEY_DOWN, false);
1540 }, QKeySequence(), tr("Autofire Down"), "autofireDown");
1541
1542 m_shortcutController->addFunctions(autofireMenu, [this]() {
1543 m_controller->setAutofire(GBA_KEY_LEFT, true);
1544 }, [this]() {
1545 m_controller->setAutofire(GBA_KEY_LEFT, false);
1546 }, QKeySequence(), tr("Autofire Left"), "autofireLeft");
1547
1548 foreach (QAction* action, m_gameActions) {
1549 action->setDisabled(true);
1550 }
1551}
1552
1553void Window::attachWidget(QWidget* widget) {
1554 m_screenWidget->layout()->addWidget(widget);
1555 m_screenWidget->unsetCursor();
1556 static_cast<QStackedLayout*>(m_screenWidget->layout())->setCurrentWidget(widget);
1557}
1558
1559void Window::detachWidget(QWidget* widget) {
1560 m_screenWidget->layout()->removeWidget(widget);
1561}
1562
1563void Window::appendMRU(const QString& fname) {
1564 int index = m_mruFiles.indexOf(fname);
1565 if (index >= 0) {
1566 m_mruFiles.removeAt(index);
1567 }
1568 m_mruFiles.prepend(fname);
1569 while (m_mruFiles.size() > ConfigController::MRU_LIST_SIZE) {
1570 m_mruFiles.removeLast();
1571 }
1572 updateMRU();
1573}
1574
1575void Window::updateMRU() {
1576 if (!m_mruMenu) {
1577 return;
1578 }
1579 for (QAction* action : m_mruMenu->actions()) {
1580 delete action;
1581 }
1582 m_mruMenu->clear();
1583 int i = 0;
1584 for (const QString& file : m_mruFiles) {
1585 QAction* item = new QAction(file, m_mruMenu);
1586 item->setShortcut(QString("Ctrl+%1").arg(i));
1587 connect(item, &QAction::triggered, [this, file]() { m_controller->loadGame(file); });
1588 m_mruMenu->addAction(item);
1589 ++i;
1590 }
1591 m_config->setMRU(m_mruFiles);
1592 m_config->write();
1593 m_mruMenu->setEnabled(i > 0);
1594}
1595
1596QAction* Window::addControlledAction(QMenu* menu, QAction* action, const QString& name) {
1597 addHiddenAction(menu, action, name);
1598 menu->addAction(action);
1599 return action;
1600}
1601
1602QAction* Window::addHiddenAction(QMenu* menu, QAction* action, const QString& name) {
1603 m_shortcutController->addAction(menu, action, name);
1604 action->setShortcutContext(Qt::WidgetShortcut);
1605 addAction(action);
1606 return action;
1607}
1608
1609void Window::focusCheck() {
1610 if (!m_config->getOption("pauseOnFocusLost").toInt()) {
1611 return;
1612 }
1613 if (QGuiApplication::focusWindow() && m_autoresume) {
1614 m_controller->setPaused(false);
1615 m_autoresume = false;
1616 } else if (!QGuiApplication::focusWindow() && !m_controller->isPaused()) {
1617 m_autoresume = true;
1618 m_controller->setPaused(true);
1619 }
1620}
1621
1622WindowBackground::WindowBackground(QWidget* parent)
1623 : QLabel(parent)
1624{
1625 setLayout(new QStackedLayout());
1626 layout()->setContentsMargins(0, 0, 0, 0);
1627 setAlignment(Qt::AlignCenter);
1628}
1629
1630void WindowBackground::setSizeHint(const QSize& hint) {
1631 m_sizeHint = hint;
1632}
1633
1634QSize WindowBackground::sizeHint() const {
1635 return m_sizeHint;
1636}
1637
1638void WindowBackground::setLockAspectRatio(int width, int height) {
1639 m_aspectWidth = width;
1640 m_aspectHeight = height;
1641}
1642
1643void WindowBackground::paintEvent(QPaintEvent*) {
1644 const QPixmap* logo = pixmap();
1645 if (!logo) {
1646 return;
1647 }
1648 QPainter painter(this);
1649 painter.setRenderHint(QPainter::SmoothPixmapTransform);
1650 painter.fillRect(QRect(QPoint(), size()), Qt::black);
1651 QSize s = size();
1652 QSize ds = s;
1653 if (ds.width() * m_aspectHeight > ds.height() * m_aspectWidth) {
1654 ds.setWidth(ds.height() * m_aspectWidth / m_aspectHeight);
1655 } else if (ds.width() * m_aspectHeight < ds.height() * m_aspectWidth) {
1656 ds.setHeight(ds.width() * m_aspectHeight / m_aspectWidth);
1657 }
1658 QPoint origin = QPoint((s.width() - ds.width()) / 2, (s.height() - ds.height()) / 2);
1659 QRect full(origin, ds);
1660 painter.drawPixmap(full, *logo);
1661}