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