src/platform/qt/Window.cpp (view raw)
1/* Copyright (c) 2013-2017 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#ifdef USE_SQLITE3
18#include "ArchiveInspector.h"
19#include "library/LibraryController.h"
20#endif
21
22#include "AboutScreen.h"
23#include "AudioProcessor.h"
24#include "CheatsView.h"
25#include "ConfigController.h"
26#include "CoreController.h"
27#include "DebuggerConsole.h"
28#include "DebuggerConsoleController.h"
29#include "Display.h"
30#include "CoreController.h"
31#include "GBAApp.h"
32#include "GDBController.h"
33#include "GDBWindow.h"
34#include "GIFView.h"
35#include "IOViewer.h"
36#include "LoadSaveState.h"
37#include "LogView.h"
38#include "MapView.h"
39#include "MemorySearch.h"
40#include "MemoryView.h"
41#include "MultiplayerController.h"
42#include "OverrideView.h"
43#include "ObjView.h"
44#include "PaletteView.h"
45#include "PlacementControl.h"
46#include "PrinterView.h"
47#include "ROMInfo.h"
48#include "SensorView.h"
49#include "SettingsView.h"
50#include "ShaderSelector.h"
51#include "ShortcutController.h"
52#include "TileView.h"
53#include "VideoView.h"
54
55#include <mgba/core/version.h>
56#include <mgba/core/cheats.h>
57#ifdef M_CORE_GB
58#include <mgba/internal/gb/gb.h>
59#include <mgba/internal/gb/video.h>
60#endif
61#ifdef M_CORE_GBA
62#include <mgba/internal/gba/gba.h>
63#include <mgba/internal/gba/video.h>
64#endif
65#include <mgba/feature/commandline.h>
66#include "feature/sqlite3/no-intro.h"
67#include <mgba-util/vfs.h>
68
69using namespace QGBA;
70
71Window::Window(CoreManager* manager, ConfigController* config, int playerId, QWidget* parent)
72 : QMainWindow(parent)
73 , m_manager(manager)
74 , m_logView(new LogView(&m_log))
75 , m_screenWidget(new WindowBackground())
76 , m_config(config)
77 , m_inputController(playerId, this)
78 , m_shortcutController(new ShortcutController(this))
79{
80 setFocusPolicy(Qt::StrongFocus);
81 setAcceptDrops(true);
82 setAttribute(Qt::WA_DeleteOnClose);
83 updateTitle();
84
85 m_logo.setDevicePixelRatio(m_screenWidget->devicePixelRatio());
86 m_logo = m_logo; // Free memory left over in old pixmap
87
88#if defined(M_CORE_GBA)
89 float i = 2;
90#elif defined(M_CORE_GB)
91 float i = 3;
92#endif
93 QVariant multiplier = m_config->getOption("scaleMultiplier");
94 if (!multiplier.isNull()) {
95 m_savedScale = multiplier.toInt();
96 i = m_savedScale;
97 }
98#ifdef USE_SQLITE3
99 m_libraryView = new LibraryController(nullptr, ConfigController::configDir() + "/library.sqlite3", m_config);
100 ConfigOption* showLibrary = m_config->addOption("showLibrary");
101 showLibrary->connect([this](const QVariant& value) {
102 if (value.toBool()) {
103 if (m_controller) {
104 m_screenWidget->layout()->addWidget(m_libraryView);
105 } else {
106 attachWidget(m_libraryView);
107 }
108 } else {
109 detachWidget(m_libraryView);
110 }
111 }, this);
112 m_config->updateOption("showLibrary");
113 ConfigOption* libraryStyle = m_config->addOption("libraryStyle");
114 libraryStyle->connect([this](const QVariant& value) {
115 m_libraryView->setViewStyle(static_cast<LibraryStyle>(value.toInt()));
116 }, this);
117 m_config->updateOption("libraryStyle");
118
119 connect(m_libraryView, &LibraryController::startGame, [this]() {
120 VFile* output = m_libraryView->selectedVFile();
121 if (output) {
122 QPair<QString, QString> path = m_libraryView->selectedPath();
123 setController(m_manager->loadGame(output, path.second, path.first), path.first + "/" + path.second);
124 }
125 });
126#endif
127#if defined(M_CORE_GBA)
128 resizeFrame(QSize(VIDEO_HORIZONTAL_PIXELS * i, VIDEO_VERTICAL_PIXELS * i));
129#elif defined(M_CORE_GB)
130 resizeFrame(QSize(GB_VIDEO_HORIZONTAL_PIXELS * i, GB_VIDEO_VERTICAL_PIXELS * i));
131#endif
132 m_screenWidget->setPixmap(m_logo);
133 m_screenWidget->setDimensions(m_logo.width(), m_logo.height());
134 m_screenWidget->setLockIntegerScaling(false);
135 m_screenWidget->setLockAspectRatio(true);
136 setCentralWidget(m_screenWidget);
137
138 connect(this, &Window::shutdown, m_logView, &QWidget::hide);
139 connect(&m_fpsTimer, &QTimer::timeout, this, &Window::showFPS);
140 connect(&m_focusCheck, &QTimer::timeout, this, &Window::focusCheck);
141 connect(&m_inputController, &InputController::profileLoaded, m_shortcutController, &ShortcutController::loadProfile);
142
143 m_log.setLevels(mLOG_WARN | mLOG_ERROR | mLOG_FATAL);
144 m_fpsTimer.setInterval(FPS_TIMER_INTERVAL);
145 m_focusCheck.setInterval(200);
146
147 m_shortcutController->setConfigController(m_config);
148 setupMenu(menuBar());
149}
150
151Window::~Window() {
152 delete m_logView;
153
154#ifdef USE_FFMPEG
155 delete m_videoView;
156#endif
157
158#ifdef USE_MAGICK
159 delete m_gifView;
160#endif
161
162#ifdef USE_SQLITE3
163 delete m_libraryView;
164#endif
165}
166
167void Window::argumentsPassed(mArguments* args) {
168 loadConfig();
169
170 if (args->patch) {
171 m_pendingPatch = args->patch;
172 }
173
174 if (args->savestate) {
175 m_pendingState = args->savestate;
176 }
177
178 if (args->fname) {
179 setController(m_manager->loadGame(args->fname), args->fname);
180 }
181
182#ifdef USE_GDB_STUB
183 if (args->debuggerType == DEBUGGER_GDB) {
184 if (!m_gdbController) {
185 m_gdbController = new GDBController(this);
186 if (m_controller) {
187 m_gdbController->setController(m_controller);
188 }
189 m_gdbController->listen();
190 }
191 }
192#endif
193}
194
195void Window::resizeFrame(const QSize& size) {
196 QSize newSize(size);
197 m_screenWidget->setSizeHint(newSize);
198 newSize -= m_screenWidget->size();
199 newSize += this->size();
200 if (!isFullScreen()) {
201 resize(newSize);
202 }
203}
204
205void Window::setConfig(ConfigController* config) {
206 m_config = config;
207}
208
209void Window::loadConfig() {
210 const mCoreOptions* opts = m_config->options();
211 reloadConfig();
212
213 if (opts->width && opts->height) {
214 resizeFrame(QSize(opts->width, opts->height));
215 }
216
217 if (opts->fullscreen) {
218 enterFullScreen();
219 }
220
221 m_mruFiles = m_config->getMRU();
222 updateMRU();
223
224 m_inputController.setConfiguration(m_config);
225}
226
227void Window::reloadConfig() {
228 const mCoreOptions* opts = m_config->options();
229
230 m_log.setLevels(opts->logLevel);
231
232 if (m_controller) {
233 m_controller->loadConfig(m_config);
234 if (m_audioProcessor) {
235 m_audioProcessor->setBufferSamples(opts->audioBuffers);
236 m_audioProcessor->requestSampleRate(opts->sampleRate);
237 }
238 m_display->resizeContext();
239 }
240 if (m_display) {
241 m_display->lockAspectRatio(opts->lockAspectRatio);
242 m_display->filter(opts->resampleVideo);
243 }
244
245 m_inputController.setScreensaverSuspendable(opts->suspendScreensaver);
246}
247
248void Window::saveConfig() {
249 m_inputController.saveConfiguration();
250 m_config->write();
251}
252
253QString Window::getFilters() const {
254 QStringList filters;
255 QStringList formats;
256
257#ifdef M_CORE_GBA
258 QStringList gbaFormats{
259 "*.gba",
260#if defined(USE_LIBZIP) || defined(USE_ZLIB)
261 "*.zip",
262#endif
263#ifdef USE_LZMA
264 "*.7z",
265#endif
266#ifdef USE_ELF
267 "*.elf",
268#endif
269 "*.agb",
270 "*.mb",
271 "*.rom",
272 "*.bin"};
273 formats.append(gbaFormats);
274 filters.append(tr("Game Boy Advance ROMs (%1)").arg(gbaFormats.join(QChar(' '))));
275#endif
276
277#ifdef M_CORE_GB
278 QStringList gbFormats{
279 "*.gb",
280 "*.gbc",
281 "*.sgb",
282#if defined(USE_LIBZIP) || defined(USE_ZLIB)
283 "*.zip",
284#endif
285#ifdef USE_LZMA
286 "*.7z",
287#endif
288 "*.rom",
289 "*.bin"};
290 formats.append(gbFormats);
291 filters.append(tr("Game Boy ROMs (%1)").arg(gbFormats.join(QChar(' '))));
292#endif
293
294 formats.removeDuplicates();
295 filters.prepend(tr("All ROMs (%1)").arg(formats.join(QChar(' '))));
296 filters.append(tr("%1 Video Logs (*.mvl)").arg(projectName));
297 return filters.join(";;");
298}
299
300QString Window::getFiltersArchive() const {
301 QStringList filters;
302
303 QStringList formats{
304#if defined(USE_LIBZIP) || defined(USE_ZLIB)
305 "*.zip",
306#endif
307#ifdef USE_LZMA
308 "*.7z",
309#endif
310 };
311 filters.append(tr("Archives (%1)").arg(formats.join(QChar(' '))));
312 return filters.join(";;");
313}
314
315void Window::selectROM() {
316 QString filename = GBAApp::app()->getOpenFileName(this, tr("Select ROM"), getFilters());
317 if (!filename.isEmpty()) {
318 setController(m_manager->loadGame(filename), filename);
319 }
320}
321
322#ifdef USE_SQLITE3
323void Window::selectROMInArchive() {
324 QString filename = GBAApp::app()->getOpenFileName(this, tr("Select ROM"), getFiltersArchive());
325 if (filename.isEmpty()) {
326 return;
327 }
328 ArchiveInspector* archiveInspector = new ArchiveInspector(filename);
329 connect(archiveInspector, &QDialog::accepted, [this, archiveInspector]() {
330 VFile* output = archiveInspector->selectedVFile();
331 QPair<QString, QString> path = archiveInspector->selectedPath();
332 if (output) {
333 setController(m_manager->loadGame(output, path.second, path.first), path.first + "/" + path.second);
334 }
335 archiveInspector->close();
336 });
337 archiveInspector->setAttribute(Qt::WA_DeleteOnClose);
338 archiveInspector->show();
339}
340
341void Window::addDirToLibrary() {
342 QString filename = GBAApp::app()->getOpenDirectoryName(this, tr("Select folder"));
343 if (filename.isEmpty()) {
344 return;
345 }
346 m_libraryView->addDirectory(filename);
347}
348#endif
349
350void Window::replaceROM() {
351 QString filename = GBAApp::app()->getOpenFileName(this, tr("Select ROM"), getFilters());
352 if (!filename.isEmpty()) {
353 m_controller->replaceGame(filename);
354 }
355}
356
357void Window::selectSave(bool temporary) {
358 QStringList formats{"*.sav"};
359 QString filter = tr("Game Boy Advance save files (%1)").arg(formats.join(QChar(' ')));
360 QString filename = GBAApp::app()->getOpenFileName(this, tr("Select save"), filter);
361 if (!filename.isEmpty()) {
362 m_controller->loadSave(filename, temporary);
363 }
364}
365
366void Window::selectState(bool load) {
367 QStringList formats{"*.ss0", "*.ss1", "*.ss2", "*.ss3", "*.ss4", "*.ss5", "*.ss6", "*.ss7", "*.ss8", "*.ss9"};
368 QString filter = tr("mGBA savestate files (%1)").arg(formats.join(QChar(' ')));
369 if (load) {
370 QString filename = GBAApp::app()->getOpenFileName(this, tr("Select savestate"), filter);
371 if (!filename.isEmpty()) {
372 m_controller->loadState(filename);
373 }
374 } else {
375 QString filename = GBAApp::app()->getSaveFileName(this, tr("Select savestate"), filter);
376 if (!filename.isEmpty()) {
377 m_controller->saveState(filename);
378 }
379 }
380}
381
382void Window::multiplayerChanged() {
383 if (!m_controller) {
384 return;
385 }
386 int attached = 1;
387 MultiplayerController* multiplayer = m_controller->multiplayerController();
388 if (multiplayer) {
389 attached = multiplayer->attached();
390 }
391 for (QAction* action : m_nonMpActions) {
392 action->setDisabled(attached > 1);
393 }
394}
395
396void Window::selectPatch() {
397 QString filename = GBAApp::app()->getOpenFileName(this, tr("Select patch"), tr("Patches (*.ips *.ups *.bps)"));
398 if (!filename.isEmpty()) {
399 if (m_controller) {
400 m_controller->loadPatch(filename);
401 } else {
402 m_pendingPatch = filename;
403 }
404 }
405}
406
407void Window::openView(QWidget* widget) {
408 connect(this, &Window::shutdown, widget, &QWidget::close);
409 widget->setAttribute(Qt::WA_DeleteOnClose);
410 widget->show();
411}
412
413void Window::loadCamImage() {
414 QString filename = GBAApp::app()->getOpenFileName(this, tr("Select image"), tr("Image file (*.png *.gif *.jpg *.jpeg);;All files (*)"));
415 if (!filename.isEmpty()) {
416 m_inputController.loadCamImage(filename);
417 }
418}
419
420void Window::importSharkport() {
421 QString filename = GBAApp::app()->getOpenFileName(this, tr("Select save"), tr("GameShark saves (*.sps *.xps)"));
422 if (!filename.isEmpty()) {
423 m_controller->importSharkport(filename);
424 }
425}
426
427void Window::exportSharkport() {
428 QString filename = GBAApp::app()->getSaveFileName(this, tr("Select save"), tr("GameShark saves (*.sps *.xps)"));
429 if (!filename.isEmpty()) {
430 m_controller->exportSharkport(filename);
431 }
432}
433
434void Window::openSettingsWindow() {
435 SettingsView* settingsWindow = new SettingsView(m_config, &m_inputController, m_shortcutController);
436#if defined(BUILD_GL) || defined(BUILD_GLES2)
437 if (m_display->supportsShaders()) {
438 settingsWindow->setShaderSelector(m_shaderView.get());
439 }
440#endif
441 connect(settingsWindow, &SettingsView::displayDriverChanged, this, &Window::reloadDisplayDriver);
442 connect(settingsWindow, &SettingsView::audioDriverChanged, this, &Window::reloadAudioDriver);
443 connect(settingsWindow, &SettingsView::cameraDriverChanged, this, &Window::mustRestart);
444 connect(settingsWindow, &SettingsView::languageChanged, this, &Window::mustRestart);
445 connect(settingsWindow, &SettingsView::pathsChanged, this, &Window::reloadConfig);
446#ifdef USE_SQLITE3
447 connect(settingsWindow, &SettingsView::libraryCleared, m_libraryView, &LibraryController::clear);
448#endif
449 openView(settingsWindow);
450}
451
452void Window::startVideoLog() {
453 QString filename = GBAApp::app()->getSaveFileName(this, tr("Select video log"), tr("Video logs (*.mvl)"));
454 if (!filename.isEmpty()) {
455 m_controller->startVideoLog(filename);
456 }
457}
458
459template <typename T, typename... A>
460std::function<void()> Window::openTView(A... arg) {
461 return [=]() {
462 T* view = new T(arg...);
463 openView(view);
464 };
465}
466
467
468template <typename T, typename... A>
469std::function<void()> Window::openControllerTView(A... arg) {
470 return [=]() {
471 T* view = new T(m_controller, arg...);
472 openView(view);
473 };
474}
475
476#ifdef USE_FFMPEG
477void Window::openVideoWindow() {
478 if (!m_videoView) {
479 m_videoView = new VideoView();
480 if (m_controller) {
481 m_videoView->setController(m_controller);
482 }
483 connect(this, &Window::shutdown, m_videoView, &QWidget::close);
484 }
485 m_videoView->show();
486}
487#endif
488
489#ifdef USE_MAGICK
490void Window::openGIFWindow() {
491 if (!m_gifView) {
492 m_gifView = new GIFView();
493 if (m_controller) {
494 m_gifView->setController(m_controller);
495 }
496 connect(this, &Window::shutdown, m_gifView, &QWidget::close);
497 }
498 m_gifView->show();
499}
500#endif
501
502#ifdef USE_GDB_STUB
503void Window::gdbOpen() {
504 if (!m_gdbController) {
505 m_gdbController = new GDBController(this);
506 }
507 GDBWindow* window = new GDBWindow(m_gdbController);
508 m_gdbController->setController(m_controller);
509 connect(m_controller.get(), &CoreController::stopping, window, &QWidget::close);
510 openView(window);
511}
512#endif
513
514#ifdef USE_DEBUGGERS
515void Window::consoleOpen() {
516 if (!m_console) {
517 m_console = new DebuggerConsoleController(this);
518 }
519 DebuggerConsole* window = new DebuggerConsole(m_console);
520 if (m_controller) {
521 m_console->setController(m_controller);
522 }
523 openView(window);
524}
525#endif
526
527void Window::keyPressEvent(QKeyEvent* event) {
528 if (event->isAutoRepeat()) {
529 QWidget::keyPressEvent(event);
530 return;
531 }
532 GBAKey key = m_inputController.mapKeyboard(event->key());
533 if (key == GBA_KEY_NONE) {
534 QWidget::keyPressEvent(event);
535 return;
536 }
537 if (m_controller) {
538 m_controller->addKey(key);
539 }
540 event->accept();
541}
542
543void Window::keyReleaseEvent(QKeyEvent* event) {
544 if (event->isAutoRepeat()) {
545 QWidget::keyReleaseEvent(event);
546 return;
547 }
548 GBAKey key = m_inputController.mapKeyboard(event->key());
549 if (key == GBA_KEY_NONE) {
550 QWidget::keyPressEvent(event);
551 return;
552 }
553 if (m_controller) {
554 m_controller->clearKey(key);
555 }
556 event->accept();
557}
558
559void Window::resizeEvent(QResizeEvent* event) {
560 if (!isFullScreen()) {
561 m_config->setOption("height", m_screenWidget->height());
562 m_config->setOption("width", m_screenWidget->width());
563 }
564
565 int factor = 0;
566 QSize size(VIDEO_HORIZONTAL_PIXELS, VIDEO_VERTICAL_PIXELS);
567 if (m_controller) {
568 size = m_controller->screenDimensions();
569 }
570 if (m_screenWidget->width() % size.width() == 0 && m_screenWidget->height() % size.height() == 0 &&
571 m_screenWidget->width() / size.width() == m_screenWidget->height() / size.height()) {
572 factor = m_screenWidget->width() / size.width();
573 } else {
574 m_savedScale = 0;
575 }
576 for (QMap<int, QAction*>::iterator iter = m_frameSizes.begin(); iter != m_frameSizes.end(); ++iter) {
577 bool enableSignals = iter.value()->blockSignals(true);
578 iter.value()->setChecked(iter.key() == factor);
579 iter.value()->blockSignals(enableSignals);
580 }
581
582 m_config->setOption("fullscreen", isFullScreen());
583}
584
585void Window::showEvent(QShowEvent* event) {
586 if (m_wasOpened) {
587 return;
588 }
589 m_wasOpened = true;
590 resizeFrame(m_screenWidget->sizeHint());
591 QVariant windowPos = m_config->getQtOption("windowPos");
592 QRect geom = QApplication::desktop()->availableGeometry(this);
593 if (!windowPos.isNull() && geom.contains(windowPos.toPoint())) {
594 move(windowPos.toPoint());
595 } else {
596 QRect rect = frameGeometry();
597 rect.moveCenter(geom.center());
598 move(rect.topLeft());
599 }
600 if (m_fullscreenOnStart) {
601 enterFullScreen();
602 m_fullscreenOnStart = false;
603 }
604 reloadDisplayDriver();
605}
606
607void Window::closeEvent(QCloseEvent* event) {
608 emit shutdown();
609 m_config->setQtOption("windowPos", pos());
610
611 if (m_savedScale > 0) {
612 m_config->setOption("height", VIDEO_VERTICAL_PIXELS * m_savedScale);
613 m_config->setOption("width", VIDEO_HORIZONTAL_PIXELS * m_savedScale);
614 }
615 saveConfig();
616 m_display.reset();
617 QMainWindow::closeEvent(event);
618}
619
620void Window::focusInEvent(QFocusEvent*) {
621 m_display->forceDraw();
622}
623
624void Window::focusOutEvent(QFocusEvent*) {
625}
626
627void Window::dragEnterEvent(QDragEnterEvent* event) {
628 if (event->mimeData()->hasFormat("text/uri-list")) {
629 event->acceptProposedAction();
630 }
631}
632
633void Window::dropEvent(QDropEvent* event) {
634 QString uris = event->mimeData()->data("text/uri-list");
635 uris = uris.trimmed();
636 if (uris.contains("\n")) {
637 // Only one file please
638 return;
639 }
640 QUrl url(uris);
641 if (!url.isLocalFile()) {
642 // No remote loading
643 return;
644 }
645 event->accept();
646 setController(m_manager->loadGame(url.toLocalFile()), url.toLocalFile());
647}
648
649void Window::mouseDoubleClickEvent(QMouseEvent* event) {
650 if (event->button() != Qt::LeftButton) {
651 return;
652 }
653 toggleFullScreen();
654}
655
656void Window::enterFullScreen() {
657 if (!isVisible()) {
658 m_fullscreenOnStart = true;
659 return;
660 }
661 if (isFullScreen()) {
662 return;
663 }
664 showFullScreen();
665#ifndef Q_OS_MAC
666 if (m_controller && !m_controller->isPaused()) {
667 menuBar()->hide();
668 }
669#endif
670}
671
672void Window::exitFullScreen() {
673 if (!isFullScreen()) {
674 return;
675 }
676 m_screenWidget->unsetCursor();
677 menuBar()->show();
678 showNormal();
679}
680
681void Window::toggleFullScreen() {
682 if (isFullScreen()) {
683 exitFullScreen();
684 } else {
685 enterFullScreen();
686 }
687}
688
689void Window::gameStarted() {
690 for (QAction* action : m_gameActions) {
691 action->setDisabled(false);
692 }
693#ifdef M_CORE_GBA
694 for (QAction* action : m_gbaActions) {
695 action->setDisabled(m_controller->platform() != PLATFORM_GBA);
696 }
697#endif
698 QSize size = m_controller->screenDimensions();
699 m_screenWidget->setDimensions(size.width(), size.height());
700 m_config->updateOption("lockIntegerScaling");
701 m_config->updateOption("lockAspectRatio");
702 if (m_savedScale > 0) {
703 resizeFrame(size * m_savedScale);
704 }
705 if (!m_display) {
706 reloadDisplayDriver();
707 }
708 attachWidget(m_display.get());
709 m_display->setMinimumSize(size);
710
711#ifndef Q_OS_MAC
712 if (isFullScreen()) {
713 menuBar()->hide();
714 }
715#endif
716 m_display->startDrawing(m_controller);
717
718 reloadAudioDriver();
719 multiplayerChanged();
720 updateTitle();
721
722 m_hitUnimplementedBiosCall = false;
723 if (m_config->getOption("showFps", "1").toInt()) {
724 m_fpsTimer.start();
725 m_frameTimer.start();
726 }
727 m_focusCheck.start();
728 if (m_display->underMouse()) {
729 m_screenWidget->setCursor(Qt::BlankCursor);
730 }
731
732 CoreController::Interrupter interrupter(m_controller, true);
733 mCore* core = m_controller->thread()->core;
734 m_videoLayers->clear();
735 m_audioChannels->clear();
736 const mCoreChannelInfo* videoLayers;
737 const mCoreChannelInfo* audioChannels;
738 size_t nVideo = core->listVideoLayers(core, &videoLayers);
739 size_t nAudio = core->listAudioChannels(core, &audioChannels);
740
741 if (nVideo) {
742 for (size_t i = 0; i < nVideo; ++i) {
743 QAction* action = new QAction(videoLayers[i].visibleName, m_videoLayers);
744 action->setCheckable(true);
745 action->setChecked(true);
746 connect(action, &QAction::triggered, [this, videoLayers, i](bool enable) {
747 m_controller->thread()->core->enableVideoLayer(m_controller->thread()->core, videoLayers[i].id, enable);
748 });
749 m_videoLayers->addAction(action);
750 }
751 }
752 if (nAudio) {
753 for (size_t i = 0; i < nAudio; ++i) {
754 QAction* action = new QAction(audioChannels[i].visibleName, m_audioChannels);
755 action->setCheckable(true);
756 action->setChecked(true);
757 connect(action, &QAction::triggered, [this, audioChannels, i](bool enable) {
758 m_controller->thread()->core->enableAudioChannel(m_controller->thread()->core, audioChannels[i].id, enable);
759 });
760 m_audioChannels->addAction(action);
761 }
762 }
763}
764
765void Window::gameStopped() {
766 m_controller.reset();
767#ifdef M_CORE_GBA
768 for (QAction* action : m_gbaActions) {
769 action->setDisabled(false);
770 }
771#endif
772 for (QAction* action : m_gameActions) {
773 action->setDisabled(true);
774 }
775 setWindowFilePath(QString());
776 updateTitle();
777 detachWidget(m_display.get());
778 m_screenWidget->setDimensions(m_logo.width(), m_logo.height());
779 m_screenWidget->setLockIntegerScaling(false);
780 m_screenWidget->setLockAspectRatio(true);
781 m_screenWidget->setPixmap(m_logo);
782 m_screenWidget->unsetCursor();
783#ifdef M_CORE_GB
784 m_display->setMinimumSize(GB_VIDEO_HORIZONTAL_PIXELS, GB_VIDEO_VERTICAL_PIXELS);
785#elif defined(M_CORE_GBA)
786 m_display->setMinimumSize(VIDEO_HORIZONTAL_PIXELS, VIDEO_VERTICAL_PIXELS);
787#endif
788
789 m_videoLayers->clear();
790 m_audioChannels->clear();
791
792 m_fpsTimer.stop();
793 m_focusCheck.stop();
794
795 emit paused(false);
796}
797
798void Window::gameCrashed(const QString& errorMessage) {
799 QMessageBox* crash = new QMessageBox(QMessageBox::Critical, tr("Crash"),
800 tr("The game has crashed with the following error:\n\n%1").arg(errorMessage),
801 QMessageBox::Ok, this, Qt::Sheet);
802 crash->setAttribute(Qt::WA_DeleteOnClose);
803 crash->show();
804 m_controller->stop();
805}
806
807void Window::gameFailed() {
808 QMessageBox* fail = new QMessageBox(QMessageBox::Warning, tr("Couldn't Load"),
809 tr("Could not load game. Are you sure it's in the correct format?"),
810 QMessageBox::Ok, this, Qt::Sheet);
811 fail->setAttribute(Qt::WA_DeleteOnClose);
812 fail->show();
813}
814
815void Window::unimplementedBiosCall(int call) {
816 if (m_hitUnimplementedBiosCall) {
817 return;
818 }
819 m_hitUnimplementedBiosCall = true;
820
821 QMessageBox* fail = new QMessageBox(
822 QMessageBox::Warning, tr("Unimplemented BIOS call"),
823 tr("This game uses a BIOS call that is not implemented. Please use the official BIOS for best experience."),
824 QMessageBox::Ok, this, Qt::Sheet);
825 fail->setAttribute(Qt::WA_DeleteOnClose);
826 fail->show();
827}
828
829void Window::reloadDisplayDriver() {
830 if (m_controller) {
831 m_display->stopDrawing();
832 detachWidget(m_display.get());
833 }
834 m_display = std::move(std::unique_ptr<Display>(Display::create(this)));
835#if defined(BUILD_GL) || defined(BUILD_GLES2)
836 m_shaderView.reset();
837 m_shaderView = std::make_unique<ShaderSelector>(m_display.get(), m_config);
838#endif
839
840 connect(this, &Window::shutdown, m_display.get(), &Display::stopDrawing);
841 connect(m_display.get(), &Display::hideCursor, [this]() {
842 if (static_cast<QStackedLayout*>(m_screenWidget->layout())->currentWidget() == m_display.get()) {
843 m_screenWidget->setCursor(Qt::BlankCursor);
844 }
845 });
846 connect(m_display.get(), &Display::showCursor, [this]() {
847 m_screenWidget->unsetCursor();
848 });
849
850 const mCoreOptions* opts = m_config->options();
851 m_display->lockAspectRatio(opts->lockAspectRatio);
852 m_display->filter(opts->resampleVideo);
853#if defined(BUILD_GL) || defined(BUILD_GLES2)
854 if (opts->shader) {
855 struct VDir* shader = VDirOpen(opts->shader);
856 if (shader && m_display->supportsShaders()) {
857 m_display->setShaders(shader);
858 m_shaderView->refreshShaders();
859 shader->close(shader);
860 }
861 }
862#endif
863
864 if (m_controller) {
865 m_display->setMinimumSize(m_controller->screenDimensions());
866 connect(m_controller.get(), &CoreController::stopping, m_display.get(), &Display::stopDrawing);
867 connect(m_controller.get(), &CoreController::stateLoaded, m_display.get(), &Display::resizeContext);
868 connect(m_controller.get(), &CoreController::stateLoaded, m_display.get(), &Display::forceDraw);
869 connect(m_controller.get(), &CoreController::rewound, m_display.get(), &Display::forceDraw);
870 connect(m_controller.get(), &CoreController::paused, m_display.get(), &Display::pauseDrawing);
871 connect(m_controller.get(), &CoreController::unpaused, m_display.get(), &Display::unpauseDrawing);
872 connect(m_controller.get(), &CoreController::frameAvailable, m_display.get(), &Display::framePosted);
873 connect(m_controller.get(), &CoreController::statusPosted, m_display.get(), &Display::showMessage);
874
875 attachWidget(m_display.get());
876 m_display->startDrawing(m_controller);
877 } else {
878#ifdef M_CORE_GB
879 m_display->setMinimumSize(GB_VIDEO_HORIZONTAL_PIXELS, GB_VIDEO_VERTICAL_PIXELS);
880#elif defined(M_CORE_GBA)
881 m_display->setMinimumSize(VIDEO_HORIZONTAL_PIXELS, VIDEO_VERTICAL_PIXELS);
882#endif
883 }
884}
885
886void Window::reloadAudioDriver() {
887 if (!m_controller) {
888 return;
889 }
890 if (m_audioProcessor) {
891 m_audioProcessor->stop();
892 m_audioProcessor.reset();
893 }
894
895 const mCoreOptions* opts = m_config->options();
896 m_audioProcessor = std::move(std::unique_ptr<AudioProcessor>(AudioProcessor::create()));
897 m_audioProcessor->setInput(m_controller);
898 m_audioProcessor->setBufferSamples(opts->audioBuffers);
899 m_audioProcessor->requestSampleRate(opts->sampleRate);
900 m_audioProcessor->start();
901 connect(m_controller.get(), &CoreController::stopping, m_audioProcessor.get(), &AudioProcessor::stop);
902}
903
904void Window::tryMakePortable() {
905 QMessageBox* confirm = new QMessageBox(QMessageBox::Question, tr("Really make portable?"),
906 tr("This will make the emulator load its configuration from the same directory as the executable. Do you want to continue?"),
907 QMessageBox::Yes | QMessageBox::Cancel, this, Qt::Sheet);
908 confirm->setAttribute(Qt::WA_DeleteOnClose);
909 connect(confirm->button(QMessageBox::Yes), &QAbstractButton::clicked, m_config, &ConfigController::makePortable);
910 confirm->show();
911}
912
913void Window::mustRestart() {
914 QMessageBox* dialog = new QMessageBox(QMessageBox::Warning, tr("Restart needed"),
915 tr("Some changes will not take effect until the emulator is restarted."),
916 QMessageBox::Ok, this, Qt::Sheet);
917 dialog->setAttribute(Qt::WA_DeleteOnClose);
918 dialog->show();
919}
920
921void Window::recordFrame() {
922 m_frameList.append(m_frameTimer.nsecsElapsed());
923 m_frameTimer.restart();
924}
925
926void Window::showFPS() {
927 if (m_frameList.isEmpty()) {
928 updateTitle();
929 return;
930 }
931 qint64 total = 0;
932 for (qint64 t : m_frameList) {
933 total += t;
934 }
935 double fps = (m_frameList.size() * 1e10) / total;
936 m_frameList.clear();
937 fps = round(fps) / 10.f;
938 updateTitle(fps);
939}
940
941void Window::updateTitle(float fps) {
942 QString title;
943
944 if (m_controller) {
945 CoreController::Interrupter interrupter(m_controller);
946 const NoIntroDB* db = GBAApp::app()->gameDB();
947 NoIntroGame game{};
948 uint32_t crc32 = 0;
949 m_controller->thread()->core->checksum(m_controller->thread()->core, &crc32, CHECKSUM_CRC32);
950
951 char gameTitle[17] = { '\0' };
952 mCore* core = m_controller->thread()->core;
953 core->getGameTitle(core, gameTitle);
954 title = gameTitle;
955
956#ifdef USE_SQLITE3
957 if (db && crc32 && NoIntroDBLookupGameByCRC(db, crc32, &game)) {
958 title = QLatin1String(game.name);
959 }
960#endif
961 MultiplayerController* multiplayer = m_controller->multiplayerController();
962 if (multiplayer && multiplayer->attached() > 1) {
963 title += tr(" - Player %1 of %2").arg(multiplayer->playerId(m_controller.get()) + 1).arg(multiplayer->attached());
964 for (QAction* action : m_nonMpActions) {
965 action->setDisabled(true);
966 }
967 } else {
968 for (QAction* action : m_nonMpActions) {
969 action->setDisabled(false);
970 }
971 }
972 }
973 if (title.isNull()) {
974 setWindowTitle(tr("%1 - %2").arg(projectName).arg(projectVersion));
975 } else if (fps < 0) {
976 setWindowTitle(tr("%1 - %2 - %3").arg(projectName).arg(title).arg(projectVersion));
977 } else {
978 setWindowTitle(tr("%1 - %2 (%3 fps) - %4").arg(projectName).arg(title).arg(fps).arg(projectVersion));
979 }
980}
981
982void Window::openStateWindow(LoadSave ls) {
983 if (m_stateWindow) {
984 return;
985 }
986 MultiplayerController* multiplayer = m_controller->multiplayerController();
987 if (multiplayer && multiplayer->attached() > 1) {
988 return;
989 }
990 bool wasPaused = m_controller->isPaused();
991 m_stateWindow = new LoadSaveState(m_controller);
992 connect(this, &Window::shutdown, m_stateWindow, &QWidget::close);
993 connect(m_stateWindow, &LoadSaveState::closed, [this]() {
994 detachWidget(m_stateWindow);
995 m_stateWindow = nullptr;
996 QMetaObject::invokeMethod(this, "setFocus", Qt::QueuedConnection);
997 });
998 if (!wasPaused) {
999 m_controller->setPaused(true);
1000 connect(m_stateWindow, &LoadSaveState::closed, [this]() {
1001 if (m_controller) {
1002 m_controller->setPaused(false);
1003 }
1004 });
1005 }
1006 m_stateWindow->setAttribute(Qt::WA_DeleteOnClose);
1007 m_stateWindow->setMode(ls);
1008 updateFrame();
1009 attachWidget(m_stateWindow);
1010}
1011
1012void Window::setupMenu(QMenuBar* menubar) {
1013 menubar->clear();
1014 QMenu* fileMenu = menubar->addMenu(tr("&File"));
1015 m_shortcutController->addMenu(fileMenu);
1016 installEventFilter(m_shortcutController);
1017 addControlledAction(fileMenu, fileMenu->addAction(tr("Load &ROM..."), this, SLOT(selectROM()), QKeySequence::Open),
1018 "loadROM");
1019#ifdef USE_SQLITE3
1020 addControlledAction(fileMenu, fileMenu->addAction(tr("Load ROM in archive..."), this, SLOT(selectROMInArchive())),
1021 "loadROMInArchive");
1022 addControlledAction(fileMenu, fileMenu->addAction(tr("Add folder to library..."), this, SLOT(addDirToLibrary())),
1023 "addDirToLibrary");
1024#endif
1025
1026 QAction* loadAlternateSave = new QAction(tr("Load alternate save..."), fileMenu);
1027 connect(loadAlternateSave, &QAction::triggered, [this]() { this->selectSave(false); });
1028 m_gameActions.append(loadAlternateSave);
1029 addControlledAction(fileMenu, loadAlternateSave, "loadAlternateSave");
1030
1031 QAction* loadTemporarySave = new QAction(tr("Load temporary save..."), fileMenu);
1032 connect(loadTemporarySave, &QAction::triggered, [this]() { this->selectSave(true); });
1033 m_gameActions.append(loadTemporarySave);
1034 addControlledAction(fileMenu, loadTemporarySave, "loadTemporarySave");
1035
1036 addControlledAction(fileMenu, fileMenu->addAction(tr("Load &patch..."), this, SLOT(selectPatch())), "loadPatch");
1037
1038#ifdef M_CORE_GBA
1039 QAction* bootBIOS = new QAction(tr("Boot BIOS"), fileMenu);
1040 connect(bootBIOS, &QAction::triggered, [this]() {
1041 setController(m_manager->loadBIOS(PLATFORM_GBA, m_config->getOption("gba.bios")), QString());
1042 });
1043 addControlledAction(fileMenu, bootBIOS, "bootBIOS");
1044#endif
1045
1046 addControlledAction(fileMenu, fileMenu->addAction(tr("Replace ROM..."), this, SLOT(replaceROM())), "replaceROM");
1047
1048 QAction* romInfo = new QAction(tr("ROM &info..."), fileMenu);
1049 connect(romInfo, &QAction::triggered, openControllerTView<ROMInfo>());
1050 m_gameActions.append(romInfo);
1051 addControlledAction(fileMenu, romInfo, "romInfo");
1052
1053 m_mruMenu = fileMenu->addMenu(tr("Recent"));
1054
1055 fileMenu->addSeparator();
1056
1057 addControlledAction(fileMenu, fileMenu->addAction(tr("Make portable"), this, SLOT(tryMakePortable())), "makePortable");
1058
1059 fileMenu->addSeparator();
1060
1061 QAction* loadState = new QAction(tr("&Load state"), fileMenu);
1062 loadState->setShortcut(tr("F10"));
1063 connect(loadState, &QAction::triggered, [this]() { this->openStateWindow(LoadSave::LOAD); });
1064 m_gameActions.append(loadState);
1065 m_nonMpActions.append(loadState);
1066 addControlledAction(fileMenu, loadState, "loadState");
1067
1068 QAction* loadStateFile = new QAction(tr("Load state file..."), fileMenu);
1069 connect(loadStateFile, &QAction::triggered, [this]() { this->selectState(true); });
1070 m_gameActions.append(loadStateFile);
1071 m_nonMpActions.append(loadStateFile);
1072 addControlledAction(fileMenu, loadStateFile, "loadStateFile");
1073
1074 QAction* saveState = new QAction(tr("&Save state"), fileMenu);
1075 saveState->setShortcut(tr("Shift+F10"));
1076 connect(saveState, &QAction::triggered, [this]() { this->openStateWindow(LoadSave::SAVE); });
1077 m_gameActions.append(saveState);
1078 m_nonMpActions.append(saveState);
1079 addControlledAction(fileMenu, saveState, "saveState");
1080
1081 QAction* saveStateFile = new QAction(tr("Save state file..."), fileMenu);
1082 connect(saveStateFile, &QAction::triggered, [this]() { this->selectState(false); });
1083 m_gameActions.append(saveStateFile);
1084 m_nonMpActions.append(saveStateFile);
1085 addControlledAction(fileMenu, saveStateFile, "saveStateFile");
1086
1087 QMenu* quickLoadMenu = fileMenu->addMenu(tr("Quick load"));
1088 QMenu* quickSaveMenu = fileMenu->addMenu(tr("Quick save"));
1089 m_shortcutController->addMenu(quickLoadMenu);
1090 m_shortcutController->addMenu(quickSaveMenu);
1091
1092 QAction* quickLoad = new QAction(tr("Load recent"), quickLoadMenu);
1093 connect(quickLoad, &QAction::triggered, [this] {
1094 m_controller->loadState();
1095 });
1096 m_gameActions.append(quickLoad);
1097 m_nonMpActions.append(quickLoad);
1098 addControlledAction(quickLoadMenu, quickLoad, "quickLoad");
1099
1100 QAction* quickSave = new QAction(tr("Save recent"), quickSaveMenu);
1101 connect(quickLoad, &QAction::triggered, [this] {
1102 m_controller->saveState();
1103 });
1104 m_gameActions.append(quickSave);
1105 m_nonMpActions.append(quickSave);
1106 addControlledAction(quickSaveMenu, quickSave, "quickSave");
1107
1108 quickLoadMenu->addSeparator();
1109 quickSaveMenu->addSeparator();
1110
1111 QAction* undoLoadState = new QAction(tr("Undo load state"), quickLoadMenu);
1112 undoLoadState->setShortcut(tr("F11"));
1113 connect(undoLoadState, &QAction::triggered, [this]() {
1114 m_controller->loadBackupState();
1115 });
1116 m_gameActions.append(undoLoadState);
1117 m_nonMpActions.append(undoLoadState);
1118 addControlledAction(quickLoadMenu, undoLoadState, "undoLoadState");
1119
1120 QAction* undoSaveState = new QAction(tr("Undo save state"), quickSaveMenu);
1121 undoSaveState->setShortcut(tr("Shift+F11"));
1122 connect(undoSaveState, &QAction::triggered, [this]() {
1123 m_controller->saveBackupState();
1124 });
1125 m_gameActions.append(undoSaveState);
1126 m_nonMpActions.append(undoSaveState);
1127 addControlledAction(quickSaveMenu, undoSaveState, "undoSaveState");
1128
1129 quickLoadMenu->addSeparator();
1130 quickSaveMenu->addSeparator();
1131
1132 int i;
1133 for (i = 1; i < 10; ++i) {
1134 quickLoad = new QAction(tr("State &%1").arg(i), quickLoadMenu);
1135 quickLoad->setShortcut(tr("F%1").arg(i));
1136 connect(quickLoad, &QAction::triggered, [this, i]() {
1137 m_controller->loadState(i);
1138 });
1139 m_gameActions.append(quickLoad);
1140 m_nonMpActions.append(quickLoad);
1141 addControlledAction(quickLoadMenu, quickLoad, QString("quickLoad.%1").arg(i));
1142
1143 quickSave = new QAction(tr("State &%1").arg(i), quickSaveMenu);
1144 quickSave->setShortcut(tr("Shift+F%1").arg(i));
1145 connect(quickSave, &QAction::triggered, [this, i]() {
1146 m_controller->saveState(i);
1147 });
1148 m_gameActions.append(quickSave);
1149 m_nonMpActions.append(quickSave);
1150 addControlledAction(quickSaveMenu, quickSave, QString("quickSave.%1").arg(i));
1151 }
1152
1153 fileMenu->addSeparator();
1154 QAction* camImage = new QAction(tr("Load camera image..."), fileMenu);
1155 connect(camImage, &QAction::triggered, this, &Window::loadCamImage);
1156 addControlledAction(fileMenu, camImage, "loadCamImage");
1157
1158#ifdef M_CORE_GBA
1159 fileMenu->addSeparator();
1160 QAction* importShark = new QAction(tr("Import GameShark Save"), fileMenu);
1161 connect(importShark, &QAction::triggered, this, &Window::importSharkport);
1162 m_gameActions.append(importShark);
1163 m_gbaActions.append(importShark);
1164 addControlledAction(fileMenu, importShark, "importShark");
1165
1166 QAction* exportShark = new QAction(tr("Export GameShark Save"), fileMenu);
1167 connect(exportShark, &QAction::triggered, this, &Window::exportSharkport);
1168 m_gameActions.append(exportShark);
1169 m_gbaActions.append(exportShark);
1170 addControlledAction(fileMenu, exportShark, "exportShark");
1171#endif
1172
1173 fileMenu->addSeparator();
1174 m_multiWindow = new QAction(tr("New multiplayer window"), fileMenu);
1175 connect(m_multiWindow, &QAction::triggered, [this]() {
1176 GBAApp::app()->newWindow();
1177 });
1178 addControlledAction(fileMenu, m_multiWindow, "multiWindow");
1179
1180#ifndef Q_OS_MAC
1181 fileMenu->addSeparator();
1182#endif
1183
1184 QAction* about = new QAction(tr("About"), fileMenu);
1185 connect(about, &QAction::triggered, openTView<AboutScreen>());
1186 fileMenu->addAction(about);
1187
1188#ifndef Q_OS_MAC
1189 addControlledAction(fileMenu, fileMenu->addAction(tr("E&xit"), this, SLOT(close()), QKeySequence::Quit), "quit");
1190#endif
1191
1192 QMenu* emulationMenu = menubar->addMenu(tr("&Emulation"));
1193 m_shortcutController->addMenu(emulationMenu);
1194 QAction* reset = new QAction(tr("&Reset"), emulationMenu);
1195 reset->setShortcut(tr("Ctrl+R"));
1196 connect(reset, &QAction::triggered, [this]() {
1197 m_controller->reset();
1198 });
1199 m_gameActions.append(reset);
1200 addControlledAction(emulationMenu, reset, "reset");
1201
1202 QAction* shutdown = new QAction(tr("Sh&utdown"), emulationMenu);
1203 connect(shutdown, &QAction::triggered, [this]() {
1204 m_controller->stop();
1205 });
1206 m_gameActions.append(shutdown);
1207 addControlledAction(emulationMenu, shutdown, "shutdown");
1208
1209#ifdef M_CORE_GBA
1210 QAction* yank = new QAction(tr("Yank game pak"), emulationMenu);
1211 connect(yank, &QAction::triggered, [this]() {
1212 m_controller->yankPak();
1213 });
1214 m_gameActions.append(yank);
1215 m_gbaActions.append(yank);
1216 addControlledAction(emulationMenu, yank, "yank");
1217#endif
1218 emulationMenu->addSeparator();
1219
1220 QAction* pause = new QAction(tr("&Pause"), emulationMenu);
1221 pause->setChecked(false);
1222 pause->setCheckable(true);
1223 pause->setShortcut(tr("Ctrl+P"));
1224 connect(pause, &QAction::triggered, [this](bool paused) {
1225 if (m_controller) {
1226 m_controller->setPaused(paused);
1227 } else {
1228 m_pendingPause = paused;
1229 }
1230 });
1231 connect(this, &Window::paused, [pause](bool paused) {
1232 pause->setChecked(paused);
1233 });
1234 addControlledAction(emulationMenu, pause, "pause");
1235
1236 QAction* frameAdvance = new QAction(tr("&Next frame"), emulationMenu);
1237 frameAdvance->setShortcut(tr("Ctrl+N"));
1238 connect(frameAdvance, &QAction::triggered, [this]() {
1239 m_controller->frameAdvance();
1240 });
1241 m_gameActions.append(frameAdvance);
1242 addControlledAction(emulationMenu, frameAdvance, "frameAdvance");
1243
1244 emulationMenu->addSeparator();
1245
1246 m_shortcutController->addFunctions(emulationMenu, [this]() {
1247 if (m_controller) {
1248 m_controller->setFastForward(true);
1249 }
1250 }, [this]() {
1251 if (m_controller) {
1252 m_controller->setFastForward(false);
1253 }
1254 }, QKeySequence(Qt::Key_Tab), tr("Fast forward (held)"), "holdFastForward");
1255
1256 QAction* turbo = new QAction(tr("&Fast forward"), emulationMenu);
1257 turbo->setCheckable(true);
1258 turbo->setChecked(false);
1259 turbo->setShortcut(tr("Shift+Tab"));
1260 connect(turbo, &QAction::triggered, [this](bool value) {
1261 m_controller->forceFastForward(value);
1262 });
1263 addControlledAction(emulationMenu, turbo, "fastForward");
1264 m_gameActions.append(turbo);
1265
1266 QMenu* ffspeedMenu = emulationMenu->addMenu(tr("Fast forward speed"));
1267 ConfigOption* ffspeed = m_config->addOption("fastForwardRatio");
1268 ffspeed->connect([this](const QVariant& value) {
1269 reloadConfig();
1270 }, this);
1271 ffspeed->addValue(tr("Unbounded"), -1.0f, ffspeedMenu);
1272 ffspeed->setValue(QVariant(-1.0f));
1273 ffspeedMenu->addSeparator();
1274 for (i = 2; i < 11; ++i) {
1275 ffspeed->addValue(tr("%0x").arg(i), i, ffspeedMenu);
1276 }
1277 m_config->updateOption("fastForwardRatio");
1278
1279 m_shortcutController->addFunctions(emulationMenu, [this]() {
1280 if (m_controller) {
1281 m_controller->setRewinding(true);
1282 }
1283 }, [this]() {
1284 if (m_controller) {
1285 m_controller->setRewinding(false);
1286 }
1287 }, QKeySequence("`"), tr("Rewind (held)"), "holdRewind");
1288
1289 QAction* rewind = new QAction(tr("Re&wind"), emulationMenu);
1290 rewind->setShortcut(tr("~"));
1291 connect(rewind, &QAction::triggered, [this]() {
1292 m_controller->rewind();
1293 });
1294 m_gameActions.append(rewind);
1295 m_nonMpActions.append(rewind);
1296 addControlledAction(emulationMenu, rewind, "rewind");
1297
1298 QAction* frameRewind = new QAction(tr("Step backwards"), emulationMenu);
1299 frameRewind->setShortcut(tr("Ctrl+B"));
1300 connect(frameRewind, &QAction::triggered, [this] () {
1301 m_controller->rewind(1);
1302 });
1303 m_gameActions.append(frameRewind);
1304 m_nonMpActions.append(frameRewind);
1305 addControlledAction(emulationMenu, frameRewind, "frameRewind");
1306
1307 ConfigOption* videoSync = m_config->addOption("videoSync");
1308 videoSync->addBoolean(tr("Sync to &video"), emulationMenu);
1309 videoSync->connect([this](const QVariant& value) {
1310 reloadConfig();
1311 }, this);
1312 m_config->updateOption("videoSync");
1313
1314 ConfigOption* audioSync = m_config->addOption("audioSync");
1315 audioSync->addBoolean(tr("Sync to &audio"), emulationMenu);
1316 audioSync->connect([this](const QVariant& value) {
1317 reloadConfig();
1318 }, this);
1319 m_config->updateOption("audioSync");
1320
1321 emulationMenu->addSeparator();
1322
1323 QMenu* solarMenu = emulationMenu->addMenu(tr("Solar sensor"));
1324 m_shortcutController->addMenu(solarMenu);
1325 QAction* solarIncrease = new QAction(tr("Increase solar level"), solarMenu);
1326 connect(solarIncrease, &QAction::triggered, &m_inputController, &InputController::increaseLuminanceLevel);
1327 addControlledAction(solarMenu, solarIncrease, "increaseLuminanceLevel");
1328
1329 QAction* solarDecrease = new QAction(tr("Decrease solar level"), solarMenu);
1330 connect(solarDecrease, &QAction::triggered, &m_inputController, &InputController::decreaseLuminanceLevel);
1331 addControlledAction(solarMenu, solarDecrease, "decreaseLuminanceLevel");
1332
1333 QAction* maxSolar = new QAction(tr("Brightest solar level"), solarMenu);
1334 connect(maxSolar, &QAction::triggered, [this]() { m_inputController.setLuminanceLevel(10); });
1335 addControlledAction(solarMenu, maxSolar, "maxLuminanceLevel");
1336
1337 QAction* minSolar = new QAction(tr("Darkest solar level"), solarMenu);
1338 connect(minSolar, &QAction::triggered, [this]() { m_inputController.setLuminanceLevel(0); });
1339 addControlledAction(solarMenu, minSolar, "minLuminanceLevel");
1340
1341 solarMenu->addSeparator();
1342 for (int i = 0; i <= 10; ++i) {
1343 QAction* setSolar = new QAction(tr("Brightness %1").arg(QString::number(i)), solarMenu);
1344 connect(setSolar, &QAction::triggered, [this, i]() {
1345 m_inputController.setLuminanceLevel(i);
1346 });
1347 addControlledAction(solarMenu, setSolar, QString("luminanceLevel.%1").arg(QString::number(i)));
1348 }
1349
1350 QMenu* avMenu = menubar->addMenu(tr("Audio/&Video"));
1351 m_shortcutController->addMenu(avMenu);
1352 QMenu* frameMenu = avMenu->addMenu(tr("Frame size"));
1353 m_shortcutController->addMenu(frameMenu, avMenu);
1354 for (int i = 1; i <= 6; ++i) {
1355 QAction* setSize = new QAction(tr("%1x").arg(QString::number(i)), avMenu);
1356 setSize->setCheckable(true);
1357 if (m_savedScale == i) {
1358 setSize->setChecked(true);
1359 }
1360 connect(setSize, &QAction::triggered, [this, i, setSize]() {
1361 showNormal();
1362 QSize size(VIDEO_HORIZONTAL_PIXELS, VIDEO_VERTICAL_PIXELS);
1363 if (m_controller) {
1364 size = m_controller->screenDimensions();
1365 }
1366 size *= i;
1367 m_savedScale = i;
1368 m_config->setOption("scaleMultiplier", i); // TODO: Port to other
1369 resizeFrame(size);
1370 bool enableSignals = setSize->blockSignals(true);
1371 setSize->setChecked(true);
1372 setSize->blockSignals(enableSignals);
1373 });
1374 m_frameSizes[i] = setSize;
1375 addControlledAction(frameMenu, setSize, QString("frame%1x").arg(QString::number(i)));
1376 }
1377 QKeySequence fullscreenKeys;
1378#ifdef Q_OS_WIN
1379 fullscreenKeys = QKeySequence("Alt+Return");
1380#else
1381 fullscreenKeys = QKeySequence("Ctrl+F");
1382#endif
1383 addControlledAction(frameMenu, frameMenu->addAction(tr("Toggle fullscreen"), this, SLOT(toggleFullScreen()), fullscreenKeys), "fullscreen");
1384
1385 ConfigOption* lockAspectRatio = m_config->addOption("lockAspectRatio");
1386 lockAspectRatio->addBoolean(tr("Lock aspect ratio"), avMenu);
1387 lockAspectRatio->connect([this](const QVariant& value) {
1388 if (m_display) {
1389 m_display->lockAspectRatio(value.toBool());
1390 }
1391 if (m_controller) {
1392 m_screenWidget->setLockAspectRatio(value.toBool());
1393 }
1394 }, this);
1395 m_config->updateOption("lockAspectRatio");
1396
1397 ConfigOption* lockIntegerScaling = m_config->addOption("lockIntegerScaling");
1398 lockIntegerScaling->addBoolean(tr("Force integer scaling"), avMenu);
1399 lockIntegerScaling->connect([this](const QVariant& value) {
1400 if (m_display) {
1401 m_display->lockIntegerScaling(value.toBool());
1402 }
1403 if (m_controller) {
1404 m_screenWidget->setLockIntegerScaling(value.toBool());
1405 }
1406 }, this);
1407 m_config->updateOption("lockIntegerScaling");
1408
1409 ConfigOption* resampleVideo = m_config->addOption("resampleVideo");
1410 resampleVideo->addBoolean(tr("Bilinear filtering"), avMenu);
1411 resampleVideo->connect([this](const QVariant& value) {
1412 if (m_display) {
1413 m_display->filter(value.toBool());
1414 }
1415 }, this);
1416 m_config->updateOption("resampleVideo");
1417
1418 QMenu* skipMenu = avMenu->addMenu(tr("Frame&skip"));
1419 ConfigOption* skip = m_config->addOption("frameskip");
1420 skip->connect([this](const QVariant& value) {
1421 reloadConfig();
1422 }, this);
1423 for (int i = 0; i <= 10; ++i) {
1424 skip->addValue(QString::number(i), i, skipMenu);
1425 }
1426 m_config->updateOption("frameskip");
1427
1428 avMenu->addSeparator();
1429
1430 ConfigOption* mute = m_config->addOption("mute");
1431 QAction* muteAction = mute->addBoolean(tr("Mute"), avMenu);
1432 mute->connect([this](const QVariant& value) {
1433 reloadConfig();
1434 }, this);
1435 m_config->updateOption("mute");
1436 addControlledAction(avMenu, muteAction, "mute");
1437
1438 QMenu* target = avMenu->addMenu(tr("FPS target"));
1439 ConfigOption* fpsTargetOption = m_config->addOption("fpsTarget");
1440 QMap<double, QAction*> fpsTargets;
1441 for (int fps : {15, 30, 45, 60, 90, 120, 240}) {
1442 fpsTargets[fps] = fpsTargetOption->addValue(QString::number(fps), fps, target);
1443 }
1444 target->addSeparator();
1445 double nativeGB = double(GBA_ARM7TDMI_FREQUENCY) / double(VIDEO_TOTAL_LENGTH);
1446 fpsTargets[nativeGB] = fpsTargetOption->addValue(tr("Native (59.7275)"), nativeGB, target);
1447
1448 fpsTargetOption->connect([this, fpsTargets](const QVariant& value) {
1449 reloadConfig();
1450 for (auto iter = fpsTargets.begin(); iter != fpsTargets.end(); ++iter) {
1451 bool enableSignals = iter.value()->blockSignals(true);
1452 iter.value()->setChecked(abs(iter.key() - value.toDouble()) < 0.001);
1453 iter.value()->blockSignals(enableSignals);
1454 }
1455 }, this);
1456 m_config->updateOption("fpsTarget");
1457
1458 avMenu->addSeparator();
1459
1460#ifdef USE_PNG
1461 QAction* screenshot = new QAction(tr("Take &screenshot"), avMenu);
1462 screenshot->setShortcut(tr("F12"));
1463 connect(screenshot, &QAction::triggered, [this]() {
1464 m_controller->screenshot();
1465 });
1466 m_gameActions.append(screenshot);
1467 addControlledAction(avMenu, screenshot, "screenshot");
1468#endif
1469
1470#ifdef USE_FFMPEG
1471 QAction* recordOutput = new QAction(tr("Record output..."), avMenu);
1472 connect(recordOutput, &QAction::triggered, this, &Window::openVideoWindow);
1473 addControlledAction(avMenu, recordOutput, "recordOutput");
1474 m_gameActions.append(recordOutput);
1475#endif
1476
1477#ifdef USE_MAGICK
1478 QAction* recordGIF = new QAction(tr("Record GIF..."), avMenu);
1479 connect(recordGIF, &QAction::triggered, this, &Window::openGIFWindow);
1480 addControlledAction(avMenu, recordGIF, "recordGIF");
1481#endif
1482
1483 QAction* recordVL = new QAction(tr("Record video log..."), avMenu);
1484 connect(recordVL, &QAction::triggered, this, &Window::startVideoLog);
1485 addControlledAction(avMenu, recordVL, "recordVL");
1486 m_gameActions.append(recordVL);
1487
1488 QAction* stopVL = new QAction(tr("Stop video log"), avMenu);
1489 connect(stopVL, &QAction::triggered, [this]() {
1490 m_controller->endVideoLog();
1491 });
1492 addControlledAction(avMenu, stopVL, "stopVL");
1493 m_gameActions.append(stopVL);
1494
1495#ifdef M_CORE_GB
1496 QAction* gbPrint = new QAction(tr("Game Boy Printer..."), avMenu);
1497 connect(gbPrint, &QAction::triggered, [this]() {
1498 PrinterView* view = new PrinterView(m_controller);
1499 openView(view);
1500 m_controller->attachPrinter();
1501
1502 });
1503 addControlledAction(avMenu, gbPrint, "gbPrint");
1504 m_gameActions.append(gbPrint);
1505#endif
1506
1507 avMenu->addSeparator();
1508 m_videoLayers = avMenu->addMenu(tr("Video layers"));
1509 m_shortcutController->addMenu(m_videoLayers, avMenu);
1510
1511 m_audioChannels = avMenu->addMenu(tr("Audio channels"));
1512 m_shortcutController->addMenu(m_audioChannels, avMenu);
1513
1514 QAction* placementControl = new QAction(tr("Adjust layer placement..."), avMenu);
1515 connect(placementControl, &QAction::triggered, openControllerTView<PlacementControl>());
1516 m_gameActions.append(placementControl);
1517 addControlledAction(avMenu, placementControl, "placementControl");
1518
1519 QMenu* toolsMenu = menubar->addMenu(tr("&Tools"));
1520 m_shortcutController->addMenu(toolsMenu);
1521 QAction* viewLogs = new QAction(tr("View &logs..."), toolsMenu);
1522 connect(viewLogs, &QAction::triggered, m_logView, &QWidget::show);
1523 addControlledAction(toolsMenu, viewLogs, "viewLogs");
1524
1525 QAction* overrides = new QAction(tr("Game &overrides..."), toolsMenu);
1526 connect(overrides, &QAction::triggered, [this]() {
1527 if (!m_overrideView) {
1528 m_overrideView = std::move(std::make_unique<OverrideView>(m_config));
1529 if (m_controller) {
1530 m_overrideView->setController(m_controller);
1531 }
1532 connect(this, &Window::shutdown, m_overrideView.get(), &QWidget::close);
1533 }
1534 m_overrideView->show();
1535 m_overrideView->recheck();
1536 });
1537 addControlledAction(toolsMenu, overrides, "overrideWindow");
1538
1539 QAction* sensors = new QAction(tr("Game &Pak sensors..."), toolsMenu);
1540 connect(sensors, &QAction::triggered, [this]() {
1541 if (!m_sensorView) {
1542 m_sensorView = std::move(std::make_unique<SensorView>(&m_inputController));
1543 if (m_controller) {
1544 m_sensorView->setController(m_controller);
1545 }
1546 connect(this, &Window::shutdown, m_sensorView.get(), &QWidget::close);
1547 }
1548 m_sensorView->show();
1549 });
1550 addControlledAction(toolsMenu, sensors, "sensorWindow");
1551
1552 QAction* cheats = new QAction(tr("&Cheats..."), toolsMenu);
1553 connect(cheats, &QAction::triggered, openControllerTView<CheatsView>());
1554 m_gameActions.append(cheats);
1555 addControlledAction(toolsMenu, cheats, "cheatsWindow");
1556
1557 toolsMenu->addSeparator();
1558 addControlledAction(toolsMenu, toolsMenu->addAction(tr("Settings..."), this, SLOT(openSettingsWindow())),
1559 "settings");
1560
1561 toolsMenu->addSeparator();
1562
1563#ifdef USE_DEBUGGERS
1564 QAction* consoleWindow = new QAction(tr("Open debugger console..."), toolsMenu);
1565 connect(consoleWindow, &QAction::triggered, this, &Window::consoleOpen);
1566 addControlledAction(toolsMenu, consoleWindow, "debuggerWindow");
1567#endif
1568
1569#ifdef USE_GDB_STUB
1570 QAction* gdbWindow = new QAction(tr("Start &GDB server..."), toolsMenu);
1571 connect(gdbWindow, &QAction::triggered, this, &Window::gdbOpen);
1572 m_gbaActions.append(gdbWindow);
1573 m_gameActions.append(gdbWindow);
1574 addControlledAction(toolsMenu, gdbWindow, "gdbWindow");
1575#endif
1576 toolsMenu->addSeparator();
1577
1578 QAction* paletteView = new QAction(tr("View &palette..."), toolsMenu);
1579 connect(paletteView, &QAction::triggered, openControllerTView<PaletteView>());
1580 m_gameActions.append(paletteView);
1581 addControlledAction(toolsMenu, paletteView, "paletteWindow");
1582
1583 QAction* objView = new QAction(tr("View &sprites..."), toolsMenu);
1584 connect(objView, &QAction::triggered, openControllerTView<ObjView>());
1585 m_gameActions.append(objView);
1586 addControlledAction(toolsMenu, objView, "spriteWindow");
1587
1588 QAction* tileView = new QAction(tr("View &tiles..."), toolsMenu);
1589 connect(tileView, &QAction::triggered, openControllerTView<TileView>());
1590 m_gameActions.append(tileView);
1591 addControlledAction(toolsMenu, tileView, "tileWindow");
1592
1593 QAction* mapView = new QAction(tr("View &map..."), toolsMenu);
1594 connect(mapView, &QAction::triggered, openControllerTView<MapView>());
1595 m_gameActions.append(mapView);
1596 addControlledAction(toolsMenu, mapView, "mapWindow");
1597
1598 QAction* memoryView = new QAction(tr("View memory..."), toolsMenu);
1599 connect(memoryView, &QAction::triggered, openControllerTView<MemoryView>());
1600 m_gameActions.append(memoryView);
1601 addControlledAction(toolsMenu, memoryView, "memoryView");
1602
1603 QAction* memorySearch = new QAction(tr("Search memory..."), toolsMenu);
1604 connect(memorySearch, &QAction::triggered, openControllerTView<MemorySearch>());
1605 m_gameActions.append(memorySearch);
1606 addControlledAction(toolsMenu, memorySearch, "memorySearch");
1607
1608#ifdef M_CORE_GBA
1609 QAction* ioViewer = new QAction(tr("View &I/O registers..."), toolsMenu);
1610 connect(ioViewer, &QAction::triggered, openControllerTView<IOViewer>());
1611 m_gameActions.append(ioViewer);
1612 m_gbaActions.append(ioViewer);
1613 addControlledAction(toolsMenu, ioViewer, "ioViewer");
1614#endif
1615
1616 ConfigOption* skipBios = m_config->addOption("skipBios");
1617 skipBios->connect([this](const QVariant& value) {
1618 reloadConfig();
1619 }, this);
1620
1621 ConfigOption* useBios = m_config->addOption("useBios");
1622 useBios->connect([this](const QVariant& value) {
1623 reloadConfig();
1624 }, this);
1625
1626 ConfigOption* buffers = m_config->addOption("audioBuffers");
1627 buffers->connect([this](const QVariant& value) {
1628 reloadConfig();
1629 }, this);
1630
1631 ConfigOption* sampleRate = m_config->addOption("sampleRate");
1632 sampleRate->connect([this](const QVariant& value) {
1633 reloadConfig();
1634 }, this);
1635
1636 ConfigOption* volume = m_config->addOption("volume");
1637 volume->connect([this](const QVariant& value) {
1638 reloadConfig();
1639 }, this);
1640
1641 ConfigOption* volumeFf = m_config->addOption("fastForwardVolume");
1642 volumeFf->connect([this](const QVariant& value) {
1643 reloadConfig();
1644 }, this);
1645
1646 ConfigOption* muteFf = m_config->addOption("fastForwardMute");
1647 muteFf->connect([this](const QVariant& value) {
1648 reloadConfig();
1649 }, this);
1650
1651 ConfigOption* rewindEnable = m_config->addOption("rewindEnable");
1652 rewindEnable->connect([this](const QVariant& value) {
1653 reloadConfig();
1654 }, this);
1655
1656 ConfigOption* rewindBufferCapacity = m_config->addOption("rewindBufferCapacity");
1657 rewindBufferCapacity->connect([this](const QVariant& value) {
1658 reloadConfig();
1659 }, this);
1660
1661 ConfigOption* allowOpposingDirections = m_config->addOption("allowOpposingDirections");
1662 allowOpposingDirections->connect([this](const QVariant& value) {
1663 reloadConfig();
1664 }, this);
1665
1666 ConfigOption* saveStateExtdata = m_config->addOption("saveStateExtdata");
1667 saveStateExtdata->connect([this](const QVariant& value) {
1668 reloadConfig();
1669 }, this);
1670
1671 ConfigOption* loadStateExtdata = m_config->addOption("loadStateExtdata");
1672 loadStateExtdata->connect([this](const QVariant& value) {
1673 reloadConfig();
1674 }, this);
1675
1676 ConfigOption* preload = m_config->addOption("preload");
1677 preload->connect([this](const QVariant& value) {
1678 m_manager->setPreload(value.toBool());
1679 }, this);
1680 m_config->updateOption("preload");
1681
1682 ConfigOption* showFps = m_config->addOption("showFps");
1683 showFps->connect([this](const QVariant& value) {
1684 if (!value.toInt()) {
1685 m_fpsTimer.stop();
1686 updateTitle();
1687 } else if (m_controller) {
1688 m_fpsTimer.start();
1689 m_frameTimer.start();
1690 }
1691 }, this);
1692
1693 QAction* exitFullScreen = new QAction(tr("Exit fullscreen"), frameMenu);
1694 connect(exitFullScreen, &QAction::triggered, this, &Window::exitFullScreen);
1695 exitFullScreen->setShortcut(QKeySequence("Esc"));
1696 addHiddenAction(frameMenu, exitFullScreen, "exitFullScreen");
1697
1698 m_shortcutController->addFunctions(toolsMenu, [this]() {
1699 if (m_controller) {
1700 mCheatPressButton(m_controller->cheatDevice(), true);
1701 }
1702 }, [this]() {
1703 if (m_controller) {
1704 mCheatPressButton(m_controller->cheatDevice(), false);
1705 }
1706 }, QKeySequence(Qt::Key_Apostrophe), tr("GameShark Button (held)"), "holdGSButton");
1707
1708 QMenu* autofireMenu = new QMenu(tr("Autofire"), this);
1709 m_shortcutController->addMenu(autofireMenu);
1710
1711 m_shortcutController->addFunctions(autofireMenu, [this]() {
1712 m_controller->setAutofire(GBA_KEY_A, true);
1713 }, [this]() {
1714 m_controller->setAutofire(GBA_KEY_A, false);
1715 }, QKeySequence(), tr("Autofire A"), "autofireA");
1716
1717 m_shortcutController->addFunctions(autofireMenu, [this]() {
1718 m_controller->setAutofire(GBA_KEY_B, true);
1719 }, [this]() {
1720 m_controller->setAutofire(GBA_KEY_B, false);
1721 }, QKeySequence(), tr("Autofire B"), "autofireB");
1722
1723 m_shortcutController->addFunctions(autofireMenu, [this]() {
1724 m_controller->setAutofire(GBA_KEY_L, true);
1725 }, [this]() {
1726 m_controller->setAutofire(GBA_KEY_L, false);
1727 }, QKeySequence(), tr("Autofire L"), "autofireL");
1728
1729 m_shortcutController->addFunctions(autofireMenu, [this]() {
1730 m_controller->setAutofire(GBA_KEY_R, true);
1731 }, [this]() {
1732 m_controller->setAutofire(GBA_KEY_R, false);
1733 }, QKeySequence(), tr("Autofire R"), "autofireR");
1734
1735 m_shortcutController->addFunctions(autofireMenu, [this]() {
1736 m_controller->setAutofire(GBA_KEY_START, true);
1737 }, [this]() {
1738 m_controller->setAutofire(GBA_KEY_START, false);
1739 }, QKeySequence(), tr("Autofire Start"), "autofireStart");
1740
1741 m_shortcutController->addFunctions(autofireMenu, [this]() {
1742 m_controller->setAutofire(GBA_KEY_SELECT, true);
1743 }, [this]() {
1744 m_controller->setAutofire(GBA_KEY_SELECT, false);
1745 }, QKeySequence(), tr("Autofire Select"), "autofireSelect");
1746
1747 m_shortcutController->addFunctions(autofireMenu, [this]() {
1748 m_controller->setAutofire(GBA_KEY_UP, true);
1749 }, [this]() {
1750 m_controller->setAutofire(GBA_KEY_UP, false);
1751 }, QKeySequence(), tr("Autofire Up"), "autofireUp");
1752
1753 m_shortcutController->addFunctions(autofireMenu, [this]() {
1754 m_controller->setAutofire(GBA_KEY_RIGHT, true);
1755 }, [this]() {
1756 m_controller->setAutofire(GBA_KEY_RIGHT, false);
1757 }, QKeySequence(), tr("Autofire Right"), "autofireRight");
1758
1759 m_shortcutController->addFunctions(autofireMenu, [this]() {
1760 m_controller->setAutofire(GBA_KEY_DOWN, true);
1761 }, [this]() {
1762 m_controller->setAutofire(GBA_KEY_DOWN, false);
1763 }, QKeySequence(), tr("Autofire Down"), "autofireDown");
1764
1765 m_shortcutController->addFunctions(autofireMenu, [this]() {
1766 m_controller->setAutofire(GBA_KEY_LEFT, true);
1767 }, [this]() {
1768 m_controller->setAutofire(GBA_KEY_LEFT, false);
1769 }, QKeySequence(), tr("Autofire Left"), "autofireLeft");
1770
1771 for (QAction* action : m_gameActions) {
1772 action->setDisabled(true);
1773 }
1774}
1775
1776void Window::attachWidget(QWidget* widget) {
1777 m_screenWidget->layout()->addWidget(widget);
1778 m_screenWidget->unsetCursor();
1779 static_cast<QStackedLayout*>(m_screenWidget->layout())->setCurrentWidget(widget);
1780}
1781
1782void Window::detachWidget(QWidget* widget) {
1783 m_screenWidget->layout()->removeWidget(widget);
1784}
1785
1786void Window::appendMRU(const QString& fname) {
1787 int index = m_mruFiles.indexOf(fname);
1788 if (index >= 0) {
1789 m_mruFiles.removeAt(index);
1790 }
1791 m_mruFiles.prepend(fname);
1792 while (m_mruFiles.size() > ConfigController::MRU_LIST_SIZE) {
1793 m_mruFiles.removeLast();
1794 }
1795 updateMRU();
1796}
1797
1798void Window::updateMRU() {
1799 if (!m_mruMenu) {
1800 return;
1801 }
1802 for (QAction* action : m_mruMenu->actions()) {
1803 delete action;
1804 }
1805 m_mruMenu->clear();
1806 int i = 0;
1807 for (const QString& file : m_mruFiles) {
1808 QAction* item = new QAction(QDir::toNativeSeparators(file).replace("&", "&&"), m_mruMenu);
1809 item->setShortcut(QString("Ctrl+%1").arg(i));
1810 connect(item, &QAction::triggered, [this, file]() {
1811 setController(m_manager->loadGame(file), file);
1812 });
1813 m_mruMenu->addAction(item);
1814 ++i;
1815 }
1816 m_config->setMRU(m_mruFiles);
1817 m_config->write();
1818 m_mruMenu->setEnabled(i > 0);
1819}
1820
1821QAction* Window::addControlledAction(QMenu* menu, QAction* action, const QString& name) {
1822 addHiddenAction(menu, action, name);
1823 menu->addAction(action);
1824 return action;
1825}
1826
1827QAction* Window::addHiddenAction(QMenu* menu, QAction* action, const QString& name) {
1828 m_shortcutController->addAction(menu, action, name);
1829 action->setShortcutContext(Qt::WidgetShortcut);
1830 addAction(action);
1831 return action;
1832}
1833
1834void Window::focusCheck() {
1835 if (!m_config->getOption("pauseOnFocusLost").toInt() || !m_controller) {
1836 return;
1837 }
1838 if (QGuiApplication::focusWindow() && m_autoresume) {
1839 m_controller->setPaused(false);
1840 m_autoresume = false;
1841 } else if (!QGuiApplication::focusWindow() && !m_controller->isPaused()) {
1842 m_autoresume = true;
1843 m_controller->setPaused(true);
1844 }
1845}
1846
1847void Window::updateFrame() {
1848 QSize size = m_controller->screenDimensions();
1849 QImage currentImage(reinterpret_cast<const uchar*>(m_controller->drawContext()), size.width(), size.height(),
1850 size.width() * BYTES_PER_PIXEL, QImage::Format_RGBX8888);
1851 QPixmap pixmap;
1852 pixmap.convertFromImage(currentImage);
1853 m_screenWidget->setPixmap(pixmap);
1854 emit paused(true);
1855}
1856
1857void Window::setController(CoreController* controller, const QString& fname) {
1858 if (!controller) {
1859 return;
1860 }
1861
1862 if (m_controller) {
1863 m_controller->stop();
1864 QTimer::singleShot(0, this, [this, controller, fname]() {
1865 setController(controller, fname);
1866 });
1867 return;
1868 }
1869 if (!fname.isEmpty()) {
1870 setWindowFilePath(fname);
1871 appendMRU(fname);
1872 }
1873
1874 m_controller = std::shared_ptr<CoreController>(controller);
1875 m_inputController.recalibrateAxes();
1876 m_controller->setInputController(&m_inputController);
1877 m_controller->setLogger(&m_log);
1878
1879 connect(this, &Window::shutdown, [this]() {
1880 if (!m_controller) {
1881 return;
1882 }
1883 m_controller->stop();
1884 });
1885
1886 connect(m_controller.get(), &CoreController::started, this, &Window::gameStarted);
1887 connect(m_controller.get(), &CoreController::started, &m_inputController, &InputController::suspendScreensaver);
1888 connect(m_controller.get(), &CoreController::stopping, this, &Window::gameStopped);
1889 {
1890 connect(m_controller.get(), &CoreController::stopping, [this]() {
1891 m_controller.reset();
1892 });
1893 }
1894 connect(m_controller.get(), &CoreController::stopping, &m_inputController, &InputController::resumeScreensaver);
1895 connect(m_controller.get(), &CoreController::paused, this, &Window::updateFrame);
1896
1897#ifndef Q_OS_MAC
1898 connect(m_controller.get(), &CoreController::paused, menuBar(), &QWidget::show);
1899 connect(m_controller.get(), &CoreController::unpaused, [this]() {
1900 if(isFullScreen()) {
1901 menuBar()->hide();
1902 }
1903 });
1904#endif
1905
1906 connect(m_controller.get(), &CoreController::paused, &m_inputController, &InputController::resumeScreensaver);
1907 connect(m_controller.get(), &CoreController::unpaused, [this]() {
1908 emit paused(false);
1909 });
1910
1911 connect(m_controller.get(), &CoreController::stopping, m_display.get(), &Display::stopDrawing);
1912 connect(m_controller.get(), &CoreController::stateLoaded, m_display.get(), &Display::resizeContext);
1913 connect(m_controller.get(), &CoreController::stateLoaded, m_display.get(), &Display::forceDraw);
1914 connect(m_controller.get(), &CoreController::rewound, m_display.get(), &Display::forceDraw);
1915 connect(m_controller.get(), &CoreController::paused, m_display.get(), &Display::pauseDrawing);
1916 connect(m_controller.get(), &CoreController::unpaused, m_display.get(), &Display::unpauseDrawing);
1917 connect(m_controller.get(), &CoreController::frameAvailable, m_display.get(), &Display::framePosted);
1918 connect(m_controller.get(), &CoreController::statusPosted, m_display.get(), &Display::showMessage);
1919
1920 connect(m_controller.get(), &CoreController::unpaused, &m_inputController, &InputController::suspendScreensaver);
1921 connect(m_controller.get(), &CoreController::frameAvailable, this, &Window::recordFrame);
1922 connect(m_controller.get(), &CoreController::crashed, this, &Window::gameCrashed);
1923 connect(m_controller.get(), &CoreController::failed, this, &Window::gameFailed);
1924 connect(m_controller.get(), &CoreController::unimplementedBiosCall, this, &Window::unimplementedBiosCall);
1925
1926#ifdef USE_GDB_STUB
1927 if (m_gdbController) {
1928 m_gdbController->setController(m_controller);
1929 }
1930#endif
1931
1932#ifdef USE_DEBUGGERS
1933 if (m_console) {
1934 m_console->setController(m_controller);
1935 }
1936#endif
1937
1938#ifdef USE_MAGICK
1939 if (m_gifView) {
1940 m_gifView->setController(m_controller);
1941 }
1942#endif
1943
1944#ifdef USE_FFMPEG
1945 if (m_videoView) {
1946 m_videoView->setController(m_controller);
1947 }
1948#endif
1949
1950 if (m_sensorView) {
1951 m_sensorView->setController(m_controller);
1952 }
1953
1954 if (m_overrideView) {
1955 m_overrideView->setController(m_controller);
1956 }
1957
1958 if (!m_pendingPatch.isEmpty()) {
1959 m_controller->loadPatch(m_pendingPatch);
1960 m_pendingPatch = QString();
1961 }
1962
1963 m_controller->loadConfig(m_config);
1964 m_controller->start();
1965
1966 if (!m_pendingState.isEmpty()) {
1967 m_controller->loadState(m_pendingState);
1968 m_pendingState = QString();
1969 }
1970
1971 if (m_pendingPause) {
1972 m_controller->setPaused(true);
1973 m_pendingPause = false;
1974 }
1975}
1976
1977WindowBackground::WindowBackground(QWidget* parent)
1978 : QWidget(parent)
1979{
1980 setLayout(new QStackedLayout());
1981 layout()->setContentsMargins(0, 0, 0, 0);
1982}
1983
1984void WindowBackground::setPixmap(const QPixmap& pmap) {
1985 m_pixmap = pmap;
1986 update();
1987}
1988
1989void WindowBackground::setSizeHint(const QSize& hint) {
1990 m_sizeHint = hint;
1991}
1992
1993QSize WindowBackground::sizeHint() const {
1994 return m_sizeHint;
1995}
1996
1997void WindowBackground::setDimensions(int width, int height) {
1998 m_aspectWidth = width;
1999 m_aspectHeight = height;
2000}
2001
2002void WindowBackground::setLockIntegerScaling(bool lock) {
2003 m_lockIntegerScaling = lock;
2004}
2005
2006void WindowBackground::setLockAspectRatio(bool lock) {
2007 m_lockAspectRatio = lock;
2008}
2009
2010void WindowBackground::paintEvent(QPaintEvent* event) {
2011 QWidget::paintEvent(event);
2012 const QPixmap& logo = pixmap();
2013 QPainter painter(this);
2014 painter.setRenderHint(QPainter::SmoothPixmapTransform);
2015 painter.fillRect(QRect(QPoint(), size()), Qt::black);
2016 QSize s = size();
2017 QSize ds = s;
2018 if (m_lockAspectRatio) {
2019 if (ds.width() * m_aspectHeight > ds.height() * m_aspectWidth) {
2020 ds.setWidth(ds.height() * m_aspectWidth / m_aspectHeight);
2021 } else if (ds.width() * m_aspectHeight < ds.height() * m_aspectWidth) {
2022 ds.setHeight(ds.width() * m_aspectHeight / m_aspectWidth);
2023 }
2024 }
2025 if (m_lockIntegerScaling) {
2026 ds.setWidth(ds.width() - ds.width() % m_aspectWidth);
2027 ds.setHeight(ds.height() - ds.height() % m_aspectHeight);
2028 }
2029 QPoint origin = QPoint((s.width() - ds.width()) / 2, (s.height() - ds.height()) / 2);
2030 QRect full(origin, ds);
2031 painter.drawPixmap(full, logo);
2032}