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