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