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