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