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