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