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