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