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