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