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