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