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*) {
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) {
878 // TODO: Mention which call?
879 if (m_hitUnimplementedBiosCall) {
880 return;
881 }
882 m_hitUnimplementedBiosCall = true;
883
884 QMessageBox* fail = new QMessageBox(
885 QMessageBox::Warning, tr("Unimplemented BIOS call"),
886 tr("This game uses a BIOS call that is not implemented. Please use the official BIOS for best experience."),
887 QMessageBox::Ok, this, Qt::Sheet);
888 fail->setAttribute(Qt::WA_DeleteOnClose);
889 fail->show();
890}
891
892void Window::reloadDisplayDriver() {
893 if (m_controller) {
894 m_display->stopDrawing();
895 detachWidget(m_display.get());
896 }
897 m_display = std::move(std::unique_ptr<Display>(Display::create(this)));
898#if defined(BUILD_GL) || defined(BUILD_GLES2)
899 m_shaderView.reset();
900 m_shaderView = std::make_unique<ShaderSelector>(m_display.get(), m_config);
901#endif
902
903 connect(m_display.get(), &Display::hideCursor, [this]() {
904 if (static_cast<QStackedLayout*>(m_screenWidget->layout())->currentWidget() == m_display.get()) {
905 m_screenWidget->setCursor(Qt::BlankCursor);
906 }
907 });
908 connect(m_display.get(), &Display::showCursor, [this]() {
909 m_screenWidget->unsetCursor();
910 });
911
912 const mCoreOptions* opts = m_config->options();
913 m_display->lockAspectRatio(opts->lockAspectRatio);
914 m_display->lockIntegerScaling(opts->lockIntegerScaling);
915 m_display->interframeBlending(opts->interframeBlending);
916 m_display->filter(opts->resampleVideo);
917 m_screenWidget->filter(opts->resampleVideo);
918 m_config->updateOption("showOSD");
919#if defined(BUILD_GL) || defined(BUILD_GLES2)
920 if (opts->shader) {
921 struct VDir* shader = VDirOpen(opts->shader);
922 if (shader && m_display->supportsShaders()) {
923 m_display->setShaders(shader);
924 m_shaderView->refreshShaders();
925 shader->close(shader);
926 }
927 }
928#endif
929
930 if (m_controller) {
931 attachDisplay();
932
933 attachWidget(m_display.get());
934 m_display->startDrawing(m_controller);
935 }
936#ifdef M_CORE_GB
937 m_display->setMinimumSize(GB_VIDEO_HORIZONTAL_PIXELS, GB_VIDEO_VERTICAL_PIXELS);
938#elif defined(M_CORE_GBA)
939 m_display->setMinimumSize(GBA_VIDEO_HORIZONTAL_PIXELS, GBA_VIDEO_VERTICAL_PIXELS);
940#endif
941}
942
943void Window::reloadAudioDriver() {
944 if (!m_controller) {
945 return;
946 }
947 if (m_audioProcessor) {
948 m_audioProcessor->stop();
949 m_audioProcessor.reset();
950 }
951
952 const mCoreOptions* opts = m_config->options();
953 m_audioProcessor = std::move(std::unique_ptr<AudioProcessor>(AudioProcessor::create()));
954 m_audioProcessor->setInput(m_controller);
955 m_audioProcessor->setBufferSamples(opts->audioBuffers);
956 m_audioProcessor->requestSampleRate(opts->sampleRate);
957 m_audioProcessor->start();
958 connect(m_controller.get(), &CoreController::stopping, m_audioProcessor.get(), &AudioProcessor::stop);
959 connect(m_controller.get(), &CoreController::fastForwardChanged, m_audioProcessor.get(), &AudioProcessor::inputParametersChanged);
960 connect(m_controller.get(), &CoreController::paused, m_audioProcessor.get(), &AudioProcessor::pause);
961 connect(m_controller.get(), &CoreController::unpaused, m_audioProcessor.get(), &AudioProcessor::start);
962}
963
964void Window::changeRenderer() {
965 if (!m_controller) {
966 return;
967 }
968 if (m_config->getOption("hwaccelVideo").toInt() && m_display->supportsShaders() && m_controller->supportsFeature(CoreController::Feature::OPENGL)) {
969 std::shared_ptr<VideoProxy> proxy = m_display->videoProxy();
970 if (!proxy) {
971 proxy = std::make_shared<VideoProxy>();
972 }
973 m_display->setVideoProxy(proxy);
974 proxy->attach(m_controller.get());
975
976 int fb = m_display->framebufferHandle();
977 if (fb >= 0) {
978 m_controller->setFramebufferHandle(fb);
979 }
980 } else {
981 m_controller->setFramebufferHandle(-1);
982 }
983}
984
985void Window::tryMakePortable() {
986 QMessageBox* confirm = new QMessageBox(QMessageBox::Question, tr("Really make portable?"),
987 tr("This will make the emulator load its configuration from the same directory as the executable. Do you want to continue?"),
988 QMessageBox::Yes | QMessageBox::Cancel, this, Qt::Sheet);
989 confirm->setAttribute(Qt::WA_DeleteOnClose);
990 connect(confirm->button(QMessageBox::Yes), &QAbstractButton::clicked, m_config, &ConfigController::makePortable);
991 confirm->show();
992}
993
994void Window::mustRestart() {
995 if (m_mustRestart.isActive()) {
996 return;
997 }
998 m_mustRestart.start();
999 QMessageBox* dialog = new QMessageBox(QMessageBox::Warning, tr("Restart needed"),
1000 tr("Some changes will not take effect until the emulator is restarted."),
1001 QMessageBox::Ok, this, Qt::Sheet);
1002 dialog->setAttribute(Qt::WA_DeleteOnClose);
1003 dialog->show();
1004}
1005
1006void Window::recordFrame() {
1007 m_frameList.append(m_frameTimer.nsecsElapsed());
1008 m_frameTimer.restart();
1009}
1010
1011void Window::showFPS() {
1012 if (m_frameList.isEmpty()) {
1013 updateTitle();
1014 return;
1015 }
1016 qint64 total = 0;
1017 for (qint64 t : m_frameList) {
1018 total += t;
1019 }
1020 double fps = (m_frameList.size() * 1e10) / total;
1021 m_frameList.clear();
1022 fps = round(fps) / 10.f;
1023 updateTitle(fps);
1024}
1025
1026void Window::updateTitle(float fps) {
1027 QString title;
1028
1029 if (m_controller) {
1030 CoreController::Interrupter interrupter(m_controller);
1031 const NoIntroDB* db = GBAApp::app()->gameDB();
1032 NoIntroGame game{};
1033 uint32_t crc32 = 0;
1034 mCore* core = m_controller->thread()->core;
1035 core->checksum(m_controller->thread()->core, &crc32, CHECKSUM_CRC32);
1036 QString filePath = windowFilePath();
1037
1038 if (m_config->getOption("showFilename").toInt() && !filePath.isNull()) {
1039 QFileInfo fileInfo(filePath);
1040 title = fileInfo.fileName();
1041 } else {
1042 char gameTitle[17] = { '\0' };
1043 core->getGameTitle(core, gameTitle);
1044 title = gameTitle;
1045
1046#ifdef USE_SQLITE3
1047 if (db && crc32 && NoIntroDBLookupGameByCRC(db, crc32, &game)) {
1048 title = QLatin1String(game.name);
1049 }
1050#endif
1051 }
1052
1053 MultiplayerController* multiplayer = m_controller->multiplayerController();
1054 if (multiplayer && multiplayer->attached() > 1) {
1055 title += tr(" - Player %1 of %2").arg(multiplayer->playerId(m_controller.get()) + 1).arg(multiplayer->attached());
1056 for (Action* action : m_nonMpActions) {
1057 action->setEnabled(false);
1058 }
1059 } else {
1060 for (Action* action : m_nonMpActions) {
1061 action->setEnabled(true);
1062 }
1063 }
1064 }
1065 if (title.isNull()) {
1066 setWindowTitle(tr("%1 - %2").arg(projectName).arg(projectVersion));
1067 } else if (fps < 0) {
1068 setWindowTitle(tr("%1 - %2 - %3").arg(projectName).arg(title).arg(projectVersion));
1069 } else {
1070 setWindowTitle(tr("%1 - %2 (%3 fps) - %4").arg(projectName).arg(title).arg(fps).arg(projectVersion));
1071 }
1072}
1073
1074void Window::openStateWindow(LoadSave ls) {
1075 if (m_stateWindow) {
1076 return;
1077 }
1078 MultiplayerController* multiplayer = m_controller->multiplayerController();
1079 if (multiplayer && multiplayer->attached() > 1) {
1080 return;
1081 }
1082 bool wasPaused = m_controller->isPaused();
1083 m_stateWindow = new LoadSaveState(m_controller);
1084 connect(this, &Window::shutdown, m_stateWindow, &QWidget::close);
1085 connect(m_stateWindow, &LoadSaveState::closed, [this]() {
1086 detachWidget(m_stateWindow);
1087 m_stateWindow = nullptr;
1088 QMetaObject::invokeMethod(this, "setFocus", Qt::QueuedConnection);
1089 });
1090 if (!wasPaused) {
1091 m_controller->setPaused(true);
1092 connect(m_stateWindow, &LoadSaveState::closed, [this]() {
1093 if (m_controller) {
1094 m_controller->setPaused(false);
1095 }
1096 });
1097 }
1098 m_stateWindow->setAttribute(Qt::WA_DeleteOnClose);
1099 m_stateWindow->setMode(ls);
1100 updateFrame();
1101#ifndef Q_OS_MAC
1102 menuBar()->show();
1103#endif
1104 attachWidget(m_stateWindow);
1105}
1106
1107void Window::setupMenu(QMenuBar* menubar) {
1108 installEventFilter(m_shortcutController);
1109
1110 menubar->clear();
1111 m_actions.addMenu(tr("&File"), "file");
1112
1113 m_actions.addAction(tr("Load &ROM..."), "loadROM", this, &Window::selectROM, "file", QKeySequence::Open);
1114
1115#ifdef USE_SQLITE3
1116 m_actions.addAction(tr("Load ROM in archive..."), "loadROMInArchive", this, &Window::selectROMInArchive, "file");
1117 m_actions.addAction(tr("Add folder to library..."), "addDirToLibrary", this, &Window::addDirToLibrary, "file");
1118#endif
1119
1120 addGameAction(tr("Load alternate save..."), "loadAlternateSave", [this]() {
1121 this->selectSave(false);
1122 }, "file");
1123 addGameAction(tr("Load temporary save..."), "loadTemporarySave", [this]() {
1124 this->selectSave(true);
1125 }, "file");
1126
1127 m_actions.addAction(tr("Load &patch..."), "loadPatch", this, &Window::selectPatch, "file");
1128
1129#ifdef M_CORE_GBA
1130 m_actions.addAction(tr("Boot BIOS"), "bootBIOS", [this]() {
1131 setController(m_manager->loadBIOS(PLATFORM_GBA, m_config->getOption("gba.bios")), QString());
1132 }, "file");
1133#endif
1134
1135 addGameAction(tr("Replace ROM..."), "replaceROM", this, &Window::replaceROM, "file");
1136#ifdef M_CORE_GBA
1137 Action* scanCard = addGameAction(tr("Scan e-Reader dotcodes..."), "scanCard", this, &Window::scanCard, "file");
1138 m_platformActions.insert(PLATFORM_GBA, scanCard);
1139#endif
1140
1141 addGameAction(tr("ROM &info..."), "romInfo", openControllerTView<ROMInfo>(), "file");
1142
1143 m_actions.addMenu(tr("Recent"), "mru", "file");
1144 m_actions.addSeparator("file");
1145
1146 m_actions.addAction(tr("Make portable"), "makePortable", this, &Window::tryMakePortable, "file");
1147 m_actions.addSeparator("file");
1148
1149 Action* loadState = addGameAction(tr("&Load state"), "loadState", [this]() {
1150 this->openStateWindow(LoadSave::LOAD);
1151 }, "file", QKeySequence("F10"));
1152 m_nonMpActions.append(loadState);
1153
1154 Action* loadStateFile = addGameAction(tr("Load state file..."), "loadStateFile", [this]() {
1155 this->selectState(true);
1156 }, "file");
1157 m_nonMpActions.append(loadStateFile);
1158
1159 Action* saveState = addGameAction(tr("&Save state"), "saveState", [this]() {
1160 this->openStateWindow(LoadSave::SAVE);
1161 }, "file", QKeySequence("Shift+F10"));
1162 m_nonMpActions.append(saveState);
1163
1164 Action* saveStateFile = addGameAction(tr("Save state file..."), "saveStateFile", [this]() {
1165 this->selectState(false);
1166 }, "file");
1167 m_nonMpActions.append(saveStateFile);
1168
1169 m_actions.addMenu(tr("Quick load"), "quickLoad", "file");
1170 m_actions.addMenu(tr("Quick save"), "quickSave", "file");
1171
1172 Action* quickLoad = addGameAction(tr("Load recent"), "quickLoad", [this] {
1173 m_controller->loadState();
1174 }, "quickLoad");
1175 m_nonMpActions.append(quickLoad);
1176
1177 Action* quickSave = addGameAction(tr("Save recent"), "quickSave", [this] {
1178 m_controller->saveState();
1179 }, "quickSave");
1180 m_nonMpActions.append(quickSave);
1181
1182 m_actions.addSeparator("quickLoad");
1183 m_actions.addSeparator("quickSave");
1184
1185 Action* undoLoadState = addGameAction(tr("Undo load state"), "undoLoadState", &CoreController::loadBackupState, "quickLoad", QKeySequence("F11"));
1186 m_nonMpActions.append(undoLoadState);
1187
1188 Action* undoSaveState = addGameAction(tr("Undo save state"), "undoSaveState", &CoreController::saveBackupState, "quickSave", QKeySequence("Shift+F11"));
1189 m_nonMpActions.append(undoSaveState);
1190
1191 m_actions.addSeparator("quickLoad");
1192 m_actions.addSeparator("quickSave");
1193
1194 for (int i = 1; i < 10; ++i) {
1195 Action* quickLoad = addGameAction(tr("State &%1").arg(i), QString("quickLoad.%1").arg(i), [this, i]() {
1196 m_controller->loadState(i);
1197 }, "quickLoad", QString("F%1").arg(i));
1198 m_nonMpActions.append(quickLoad);
1199
1200 Action* quickSave = addGameAction(tr("State &%1").arg(i), QString("quickSave.%1").arg(i), [this, i]() {
1201 m_controller->saveState(i);
1202 }, "quickSave", QString("Shift+F%1").arg(i));
1203 m_nonMpActions.append(quickSave);
1204 }
1205
1206 m_actions.addSeparator("file");
1207 m_actions.addAction(tr("Load camera image..."), "loadCamImage", this, &Window::loadCamImage, "file");
1208
1209#ifdef M_CORE_GBA
1210 m_actions.addSeparator("file");
1211 Action* importShark = addGameAction(tr("Import GameShark Save..."), "importShark", this, &Window::importSharkport, "file");
1212 m_platformActions.insert(PLATFORM_GBA, importShark);
1213
1214 Action* exportShark = addGameAction(tr("Export GameShark Save..."), "exportShark", this, &Window::exportSharkport, "file");
1215 m_platformActions.insert(PLATFORM_GBA, exportShark);
1216#endif
1217
1218 m_actions.addSeparator("file");
1219 m_multiWindow = m_actions.addAction(tr("New multiplayer window"), "multiWindow", [this]() {
1220 GBAApp::app()->newWindow();
1221 }, "file");
1222
1223#ifndef Q_OS_MAC
1224 m_actions.addSeparator("file");
1225#endif
1226
1227 m_actions.addAction(tr("About..."), "about", openTView<AboutScreen>(), "file");
1228
1229#ifndef Q_OS_MAC
1230 m_actions.addAction(tr("E&xit"), "quit", static_cast<QWidget*>(this), &QWidget::close, "file", QKeySequence::Quit);
1231#endif
1232
1233 m_actions.addMenu(tr("&Emulation"), "emu");
1234 addGameAction(tr("&Reset"), "reset", &CoreController::reset, "emu", QKeySequence("Ctrl+R"));
1235 addGameAction(tr("Sh&utdown"), "shutdown", &CoreController::stop, "emu");
1236 addGameAction(tr("Yank game pak"), "yank", &CoreController::yankPak, "emu");
1237
1238 m_actions.addSeparator("emu");
1239
1240 Action* pause = m_actions.addBooleanAction(tr("&Pause"), "pause", [this](bool paused) {
1241 if (m_controller) {
1242 m_controller->setPaused(paused);
1243 } else {
1244 m_pendingPause = paused;
1245 }
1246 }, "emu", QKeySequence("Ctrl+P"));
1247 connect(this, &Window::paused, pause, &Action::setActive);
1248
1249 addGameAction(tr("&Next frame"), "frameAdvance", &CoreController::frameAdvance, "emu", QKeySequence("Ctrl+N"));
1250
1251 m_actions.addSeparator("emu");
1252
1253 m_actions.addHeldAction(tr("Fast forward (held)"), "holdFastForward", [this](bool held) {
1254 if (m_controller) {
1255 m_controller->setFastForward(held);
1256 }
1257 }, "emu", QKeySequence(Qt::Key_Tab));
1258
1259 addGameAction(tr("&Fast forward"), "fastForward", [this](bool value) {
1260 m_controller->forceFastForward(value);
1261 }, "emu", QKeySequence("Shift+Tab"));
1262
1263 m_actions.addMenu(tr("Fast forward speed"), "fastForwardSpeed", "emu");
1264 ConfigOption* ffspeed = m_config->addOption("fastForwardRatio");
1265 ffspeed->connect([this](const QVariant&) {
1266 reloadConfig();
1267 }, this);
1268 ffspeed->addValue(tr("Unbounded"), -1.0f, &m_actions, "fastForwardSpeed");
1269 ffspeed->setValue(QVariant(-1.0f));
1270 m_actions.addSeparator("fastForwardSpeed");
1271 for (int i = 2; i < 11; ++i) {
1272 ffspeed->addValue(tr("%0x").arg(i), i, &m_actions, "fastForwardSpeed");
1273 }
1274 m_config->updateOption("fastForwardRatio");
1275
1276 Action* rewindHeld = m_actions.addHeldAction(tr("Rewind (held)"), "holdRewind", [this](bool held) {
1277 if (m_controller) {
1278 m_controller->setRewinding(held);
1279 }
1280 }, "emu", QKeySequence("`"));
1281 m_nonMpActions.append(rewindHeld);
1282
1283 Action* rewind = addGameAction(tr("Re&wind"), "rewind", [this]() {
1284 m_controller->rewind();
1285 }, "emu", QKeySequence("~"));
1286 m_nonMpActions.append(rewind);
1287
1288 Action* frameRewind = addGameAction(tr("Step backwards"), "frameRewind", [this] () {
1289 m_controller->rewind(1);
1290 }, "emu", QKeySequence("Ctrl+B"));
1291 m_nonMpActions.append(frameRewind);
1292
1293 ConfigOption* videoSync = m_config->addOption("videoSync");
1294 videoSync->addBoolean(tr("Sync to &video"), &m_actions, "emu");
1295 videoSync->connect([this](const QVariant&) {
1296 reloadConfig();
1297 }, this);
1298 m_config->updateOption("videoSync");
1299
1300 ConfigOption* audioSync = m_config->addOption("audioSync");
1301 audioSync->addBoolean(tr("Sync to &audio"), &m_actions, "emu");
1302 audioSync->connect([this](const QVariant&) {
1303 reloadConfig();
1304 }, this);
1305 m_config->updateOption("audioSync");
1306
1307 m_actions.addSeparator("emu");
1308
1309 m_actions.addMenu(tr("Solar sensor"), "solar", "emu");
1310 m_actions.addAction(tr("Increase solar level"), "increaseLuminanceLevel", &m_inputController, &InputController::increaseLuminanceLevel, "solar");
1311 m_actions.addAction(tr("Decrease solar level"), "decreaseLuminanceLevel", &m_inputController, &InputController::decreaseLuminanceLevel, "solar");
1312 m_actions.addAction(tr("Brightest solar level"), "maxLuminanceLevel", [this]() {
1313 m_inputController.setLuminanceLevel(10);
1314 }, "solar");
1315 m_actions.addAction(tr("Darkest solar level"), "minLuminanceLevel", [this]() {
1316 m_inputController.setLuminanceLevel(0);
1317 }, "solar");
1318
1319 m_actions.addSeparator("solar");
1320 for (int i = 0; i <= 10; ++i) {
1321 m_actions.addAction(tr("Brightness %1").arg(QString::number(i)), QString("luminanceLevel.%1").arg(QString::number(i)), [this, i]() {
1322 m_inputController.setLuminanceLevel(i);
1323 }, "solar");
1324 }
1325
1326#ifdef M_CORE_GB
1327 Action* gbPrint = addGameAction(tr("Game Boy Printer..."), "gbPrint", [this]() {
1328 PrinterView* view = new PrinterView(m_controller);
1329 openView(view);
1330 m_controller->attachPrinter();
1331 }, "emu");
1332 m_platformActions.insert(PLATFORM_GB, gbPrint);
1333#endif
1334
1335#ifdef M_CORE_GBA
1336 Action* bcGate = addGameAction(tr("BattleChip Gate..."), "bcGate", openControllerTView<BattleChipView>(this), "emu");
1337 m_platformActions.insert(PLATFORM_GBA, bcGate);
1338#endif
1339
1340 m_actions.addMenu(tr("Audio/&Video"), "av");
1341 m_actions.addMenu(tr("Frame size"), "frame", "av");
1342 for (int i = 1; i <= 8; ++i) {
1343 Action* setSize = m_actions.addAction(tr("%1×").arg(QString::number(i)), QString("frame.%1x").arg(QString::number(i)), [this, i]() {
1344 Action* setSize = m_frameSizes[i];
1345 showNormal();
1346 QSize size(GBA_VIDEO_HORIZONTAL_PIXELS, GBA_VIDEO_VERTICAL_PIXELS);
1347 if (m_controller) {
1348 size = m_controller->screenDimensions();
1349 }
1350 size *= i;
1351 m_savedScale = i;
1352 m_config->setOption("scaleMultiplier", i); // TODO: Port to other
1353 resizeFrame(size);
1354 setSize->setActive(true);
1355 }, "frame");
1356 setSize->setExclusive(true);
1357 if (m_savedScale == i) {
1358 setSize->setActive(true);
1359 }
1360 m_frameSizes[i] = setSize;
1361 }
1362 QKeySequence fullscreenKeys;
1363#ifdef Q_OS_WIN
1364 fullscreenKeys = QKeySequence("Alt+Return");
1365#else
1366 fullscreenKeys = QKeySequence("Ctrl+F");
1367#endif
1368 m_actions.addAction(tr("Toggle fullscreen"), "fullscreen", this, &Window::toggleFullScreen, "frame", fullscreenKeys);
1369
1370 ConfigOption* lockAspectRatio = m_config->addOption("lockAspectRatio");
1371 lockAspectRatio->addBoolean(tr("Lock aspect ratio"), &m_actions, "av");
1372 lockAspectRatio->connect([this](const QVariant& value) {
1373 if (m_display) {
1374 m_display->lockAspectRatio(value.toBool());
1375 }
1376 if (m_controller) {
1377 m_screenWidget->setLockAspectRatio(value.toBool());
1378 }
1379 }, this);
1380 m_config->updateOption("lockAspectRatio");
1381
1382 ConfigOption* lockIntegerScaling = m_config->addOption("lockIntegerScaling");
1383 lockIntegerScaling->addBoolean(tr("Force integer scaling"), &m_actions, "av");
1384 lockIntegerScaling->connect([this](const QVariant& value) {
1385 if (m_display) {
1386 m_display->lockIntegerScaling(value.toBool());
1387 }
1388 if (m_controller) {
1389 m_screenWidget->setLockIntegerScaling(value.toBool());
1390 }
1391 }, this);
1392 m_config->updateOption("lockIntegerScaling");
1393
1394 ConfigOption* interframeBlending = m_config->addOption("interframeBlending");
1395 interframeBlending->addBoolean(tr("Interframe blending"), &m_actions, "av");
1396 interframeBlending->connect([this](const QVariant& value) {
1397 if (m_display) {
1398 m_display->interframeBlending(value.toBool());
1399 }
1400 }, this);
1401 m_config->updateOption("interframeBlending");
1402
1403 ConfigOption* resampleVideo = m_config->addOption("resampleVideo");
1404 resampleVideo->addBoolean(tr("Bilinear filtering"), &m_actions, "av");
1405 resampleVideo->connect([this](const QVariant& value) {
1406 if (m_display) {
1407 m_display->filter(value.toBool());
1408 }
1409 m_screenWidget->filter(value.toBool());
1410 }, this);
1411 m_config->updateOption("resampleVideo");
1412
1413 m_actions.addMenu(tr("Frame&skip"),"skip", "av");
1414 ConfigOption* skip = m_config->addOption("frameskip");
1415 skip->connect([this](const QVariant&) {
1416 reloadConfig();
1417 }, this);
1418 for (int i = 0; i <= 10; ++i) {
1419 skip->addValue(QString::number(i), i, &m_actions, "skip");
1420 }
1421 m_config->updateOption("frameskip");
1422
1423 m_actions.addSeparator("av");
1424
1425 ConfigOption* mute = m_config->addOption("mute");
1426 mute->addBoolean(tr("Mute"), &m_actions, "av");
1427 mute->connect([this](const QVariant& value) {
1428 if (value.toInt()) {
1429 m_config->setOption("fastForwardMute", true);
1430 }
1431 reloadConfig();
1432 }, this);
1433 m_config->updateOption("mute");
1434
1435 m_actions.addMenu(tr("FPS target"),"target", "av");
1436 ConfigOption* fpsTargetOption = m_config->addOption("fpsTarget");
1437 QMap<double, Action*> fpsTargets;
1438 for (int fps : {15, 30, 45, 60, 90, 120, 240}) {
1439 fpsTargets[fps] = fpsTargetOption->addValue(QString::number(fps), fps, &m_actions, "target");
1440 }
1441 m_actions.addSeparator("target");
1442 double nativeGB = double(GBA_ARM7TDMI_FREQUENCY) / double(VIDEO_TOTAL_LENGTH);
1443 fpsTargets[nativeGB] = fpsTargetOption->addValue(tr("Native (59.7275)"), nativeGB, &m_actions, "target");
1444
1445 fpsTargetOption->connect([this, fpsTargets](const QVariant& value) {
1446 reloadConfig();
1447 for (auto iter = fpsTargets.begin(); iter != fpsTargets.end(); ++iter) {
1448 bool enableSignals = iter.value()->blockSignals(true);
1449 iter.value()->setActive(abs(iter.key() - value.toDouble()) < 0.001);
1450 iter.value()->blockSignals(enableSignals);
1451 }
1452 }, this);
1453 m_config->updateOption("fpsTarget");
1454
1455 m_actions.addSeparator("av");
1456
1457#ifdef USE_PNG
1458 addGameAction(tr("Take &screenshot"), "screenshot", [this]() {
1459 m_controller->screenshot();
1460 }, "av", tr("F12"));
1461#endif
1462
1463#ifdef USE_FFMPEG
1464 addGameAction(tr("Record A/V..."), "recordOutput", this, &Window::openVideoWindow, "av");
1465 addGameAction(tr("Record GIF/WebP/APNG..."), "recordGIF", this, &Window::openGIFWindow, "av");
1466#endif
1467
1468 m_actions.addSeparator("av");
1469 m_actions.addMenu(tr("Video layers"), "videoLayers", "av");
1470 m_actions.addMenu(tr("Audio channels"), "audioChannels", "av");
1471
1472 addGameAction(tr("Adjust layer placement..."), "placementControl", openControllerTView<PlacementControl>(), "av");
1473
1474 m_actions.addMenu(tr("&Tools"), "tools");
1475 m_actions.addAction(tr("View &logs..."), "viewLogs", static_cast<QWidget*>(m_logView), &QWidget::show, "tools");
1476
1477 m_actions.addAction(tr("Game &overrides..."), "overrideWindow", [this]() {
1478 if (!m_overrideView) {
1479 m_overrideView = std::move(std::make_unique<OverrideView>(m_config));
1480 if (m_controller) {
1481 m_overrideView->setController(m_controller);
1482 }
1483 connect(this, &Window::shutdown, m_overrideView.get(), &QWidget::close);
1484 }
1485 m_overrideView->show();
1486 m_overrideView->recheck();
1487 }, "tools");
1488
1489 m_actions.addAction(tr("Game Pak sensors..."), "sensorWindow", [this]() {
1490 if (!m_sensorView) {
1491 m_sensorView = std::move(std::make_unique<SensorView>(&m_inputController));
1492 if (m_controller) {
1493 m_sensorView->setController(m_controller);
1494 }
1495 connect(this, &Window::shutdown, m_sensorView.get(), &QWidget::close);
1496 }
1497 m_sensorView->show();
1498 }, "tools");
1499
1500 addGameAction(tr("&Cheats..."), "cheatsWindow", openControllerTView<CheatsView>(), "tools");
1501
1502 m_actions.addSeparator("tools");
1503 m_actions.addAction(tr("Settings..."), "settings", this, &Window::openSettingsWindow, "tools");
1504
1505#ifdef USE_DEBUGGERS
1506 m_actions.addSeparator("tools");
1507 m_actions.addAction(tr("Open debugger console..."), "debuggerWindow", this, &Window::consoleOpen, "tools");
1508#ifdef USE_GDB_STUB
1509 Action* gdbWindow = addGameAction(tr("Start &GDB server..."), "gdbWindow", this, &Window::gdbOpen, "tools");
1510 m_platformActions.insert(PLATFORM_GBA, gdbWindow);
1511#endif
1512#endif
1513 m_actions.addSeparator("tools");
1514
1515 addGameAction(tr("View &palette..."), "paletteWindow", openControllerTView<PaletteView>(), "tools");
1516 addGameAction(tr("View &sprites..."), "spriteWindow", openControllerTView<ObjView>(), "tools");
1517 addGameAction(tr("View &tiles..."), "tileWindow", openControllerTView<TileView>(), "tools");
1518 addGameAction(tr("View &map..."), "mapWindow", openControllerTView<MapView>(), "tools");
1519
1520#ifdef M_CORE_GBA
1521 Action* frameWindow = addGameAction(tr("&Frame inspector..."), "frameWindow", [this]() {
1522 if (!m_frameView) {
1523 m_frameView = new FrameView(m_controller);
1524 connect(this, &Window::shutdown, this, [this]() {
1525 if (m_frameView) {
1526 m_frameView->close();
1527 }
1528 });
1529 connect(m_frameView, &QObject::destroyed, this, [this]() {
1530 m_frameView = nullptr;
1531 });
1532 m_frameView->setAttribute(Qt::WA_DeleteOnClose);
1533 }
1534 m_frameView->show();
1535 }, "tools");
1536 m_platformActions.insert(PLATFORM_GBA, frameWindow);
1537#endif
1538
1539 addGameAction(tr("View memory..."), "memoryView", openControllerTView<MemoryView>(), "tools");
1540 addGameAction(tr("Search memory..."), "memorySearch", openControllerTView<MemorySearch>(), "tools");
1541
1542#ifdef M_CORE_GBA
1543 Action* ioViewer = addGameAction(tr("View &I/O registers..."), "ioViewer", openControllerTView<IOViewer>(), "tools");
1544 m_platformActions.insert(PLATFORM_GBA, ioViewer);
1545#endif
1546
1547 m_actions.addSeparator("tools");
1548 addGameAction(tr("Record debug video log..."), "recordVL", this, &Window::startVideoLog, "tools");
1549 addGameAction(tr("Stop debug video log"), "stopVL", [this]() {
1550 m_controller->endVideoLog();
1551 }, "tools");
1552
1553 ConfigOption* skipBios = m_config->addOption("skipBios");
1554 skipBios->connect([this](const QVariant&) {
1555 reloadConfig();
1556 }, this);
1557
1558 ConfigOption* useBios = m_config->addOption("useBios");
1559 useBios->connect([this](const QVariant&) {
1560 reloadConfig();
1561 }, this);
1562
1563 ConfigOption* buffers = m_config->addOption("audioBuffers");
1564 buffers->connect([this](const QVariant&) {
1565 reloadConfig();
1566 }, this);
1567
1568 ConfigOption* sampleRate = m_config->addOption("sampleRate");
1569 sampleRate->connect([this](const QVariant&) {
1570 reloadConfig();
1571 }, this);
1572
1573 ConfigOption* volume = m_config->addOption("volume");
1574 volume->connect([this](const QVariant&) {
1575 reloadConfig();
1576 }, this);
1577
1578 ConfigOption* volumeFf = m_config->addOption("fastForwardVolume");
1579 volumeFf->connect([this](const QVariant&) {
1580 reloadConfig();
1581 }, this);
1582
1583 ConfigOption* muteFf = m_config->addOption("fastForwardMute");
1584 muteFf->connect([this](const QVariant&) {
1585 reloadConfig();
1586 }, this);
1587
1588 ConfigOption* rewindEnable = m_config->addOption("rewindEnable");
1589 rewindEnable->connect([this](const QVariant&) {
1590 reloadConfig();
1591 }, this);
1592
1593 ConfigOption* rewindBufferCapacity = m_config->addOption("rewindBufferCapacity");
1594 rewindBufferCapacity->connect([this](const QVariant&) {
1595 reloadConfig();
1596 }, this);
1597
1598 ConfigOption* allowOpposingDirections = m_config->addOption("allowOpposingDirections");
1599 allowOpposingDirections->connect([this](const QVariant&) {
1600 reloadConfig();
1601 }, this);
1602
1603 ConfigOption* saveStateExtdata = m_config->addOption("saveStateExtdata");
1604 saveStateExtdata->connect([this](const QVariant&) {
1605 reloadConfig();
1606 }, this);
1607
1608 ConfigOption* loadStateExtdata = m_config->addOption("loadStateExtdata");
1609 loadStateExtdata->connect([this](const QVariant&) {
1610 reloadConfig();
1611 }, this);
1612
1613 ConfigOption* preload = m_config->addOption("preload");
1614 preload->connect([this](const QVariant& value) {
1615 m_manager->setPreload(value.toBool());
1616 }, this);
1617 m_config->updateOption("preload");
1618
1619 ConfigOption* showFps = m_config->addOption("showFps");
1620 showFps->connect([this](const QVariant& value) {
1621 if (!value.toInt()) {
1622 m_fpsTimer.stop();
1623 updateTitle();
1624 } else if (m_controller) {
1625 m_fpsTimer.start();
1626 m_frameTimer.start();
1627 }
1628 }, this);
1629
1630 ConfigOption* showOSD = m_config->addOption("showOSD");
1631 showOSD->connect([this](const QVariant& value) {
1632 if (m_display) {
1633 m_display->showOSDMessages(value.toBool());
1634 }
1635 }, this);
1636
1637 ConfigOption* videoScale = m_config->addOption("videoScale");
1638 videoScale->connect([this](const QVariant& value) {
1639 if (m_display) {
1640 m_display->setVideoScale(value.toInt());
1641 }
1642 }, this);
1643
1644 m_actions.addHiddenAction(tr("Exit fullscreen"), "exitFullScreen", this, &Window::exitFullScreen, "frame", QKeySequence("Esc"));
1645
1646 m_actions.addHeldAction(tr("GameShark Button (held)"), "holdGSButton", [this](bool held) {
1647 if (m_controller) {
1648 mCheatPressButton(m_controller->cheatDevice(), held);
1649 }
1650 }, "tools", QKeySequence(Qt::Key_Apostrophe));
1651
1652 m_actions.addHiddenMenu(tr("Autofire"), "autofire");
1653 m_actions.addHeldAction(tr("Autofire A"), "autofireA", [this](bool held) {
1654 if (m_controller) {
1655 m_controller->setAutofire(GBA_KEY_A, held);
1656 }
1657 }, "autofire");
1658 m_actions.addHeldAction(tr("Autofire B"), "autofireB", [this](bool held) {
1659 if (m_controller) {
1660 m_controller->setAutofire(GBA_KEY_B, held);
1661 }
1662 }, "autofire");
1663 m_actions.addHeldAction(tr("Autofire L"), "autofireL", [this](bool held) {
1664 if (m_controller) {
1665 m_controller->setAutofire(GBA_KEY_L, held);
1666 }
1667 }, "autofire");
1668 m_actions.addHeldAction(tr("Autofire R"), "autofireR", [this](bool held) {
1669 if (m_controller) {
1670 m_controller->setAutofire(GBA_KEY_R, held);
1671 }
1672 }, "autofire");
1673 m_actions.addHeldAction(tr("Autofire Start"), "autofireStart", [this](bool held) {
1674 if (m_controller) {
1675 m_controller->setAutofire(GBA_KEY_START, held);
1676 }
1677 }, "autofire");
1678 m_actions.addHeldAction(tr("Autofire Select"), "autofireSelect", [this](bool held) {
1679 if (m_controller) {
1680 m_controller->setAutofire(GBA_KEY_SELECT, held);
1681 }
1682 }, "autofire");
1683 m_actions.addHeldAction(tr("Autofire Up"), "autofireUp", [this](bool held) {
1684 if (m_controller) {
1685 m_controller->setAutofire(GBA_KEY_UP, held);
1686 }
1687 }, "autofire");
1688 m_actions.addHeldAction(tr("Autofire Right"), "autofireRight", [this](bool held) {
1689 if (m_controller) {
1690 m_controller->setAutofire(GBA_KEY_RIGHT, held);
1691 }
1692 }, "autofire");
1693 m_actions.addHeldAction(tr("Autofire Down"), "autofireDown", [this](bool held) {
1694 if (m_controller) {
1695 m_controller->setAutofire(GBA_KEY_DOWN, held);
1696 }
1697 }, "autofire");
1698 m_actions.addHeldAction(tr("Autofire Left"), "autofireLeft", [this](bool held) {
1699 if (m_controller) {
1700 m_controller->setAutofire(GBA_KEY_LEFT, held);
1701 }
1702 }, "autofire");
1703
1704 for (Action* action : m_gameActions) {
1705 action->setEnabled(false);
1706 }
1707
1708 m_shortcutController->rebuildItems();
1709 m_actions.rebuildMenu(menuBar(), this, *m_shortcutController);
1710}
1711
1712void Window::attachWidget(QWidget* widget) {
1713 m_screenWidget->layout()->addWidget(widget);
1714 m_screenWidget->unsetCursor();
1715 static_cast<QStackedLayout*>(m_screenWidget->layout())->setCurrentWidget(widget);
1716}
1717
1718void Window::detachWidget(QWidget* widget) {
1719 m_screenWidget->layout()->removeWidget(widget);
1720}
1721
1722void Window::appendMRU(const QString& fname) {
1723 int index = m_mruFiles.indexOf(fname);
1724 if (index >= 0) {
1725 m_mruFiles.removeAt(index);
1726 }
1727 m_mruFiles.prepend(fname);
1728 while (m_mruFiles.size() > ConfigController::MRU_LIST_SIZE) {
1729 m_mruFiles.removeLast();
1730 }
1731 updateMRU();
1732}
1733
1734void Window::clearMRU() {
1735 m_mruFiles.clear();
1736 updateMRU();
1737}
1738
1739void Window::updateMRU() {
1740 m_actions.clearMenu("mru");
1741 int i = 0;
1742 for (const QString& file : m_mruFiles) {
1743 QString displayName(QDir::toNativeSeparators(file).replace("&", "&&"));
1744 m_actions.addAction(displayName, QString("mru.%1").arg(QString::number(i)), [this, file]() {
1745 setController(m_manager->loadGame(file), file);
1746 }, "mru", QString("Ctrl+%1").arg(i));
1747 ++i;
1748 }
1749 m_config->setMRU(m_mruFiles);
1750 m_config->write();
1751 m_actions.addSeparator("mru");
1752 m_actions.addAction(tr("Clear"), "resetMru", this, &Window::clearMRU, "mru");
1753
1754 m_actions.rebuildMenu(menuBar(), this, *m_shortcutController);
1755}
1756
1757Action* Window::addGameAction(const QString& visibleName, const QString& name, Action::Function function, const QString& menu, const QKeySequence& shortcut) {
1758 Action* action = m_actions.addAction(visibleName, name, [this, function]() {
1759 if (m_controller) {
1760 function();
1761 }
1762 }, menu, shortcut);
1763 m_gameActions.append(action);
1764 return action;
1765}
1766
1767template<typename T, typename V>
1768Action* Window::addGameAction(const QString& visibleName, const QString& name, T* obj, V (T::*method)(), const QString& menu, const QKeySequence& shortcut) {
1769 return addGameAction(visibleName, name, [this, obj, method]() {
1770 (obj->*method)();
1771 }, menu, shortcut);
1772}
1773
1774template<typename V>
1775Action* Window::addGameAction(const QString& visibleName, const QString& name, V (CoreController::*method)(), const QString& menu, const QKeySequence& shortcut) {
1776 return addGameAction(visibleName, name, [this, method]() {
1777 (m_controller.get()->*method)();
1778 }, menu, shortcut);
1779}
1780
1781Action* Window::addGameAction(const QString& visibleName, const QString& name, Action::BooleanFunction function, const QString& menu, const QKeySequence& shortcut) {
1782 Action* action = m_actions.addBooleanAction(visibleName, name, [this, function](bool value) {
1783 if (m_controller) {
1784 function(value);
1785 }
1786 }, menu, shortcut);
1787 m_gameActions.append(action);
1788 return action;
1789}
1790
1791void Window::focusCheck() {
1792 if (!m_config->getOption("pauseOnFocusLost").toInt() || !m_controller) {
1793 return;
1794 }
1795 if (QGuiApplication::focusWindow() && m_autoresume) {
1796 m_controller->setPaused(false);
1797 m_autoresume = false;
1798 } else if (!QGuiApplication::focusWindow() && !m_controller->isPaused()) {
1799 m_autoresume = true;
1800 m_controller->setPaused(true);
1801 }
1802}
1803
1804void Window::updateFrame() {
1805 QPixmap pixmap;
1806 pixmap.convertFromImage(m_controller->getPixels());
1807 m_screenWidget->setPixmap(pixmap);
1808 emit paused(true);
1809}
1810
1811void Window::setController(CoreController* controller, const QString& fname) {
1812 if (!controller) {
1813 return;
1814 }
1815 if (m_pendingClose) {
1816 return;
1817 }
1818
1819 if (m_controller) {
1820 m_controller->stop();
1821 QTimer::singleShot(0, this, [this, controller, fname]() {
1822 setController(controller, fname);
1823 });
1824 return;
1825 }
1826 if (!fname.isEmpty()) {
1827 setWindowFilePath(fname);
1828 appendMRU(fname);
1829 }
1830
1831 if (!m_display) {
1832 reloadDisplayDriver();
1833 }
1834
1835 m_controller = std::shared_ptr<CoreController>(controller);
1836 m_inputController.recalibrateAxes();
1837 m_controller->setInputController(&m_inputController);
1838 m_controller->setLogger(&m_log);
1839 m_display->startDrawing(m_controller);
1840
1841 connect(this, &Window::shutdown, [this]() {
1842 if (!m_controller) {
1843 return;
1844 }
1845 m_controller->stop();
1846 disconnect(m_controller.get(), &CoreController::started, this, &Window::gameStarted);
1847 });
1848
1849 connect(m_controller.get(), &CoreController::started, this, &Window::gameStarted);
1850 connect(m_controller.get(), &CoreController::started, &m_inputController, &InputController::suspendScreensaver);
1851 connect(m_controller.get(), &CoreController::stopping, this, &Window::gameStopped);
1852 {
1853 connect(m_controller.get(), &CoreController::stopping, [this]() {
1854 m_controller.reset();
1855 });
1856 }
1857 connect(m_controller.get(), &CoreController::stopping, &m_inputController, &InputController::resumeScreensaver);
1858 connect(m_controller.get(), &CoreController::paused, this, &Window::updateFrame);
1859
1860#ifndef Q_OS_MAC
1861 connect(m_controller.get(), &CoreController::paused, menuBar(), &QWidget::show);
1862 connect(m_controller.get(), &CoreController::unpaused, [this]() {
1863 if(isFullScreen()) {
1864 menuBar()->hide();
1865 }
1866 });
1867#endif
1868
1869 connect(m_controller.get(), &CoreController::paused, &m_inputController, &InputController::resumeScreensaver);
1870 connect(m_controller.get(), &CoreController::unpaused, [this]() {
1871 emit paused(false);
1872 });
1873
1874 attachDisplay();
1875
1876 connect(m_controller.get(), &CoreController::unpaused, &m_inputController, &InputController::suspendScreensaver);
1877 connect(m_controller.get(), &CoreController::frameAvailable, this, &Window::recordFrame);
1878 connect(m_controller.get(), &CoreController::crashed, this, &Window::gameCrashed);
1879 connect(m_controller.get(), &CoreController::failed, this, &Window::gameFailed);
1880 connect(m_controller.get(), &CoreController::unimplementedBiosCall, this, &Window::unimplementedBiosCall);
1881
1882#ifdef USE_GDB_STUB
1883 if (m_gdbController) {
1884 m_gdbController->setController(m_controller);
1885 }
1886#endif
1887
1888#ifdef USE_DEBUGGERS
1889 if (m_console) {
1890 m_console->setController(m_controller);
1891 }
1892#endif
1893
1894#ifdef USE_FFMPEG
1895 if (m_gifView) {
1896 m_gifView->setController(m_controller);
1897 }
1898
1899 if (m_videoView) {
1900 m_videoView->setController(m_controller);
1901 }
1902#endif
1903
1904 if (m_sensorView) {
1905 m_sensorView->setController(m_controller);
1906 }
1907
1908 if (m_overrideView) {
1909 m_overrideView->setController(m_controller);
1910 }
1911
1912 if (!m_pendingPatch.isEmpty()) {
1913 m_controller->loadPatch(m_pendingPatch);
1914 m_pendingPatch = QString();
1915 }
1916
1917 m_controller->loadConfig(m_config);
1918 m_controller->start();
1919
1920 if (!m_pendingState.isEmpty()) {
1921 m_controller->loadState(m_pendingState);
1922 m_pendingState = QString();
1923 }
1924
1925 if (m_pendingPause) {
1926 m_controller->setPaused(true);
1927 m_pendingPause = false;
1928 }
1929}
1930
1931void Window::attachDisplay() {
1932 connect(m_controller.get(), &CoreController::stateLoaded, m_display.get(), &Display::resizeContext);
1933 connect(m_controller.get(), &CoreController::stateLoaded, m_display.get(), &Display::forceDraw);
1934 connect(m_controller.get(), &CoreController::rewound, m_display.get(), &Display::forceDraw);
1935 connect(m_controller.get(), &CoreController::paused, m_display.get(), &Display::pauseDrawing);
1936 connect(m_controller.get(), &CoreController::unpaused, m_display.get(), &Display::unpauseDrawing);
1937 connect(m_controller.get(), &CoreController::frameAvailable, m_display.get(), &Display::framePosted);
1938 connect(m_controller.get(), &CoreController::statusPosted, m_display.get(), &Display::showMessage);
1939 connect(m_controller.get(), &CoreController::didReset, m_display.get(), &Display::resizeContext);
1940 changeRenderer();
1941}
1942
1943WindowBackground::WindowBackground(QWidget* parent)
1944 : QWidget(parent)
1945{
1946 setLayout(new QStackedLayout());
1947 layout()->setContentsMargins(0, 0, 0, 0);
1948}
1949
1950void WindowBackground::setPixmap(const QPixmap& pmap) {
1951 m_pixmap = pmap;
1952 update();
1953}
1954
1955void WindowBackground::setSizeHint(const QSize& hint) {
1956 m_sizeHint = hint;
1957}
1958
1959QSize WindowBackground::sizeHint() const {
1960 return m_sizeHint;
1961}
1962
1963void WindowBackground::setDimensions(int width, int height) {
1964 m_aspectWidth = width;
1965 m_aspectHeight = height;
1966}
1967
1968void WindowBackground::setLockIntegerScaling(bool lock) {
1969 m_lockIntegerScaling = lock;
1970}
1971
1972void WindowBackground::setLockAspectRatio(bool lock) {
1973 m_lockAspectRatio = lock;
1974}
1975
1976void WindowBackground::filter(bool filter) {
1977 m_filter = filter;
1978}
1979
1980void WindowBackground::paintEvent(QPaintEvent* event) {
1981 QWidget::paintEvent(event);
1982 const QPixmap& logo = pixmap();
1983 QPainter painter(this);
1984 painter.setRenderHint(QPainter::SmoothPixmapTransform, m_filter);
1985 painter.fillRect(QRect(QPoint(), size()), Qt::black);
1986 QSize s = size();
1987 QSize ds = s;
1988 if (m_lockAspectRatio) {
1989 if (ds.width() * m_aspectHeight > ds.height() * m_aspectWidth) {
1990 ds.setWidth(ds.height() * m_aspectWidth / m_aspectHeight);
1991 } else if (ds.width() * m_aspectHeight < ds.height() * m_aspectWidth) {
1992 ds.setHeight(ds.width() * m_aspectHeight / m_aspectWidth);
1993 }
1994 }
1995 if (m_lockIntegerScaling) {
1996 if (ds.width() >= m_aspectWidth) {
1997 ds.setWidth(ds.width() - ds.width() % m_aspectWidth);
1998 }
1999 if (ds.height() >= m_aspectHeight) {
2000 ds.setHeight(ds.height() - ds.height() % m_aspectHeight);
2001 }
2002 }
2003 QPoint origin = QPoint((s.width() - ds.width()) / 2, (s.height() - ds.height()) / 2);
2004 QRect full(origin, ds);
2005 painter.drawPixmap(full, logo);
2006}