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*) {
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) {
944 // TODO: Mention which call?
945 if (m_hitUnimplementedBiosCall) {
946 return;
947 }
948 m_hitUnimplementedBiosCall = true;
949
950 QMessageBox* fail = new QMessageBox(
951 QMessageBox::Warning, tr("Unimplemented BIOS call"),
952 tr("This game uses a BIOS call that is not implemented. Please use the official BIOS for best experience."),
953 QMessageBox::Ok, this, Qt::Sheet);
954 fail->setAttribute(Qt::WA_DeleteOnClose);
955 fail->show();
956}
957
958void Window::reloadDisplayDriver() {
959 if (m_controller) {
960 m_display->stopDrawing();
961 detachWidget(m_display.get());
962 }
963 m_display = std::move(std::unique_ptr<Display>(Display::create(this)));
964#if defined(BUILD_GL) || defined(BUILD_GLES2)
965 m_shaderView.reset();
966 m_shaderView = std::make_unique<ShaderSelector>(m_display.get(), m_config);
967#endif
968
969 connect(m_display.get(), &Display::hideCursor, [this]() {
970 if (static_cast<QStackedLayout*>(m_screenWidget->layout())->currentWidget() == m_display.get()) {
971 m_screenWidget->setCursor(Qt::BlankCursor);
972 }
973 });
974 connect(m_display.get(), &Display::showCursor, [this]() {
975 m_screenWidget->unsetCursor();
976 });
977
978 const mCoreOptions* opts = m_config->options();
979 m_display->lockAspectRatio(opts->lockAspectRatio);
980 m_display->lockIntegerScaling(opts->lockIntegerScaling);
981 m_display->interframeBlending(opts->interframeBlending);
982 m_display->filter(opts->resampleVideo);
983 m_screenWidget->filter(opts->resampleVideo);
984 m_config->updateOption("showOSD");
985#if defined(BUILD_GL) || defined(BUILD_GLES2)
986 if (opts->shader) {
987 struct VDir* shader = VDirOpen(opts->shader);
988 if (shader && m_display->supportsShaders()) {
989 m_display->setShaders(shader);
990 m_shaderView->refreshShaders();
991 shader->close(shader);
992 }
993 }
994#endif
995
996 if (m_controller) {
997 attachDisplay();
998
999 attachWidget(m_display.get());
1000 m_display->startDrawing(m_controller);
1001 }
1002#ifdef M_CORE_GB
1003 m_display->setMinimumSize(GB_VIDEO_HORIZONTAL_PIXELS, GB_VIDEO_VERTICAL_PIXELS);
1004#elif defined(M_CORE_GBA)
1005 m_display->setMinimumSize(GBA_VIDEO_HORIZONTAL_PIXELS, GBA_VIDEO_VERTICAL_PIXELS);
1006#endif
1007}
1008
1009void Window::reloadAudioDriver() {
1010 if (!m_controller) {
1011 return;
1012 }
1013 if (m_audioProcessor) {
1014 m_audioProcessor->stop();
1015 m_audioProcessor.reset();
1016 }
1017
1018 const mCoreOptions* opts = m_config->options();
1019 m_audioProcessor = std::move(std::unique_ptr<AudioProcessor>(AudioProcessor::create()));
1020 m_audioProcessor->setInput(m_controller);
1021 m_audioProcessor->setBufferSamples(opts->audioBuffers);
1022 m_audioProcessor->requestSampleRate(opts->sampleRate);
1023 m_audioProcessor->start();
1024 connect(m_controller.get(), &CoreController::stopping, m_audioProcessor.get(), &AudioProcessor::stop);
1025 connect(m_controller.get(), &CoreController::fastForwardChanged, m_audioProcessor.get(), &AudioProcessor::inputParametersChanged);
1026 connect(m_controller.get(), &CoreController::paused, m_audioProcessor.get(), &AudioProcessor::pause);
1027 connect(m_controller.get(), &CoreController::unpaused, m_audioProcessor.get(), &AudioProcessor::start);
1028}
1029
1030void Window::changeRenderer() {
1031 if (!m_controller) {
1032 return;
1033 }
1034 if (m_config->getOption("hwaccelVideo").toInt() && m_display->supportsShaders() && m_controller->supportsFeature(CoreController::Feature::OPENGL)) {
1035 std::shared_ptr<VideoProxy> proxy = m_display->videoProxy();
1036 if (!proxy) {
1037 proxy = std::make_shared<VideoProxy>();
1038 }
1039 m_display->setVideoProxy(proxy);
1040 proxy->attach(m_controller.get());
1041
1042 int fb = m_display->framebufferHandle();
1043 if (fb >= 0) {
1044 m_controller->setFramebufferHandle(fb);
1045 }
1046 } else {
1047 m_controller->setFramebufferHandle(-1);
1048 }
1049}
1050
1051void Window::tryMakePortable() {
1052 QMessageBox* confirm = new QMessageBox(QMessageBox::Question, tr("Really make portable?"),
1053 tr("This will make the emulator load its configuration from the same directory as the executable. Do you want to continue?"),
1054 QMessageBox::Yes | QMessageBox::Cancel, this, Qt::Sheet);
1055 confirm->setAttribute(Qt::WA_DeleteOnClose);
1056 connect(confirm->button(QMessageBox::Yes), &QAbstractButton::clicked, m_config, &ConfigController::makePortable);
1057 confirm->show();
1058}
1059
1060void Window::mustRestart() {
1061 if (m_mustRestart.isActive()) {
1062 return;
1063 }
1064 m_mustRestart.start();
1065 QMessageBox* dialog = new QMessageBox(QMessageBox::Warning, tr("Restart needed"),
1066 tr("Some changes will not take effect until the emulator is restarted."),
1067 QMessageBox::Ok, this, Qt::Sheet);
1068 dialog->setAttribute(Qt::WA_DeleteOnClose);
1069 dialog->show();
1070}
1071
1072void Window::recordFrame() {
1073 m_frameList.append(m_frameTimer.nsecsElapsed());
1074 m_frameTimer.restart();
1075}
1076
1077void Window::showFPS() {
1078 if (m_frameList.isEmpty()) {
1079 updateTitle();
1080 return;
1081 }
1082 qint64 total = 0;
1083 for (qint64 t : m_frameList) {
1084 total += t;
1085 }
1086 double fps = (m_frameList.size() * 1e10) / total;
1087 m_frameList.clear();
1088 fps = round(fps) / 10.f;
1089 updateTitle(fps);
1090}
1091
1092void Window::updateTitle(float fps) {
1093 QString title;
1094
1095 if (m_controller) {
1096 CoreController::Interrupter interrupter(m_controller);
1097 const NoIntroDB* db = GBAApp::app()->gameDB();
1098 NoIntroGame game{};
1099 uint32_t crc32 = 0;
1100 mCore* core = m_controller->thread()->core;
1101 core->checksum(m_controller->thread()->core, &crc32, CHECKSUM_CRC32);
1102 QString filePath = windowFilePath();
1103
1104 if (m_config->getOption("showFilename").toInt() && !filePath.isNull()) {
1105 QFileInfo fileInfo(filePath);
1106 title = fileInfo.fileName();
1107 } else {
1108 char gameTitle[17] = { '\0' };
1109 core->getGameTitle(core, gameTitle);
1110 title = gameTitle;
1111
1112#ifdef USE_SQLITE3
1113 if (db && crc32 && NoIntroDBLookupGameByCRC(db, crc32, &game)) {
1114 title = QLatin1String(game.name);
1115 }
1116#endif
1117 }
1118
1119 MultiplayerController* multiplayer = m_controller->multiplayerController();
1120 if (multiplayer && multiplayer->attached() > 1) {
1121 title += tr(" - Player %1 of %2").arg(multiplayer->playerId(m_controller.get()) + 1).arg(multiplayer->attached());
1122 for (Action* action : m_nonMpActions) {
1123 action->setEnabled(false);
1124 }
1125 } else {
1126 for (Action* action : m_nonMpActions) {
1127 action->setEnabled(true);
1128 }
1129 }
1130 }
1131 if (title.isNull()) {
1132 setWindowTitle(tr("%1 - %2").arg(projectName).arg(projectVersion));
1133 } else if (fps < 0) {
1134 setWindowTitle(tr("%1 - %2 - %3").arg(projectName).arg(title).arg(projectVersion));
1135 } else {
1136 setWindowTitle(tr("%1 - %2 (%3 fps) - %4").arg(projectName).arg(title).arg(fps).arg(projectVersion));
1137 }
1138}
1139
1140void Window::openStateWindow(LoadSave ls) {
1141 if (m_stateWindow) {
1142 return;
1143 }
1144 MultiplayerController* multiplayer = m_controller->multiplayerController();
1145 if (multiplayer && multiplayer->attached() > 1) {
1146 return;
1147 }
1148 bool wasPaused = m_controller->isPaused();
1149 m_stateWindow = new LoadSaveState(m_controller);
1150 connect(this, &Window::shutdown, m_stateWindow, &QWidget::close);
1151 connect(m_stateWindow, &LoadSaveState::closed, [this]() {
1152 detachWidget(m_stateWindow);
1153 m_stateWindow = nullptr;
1154 QMetaObject::invokeMethod(this, "setFocus", Qt::QueuedConnection);
1155 });
1156 if (!wasPaused) {
1157 m_controller->setPaused(true);
1158 connect(m_stateWindow, &LoadSaveState::closed, [this]() {
1159 if (m_controller) {
1160 m_controller->setPaused(false);
1161 }
1162 });
1163 }
1164 m_stateWindow->setAttribute(Qt::WA_DeleteOnClose);
1165 m_stateWindow->setMode(ls);
1166 updateFrame();
1167#ifndef Q_OS_MAC
1168 menuBar()->show();
1169#endif
1170 attachWidget(m_stateWindow);
1171}
1172
1173void Window::setupMenu(QMenuBar* menubar) {
1174 installEventFilter(m_shortcutController);
1175
1176 menubar->clear();
1177 m_actions.addMenu(tr("&File"), "file");
1178
1179 m_actions.addAction(tr("Load &ROM..."), "loadROM", this, &Window::selectROM, "file", QKeySequence::Open);
1180
1181#ifdef USE_SQLITE3
1182 m_actions.addAction(tr("Load ROM in archive..."), "loadROMInArchive", this, &Window::selectROMInArchive, "file");
1183 m_actions.addAction(tr("Add folder to library..."), "addDirToLibrary", this, &Window::addDirToLibrary, "file");
1184#endif
1185
1186 addGameAction(tr("Load alternate save..."), "loadAlternateSave", [this]() {
1187 this->selectSave(false);
1188 }, "file");
1189 addGameAction(tr("Load temporary save..."), "loadTemporarySave", [this]() {
1190 this->selectSave(true);
1191 }, "file");
1192
1193 m_actions.addAction(tr("Load &patch..."), "loadPatch", this, &Window::selectPatch, "file");
1194
1195#ifdef M_CORE_GBA
1196 m_actions.addAction(tr("Boot BIOS"), "bootBIOS", [this]() {
1197 setController(m_manager->loadBIOS(PLATFORM_GBA, m_config->getOption("gba.bios")), QString());
1198 }, "file");
1199#endif
1200
1201 addGameAction(tr("Replace ROM..."), "replaceROM", this, &Window::replaceROM, "file");
1202#ifdef M_CORE_GBA
1203 Action* scanCard = addGameAction(tr("Scan e-Reader dotcodes..."), "scanCard", this, &Window::scanCard, "file");
1204 m_platformActions.insert(PLATFORM_GBA, scanCard);
1205#endif
1206
1207 addGameAction(tr("ROM &info..."), "romInfo", openControllerTView<ROMInfo>(), "file");
1208
1209 m_actions.addMenu(tr("Recent"), "mru", "file");
1210 m_actions.addSeparator("file");
1211
1212 m_actions.addAction(tr("Make portable"), "makePortable", this, &Window::tryMakePortable, "file");
1213 m_actions.addSeparator("file");
1214
1215 Action* loadState = addGameAction(tr("&Load state"), "loadState", [this]() {
1216 this->openStateWindow(LoadSave::LOAD);
1217 }, "file", QKeySequence("F10"));
1218 m_nonMpActions.append(loadState);
1219 m_platformActions.insert(PLATFORM_GBA, loadState);
1220 m_platformActions.insert(PLATFORM_GB, loadState);
1221
1222 Action* loadStateFile = addGameAction(tr("Load state file..."), "loadStateFile", [this]() {
1223 this->selectState(true);
1224 }, "file");
1225 m_nonMpActions.append(loadStateFile);
1226 m_platformActions.insert(PLATFORM_GBA, loadStateFile);
1227 m_platformActions.insert(PLATFORM_GB, loadStateFile);
1228
1229 Action* saveState = addGameAction(tr("&Save state"), "saveState", [this]() {
1230 this->openStateWindow(LoadSave::SAVE);
1231 }, "file", QKeySequence("Shift+F10"));
1232 m_nonMpActions.append(saveState);
1233 m_platformActions.insert(PLATFORM_GBA, saveState);
1234 m_platformActions.insert(PLATFORM_GB, saveState);
1235
1236 Action* saveStateFile = addGameAction(tr("Save state file..."), "saveStateFile", [this]() {
1237 this->selectState(false);
1238 }, "file");
1239 m_nonMpActions.append(saveStateFile);
1240 m_platformActions.insert(PLATFORM_GBA, saveStateFile);
1241 m_platformActions.insert(PLATFORM_GB, saveStateFile);
1242
1243 m_actions.addMenu(tr("Quick load"), "quickLoad", "file");
1244 m_actions.addMenu(tr("Quick save"), "quickSave", "file");
1245
1246 Action* quickLoad = addGameAction(tr("Load recent"), "quickLoad", [this] {
1247 m_controller->loadState();
1248 }, "quickLoad");
1249 m_nonMpActions.append(quickLoad);
1250 m_platformActions.insert(PLATFORM_GBA, quickLoad);
1251 m_platformActions.insert(PLATFORM_GB, quickLoad);
1252
1253 Action* quickSave = addGameAction(tr("Save recent"), "quickSave", [this] {
1254 m_controller->saveState();
1255 }, "quickSave");
1256 m_nonMpActions.append(quickSave);
1257 m_platformActions.insert(PLATFORM_GBA, quickSave);
1258 m_platformActions.insert(PLATFORM_GB, quickSave);
1259
1260 m_actions.addSeparator("quickLoad");
1261 m_actions.addSeparator("quickSave");
1262
1263 Action* undoLoadState = addGameAction(tr("Undo load state"), "undoLoadState", &CoreController::loadBackupState, "quickLoad", QKeySequence("F11"));
1264 m_nonMpActions.append(undoLoadState);
1265 m_platformActions.insert(PLATFORM_GBA, undoLoadState);
1266 m_platformActions.insert(PLATFORM_GB, undoLoadState);
1267
1268 Action* undoSaveState = addGameAction(tr("Undo save state"), "undoSaveState", &CoreController::saveBackupState, "quickSave", QKeySequence("Shift+F11"));
1269 m_nonMpActions.append(undoSaveState);
1270 m_platformActions.insert(PLATFORM_GBA, undoSaveState);
1271 m_platformActions.insert(PLATFORM_GB, undoSaveState);
1272
1273 m_actions.addSeparator("quickLoad");
1274 m_actions.addSeparator("quickSave");
1275
1276 for (int i = 1; i < 10; ++i) {
1277 Action* quickLoad = addGameAction(tr("State &%1").arg(i), QString("quickLoad.%1").arg(i), [this, i]() {
1278 m_controller->loadState(i);
1279 }, "quickLoad", QString("F%1").arg(i));
1280 m_nonMpActions.append(quickLoad);
1281 m_platformActions.insert(PLATFORM_GBA, quickLoad);
1282 m_platformActions.insert(PLATFORM_GB, quickLoad);
1283
1284 Action* quickSave = addGameAction(tr("State &%1").arg(i), QString("quickSave.%1").arg(i), [this, i]() {
1285 m_controller->saveState(i);
1286 }, "quickSave", QString("Shift+F%1").arg(i));
1287 m_nonMpActions.append(quickSave);
1288 m_platformActions.insert(PLATFORM_GBA, quickSave);
1289 m_platformActions.insert(PLATFORM_GB, quickSave);
1290 }
1291
1292 m_actions.addSeparator("file");
1293 m_actions.addAction(tr("Load camera image..."), "loadCamImage", this, &Window::loadCamImage, "file");
1294
1295#ifdef M_CORE_GBA
1296 m_actions.addSeparator("file");
1297 Action* importShark = addGameAction(tr("Import GameShark Save..."), "importShark", this, &Window::importSharkport, "file");
1298 m_platformActions.insert(PLATFORM_GBA, importShark);
1299
1300 Action* exportShark = addGameAction(tr("Export GameShark Save..."), "exportShark", this, &Window::exportSharkport, "file");
1301 m_platformActions.insert(PLATFORM_GBA, exportShark);
1302#endif
1303
1304 m_actions.addSeparator("file");
1305 m_multiWindow = m_actions.addAction(tr("New multiplayer window"), "multiWindow", [this]() {
1306 GBAApp::app()->newWindow();
1307 }, "file");
1308
1309#ifndef Q_OS_MAC
1310 m_actions.addSeparator("file");
1311#endif
1312
1313 m_actions.addAction(tr("About..."), "about", openTView<AboutScreen>(), "file");
1314
1315#ifndef Q_OS_MAC
1316 m_actions.addAction(tr("E&xit"), "quit", static_cast<QWidget*>(this), &QWidget::close, "file", QKeySequence::Quit);
1317#endif
1318
1319 m_actions.addMenu(tr("&Emulation"), "emu");
1320
1321 addGameAction(tr("&Reset"), "reset", &CoreController::reset, "emu", QKeySequence("Ctrl+R"));
1322 addGameAction(tr("Sh&utdown"), "shutdown", &CoreController::stop, "emu");
1323 Action* yank = addGameAction(tr("Yank game pak"), "yank", &CoreController::yankPak, "emu");
1324 m_platformActions.insert(PLATFORM_GBA, yank);
1325 m_platformActions.insert(PLATFORM_GB, yank);
1326
1327 m_actions.addSeparator("emu");
1328
1329 Action* pause = m_actions.addBooleanAction(tr("&Pause"), "pause", [this](bool paused) {
1330 if (m_controller) {
1331 m_controller->setPaused(paused);
1332 } else {
1333 m_pendingPause = paused;
1334 }
1335 }, "emu", QKeySequence("Ctrl+P"));
1336 connect(this, &Window::paused, pause, &Action::setActive);
1337
1338 addGameAction(tr("&Next frame"), "frameAdvance", &CoreController::frameAdvance, "emu", QKeySequence("Ctrl+N"));
1339
1340 m_actions.addSeparator("emu");
1341
1342 m_actions.addHeldAction(tr("Fast forward (held)"), "holdFastForward", [this](bool held) {
1343 if (m_controller) {
1344 m_controller->setFastForward(held);
1345 }
1346 }, "emu", QKeySequence(Qt::Key_Tab));
1347
1348 addGameAction(tr("&Fast forward"), "fastForward", [this](bool value) {
1349 m_controller->forceFastForward(value);
1350 }, "emu", QKeySequence("Shift+Tab"));
1351
1352 m_actions.addMenu(tr("Fast forward speed"), "fastForwardSpeed", "emu");
1353 ConfigOption* ffspeed = m_config->addOption("fastForwardRatio");
1354 ffspeed->connect([this](const QVariant&) {
1355 reloadConfig();
1356 }, this);
1357 ffspeed->addValue(tr("Unbounded"), -1.0f, &m_actions, "fastForwardSpeed");
1358 ffspeed->setValue(QVariant(-1.0f));
1359 m_actions.addSeparator("fastForwardSpeed");
1360 for (int i = 2; i < 11; ++i) {
1361 ffspeed->addValue(tr("%0x").arg(i), i, &m_actions, "fastForwardSpeed");
1362 }
1363 m_config->updateOption("fastForwardRatio");
1364
1365 Action* rewindHeld = m_actions.addHeldAction(tr("Rewind (held)"), "holdRewind", [this](bool held) {
1366 if (m_controller) {
1367 m_controller->setRewinding(held);
1368 }
1369 }, "emu", QKeySequence("`"));
1370 m_nonMpActions.append(rewindHeld);
1371
1372 Action* rewind = addGameAction(tr("Re&wind"), "rewind", [this]() {
1373 m_controller->rewind();
1374 }, "emu", QKeySequence("~"));
1375 m_nonMpActions.append(rewind);
1376 m_platformActions.insert(PLATFORM_GBA, rewind);
1377 m_platformActions.insert(PLATFORM_GB, rewind);
1378
1379 Action* frameRewind = addGameAction(tr("Step backwards"), "frameRewind", [this] () {
1380 m_controller->rewind(1);
1381 }, "emu", QKeySequence("Ctrl+B"));
1382 m_nonMpActions.append(frameRewind);
1383 m_platformActions.insert(PLATFORM_GBA, frameRewind);
1384 m_platformActions.insert(PLATFORM_GB, frameRewind);
1385
1386 ConfigOption* videoSync = m_config->addOption("videoSync");
1387 videoSync->addBoolean(tr("Sync to &video"), &m_actions, "emu");
1388 videoSync->connect([this](const QVariant&) {
1389 reloadConfig();
1390 }, this);
1391 m_config->updateOption("videoSync");
1392
1393 ConfigOption* audioSync = m_config->addOption("audioSync");
1394 audioSync->addBoolean(tr("Sync to &audio"), &m_actions, "emu");
1395 audioSync->connect([this](const QVariant&) {
1396 reloadConfig();
1397 }, this);
1398 m_config->updateOption("audioSync");
1399
1400 m_actions.addSeparator("emu");
1401
1402 m_actions.addMenu(tr("Solar sensor"), "solar", "emu");
1403 m_actions.addAction(tr("Increase solar level"), "increaseLuminanceLevel", &m_inputController, &InputController::increaseLuminanceLevel, "solar");
1404 m_actions.addAction(tr("Decrease solar level"), "decreaseLuminanceLevel", &m_inputController, &InputController::decreaseLuminanceLevel, "solar");
1405 m_actions.addAction(tr("Brightest solar level"), "maxLuminanceLevel", [this]() {
1406 m_inputController.setLuminanceLevel(10);
1407 }, "solar");
1408 m_actions.addAction(tr("Darkest solar level"), "minLuminanceLevel", [this]() {
1409 m_inputController.setLuminanceLevel(0);
1410 }, "solar");
1411
1412 m_actions.addSeparator("solar");
1413 for (int i = 0; i <= 10; ++i) {
1414 m_actions.addAction(tr("Brightness %1").arg(QString::number(i)), QString("luminanceLevel.%1").arg(QString::number(i)), [this, i]() {
1415 m_inputController.setLuminanceLevel(i);
1416 }, "solar");
1417 }
1418
1419#ifdef M_CORE_GB
1420 Action* gbPrint = addGameAction(tr("Game Boy Printer..."), "gbPrint", [this]() {
1421 PrinterView* view = new PrinterView(m_controller);
1422 openView(view);
1423 m_controller->attachPrinter();
1424 }, "emu");
1425 m_platformActions.insert(PLATFORM_GB, gbPrint);
1426#endif
1427
1428#ifdef M_CORE_GBA
1429 Action* bcGate = addGameAction(tr("BattleChip Gate..."), "bcGate", openControllerTView<BattleChipView>(this), "emu");
1430 m_platformActions.insert(PLATFORM_GBA, bcGate);
1431#endif
1432
1433 m_actions.addMenu(tr("Audio/&Video"), "av");
1434 m_actions.addMenu(tr("Frame size"), "frame", "av");
1435 for (int i = 1; i <= 8; ++i) {
1436 Action* setSize = m_actions.addAction(tr("%1×").arg(QString::number(i)), QString("frame.%1x").arg(QString::number(i)), [this, i]() {
1437 Action* setSize = m_frameSizes[i];
1438 showNormal();
1439 QSize size(GBA_VIDEO_HORIZONTAL_PIXELS, GBA_VIDEO_VERTICAL_PIXELS);
1440 if (m_controller) {
1441 size = m_controller->screenDimensions();
1442 }
1443 size *= i;
1444 m_savedScale = i;
1445 m_config->setOption("scaleMultiplier", i); // TODO: Port to other
1446 resizeFrame(size);
1447 setSize->setActive(true);
1448 }, "frame");
1449 setSize->setExclusive(true);
1450 if (m_savedScale == i) {
1451 setSize->setActive(true);
1452 }
1453 m_frameSizes[i] = setSize;
1454 }
1455 QKeySequence fullscreenKeys;
1456#ifdef Q_OS_WIN
1457 fullscreenKeys = QKeySequence("Alt+Return");
1458#else
1459 fullscreenKeys = QKeySequence("Ctrl+F");
1460#endif
1461 m_actions.addAction(tr("Toggle fullscreen"), "fullscreen", this, &Window::toggleFullScreen, "frame", fullscreenKeys);
1462
1463 ConfigOption* lockAspectRatio = m_config->addOption("lockAspectRatio");
1464 lockAspectRatio->addBoolean(tr("Lock aspect ratio"), &m_actions, "av");
1465 lockAspectRatio->connect([this](const QVariant& value) {
1466 if (m_display) {
1467 m_display->lockAspectRatio(value.toBool());
1468 }
1469 if (m_controller) {
1470 m_screenWidget->setLockAspectRatio(value.toBool());
1471 }
1472 }, this);
1473 m_config->updateOption("lockAspectRatio");
1474
1475 ConfigOption* lockIntegerScaling = m_config->addOption("lockIntegerScaling");
1476 lockIntegerScaling->addBoolean(tr("Force integer scaling"), &m_actions, "av");
1477 lockIntegerScaling->connect([this](const QVariant& value) {
1478 if (m_display) {
1479 m_display->lockIntegerScaling(value.toBool());
1480 }
1481 if (m_controller) {
1482 m_screenWidget->setLockIntegerScaling(value.toBool());
1483 }
1484 }, this);
1485 m_config->updateOption("lockIntegerScaling");
1486
1487 ConfigOption* interframeBlending = m_config->addOption("interframeBlending");
1488 interframeBlending->addBoolean(tr("Interframe blending"), &m_actions, "av");
1489 interframeBlending->connect([this](const QVariant& value) {
1490 if (m_display) {
1491 m_display->interframeBlending(value.toBool());
1492 }
1493 }, this);
1494 m_config->updateOption("interframeBlending");
1495
1496 ConfigOption* resampleVideo = m_config->addOption("resampleVideo");
1497 resampleVideo->addBoolean(tr("Bilinear filtering"), &m_actions, "av");
1498 resampleVideo->connect([this](const QVariant& value) {
1499 if (m_display) {
1500 m_display->filter(value.toBool());
1501 }
1502 m_screenWidget->filter(value.toBool());
1503 }, this);
1504 m_config->updateOption("resampleVideo");
1505
1506 m_actions.addMenu(tr("Frame&skip"),"skip", "av");
1507 ConfigOption* skip = m_config->addOption("frameskip");
1508 skip->connect([this](const QVariant&) {
1509 reloadConfig();
1510 }, this);
1511 for (int i = 0; i <= 10; ++i) {
1512 skip->addValue(QString::number(i), i, &m_actions, "skip");
1513 }
1514 m_config->updateOption("frameskip");
1515
1516 m_actions.addSeparator("av");
1517
1518 ConfigOption* mute = m_config->addOption("mute");
1519 mute->addBoolean(tr("Mute"), &m_actions, "av");
1520 mute->connect([this](const QVariant& value) {
1521 if (value.toInt()) {
1522 m_config->setOption("fastForwardMute", true);
1523 }
1524 reloadConfig();
1525 }, this);
1526 m_config->updateOption("mute");
1527
1528 m_actions.addMenu(tr("FPS target"),"target", "av");
1529 ConfigOption* fpsTargetOption = m_config->addOption("fpsTarget");
1530 QMap<double, Action*> fpsTargets;
1531 for (int fps : {15, 30, 45, 60, 90, 120, 240}) {
1532 fpsTargets[fps] = fpsTargetOption->addValue(QString::number(fps), fps, &m_actions, "target");
1533 }
1534 m_actions.addSeparator("target");
1535 double nativeGB = double(GBA_ARM7TDMI_FREQUENCY) / double(VIDEO_TOTAL_LENGTH);
1536 fpsTargets[nativeGB] = fpsTargetOption->addValue(tr("Native (59.7275)"), nativeGB, &m_actions, "target");
1537
1538 fpsTargetOption->connect([this, fpsTargets](const QVariant& value) {
1539 reloadConfig();
1540 for (auto iter = fpsTargets.begin(); iter != fpsTargets.end(); ++iter) {
1541 bool enableSignals = iter.value()->blockSignals(true);
1542 iter.value()->setActive(abs(iter.key() - value.toDouble()) < 0.001);
1543 iter.value()->blockSignals(enableSignals);
1544 }
1545 }, this);
1546 m_config->updateOption("fpsTarget");
1547
1548 m_actions.addSeparator("av");
1549
1550#ifdef USE_PNG
1551 addGameAction(tr("Take &screenshot"), "screenshot", [this]() {
1552 m_controller->screenshot();
1553 }, "av", tr("F12"));
1554#endif
1555
1556#ifdef USE_FFMPEG
1557 addGameAction(tr("Record A/V..."), "recordOutput", this, &Window::openVideoWindow, "av");
1558 addGameAction(tr("Record GIF/WebP/APNG..."), "recordGIF", this, &Window::openGIFWindow, "av");
1559#endif
1560
1561 m_actions.addSeparator("av");
1562 m_actions.addMenu(tr("Video layers"), "videoLayers", "av");
1563 m_actions.addMenu(tr("Audio channels"), "audioChannels", "av");
1564
1565 addGameAction(tr("Adjust layer placement..."), "placementControl", openControllerTView<PlacementControl>(), "av");
1566
1567 m_actions.addMenu(tr("&Tools"), "tools");
1568 m_actions.addAction(tr("View &logs..."), "viewLogs", static_cast<QWidget*>(m_logView), &QWidget::show, "tools");
1569
1570 m_actions.addAction(tr("Game &overrides..."), "overrideWindow", [this]() {
1571 if (!m_overrideView) {
1572 m_overrideView = std::move(std::make_unique<OverrideView>(m_config));
1573 if (m_controller) {
1574 m_overrideView->setController(m_controller);
1575 }
1576 connect(this, &Window::shutdown, m_overrideView.get(), &QWidget::close);
1577 }
1578 m_overrideView->show();
1579 m_overrideView->recheck();
1580 }, "tools");
1581
1582 m_actions.addAction(tr("Game Pak sensors..."), "sensorWindow", [this]() {
1583 if (!m_sensorView) {
1584 m_sensorView = std::move(std::make_unique<SensorView>(&m_inputController));
1585 if (m_controller) {
1586 m_sensorView->setController(m_controller);
1587 }
1588 connect(this, &Window::shutdown, m_sensorView.get(), &QWidget::close);
1589 }
1590 m_sensorView->show();
1591 }, "tools");
1592
1593 addGameAction(tr("&Cheats..."), "cheatsWindow", openControllerTView<CheatsView>(), "tools");
1594
1595 m_actions.addSeparator("tools");
1596 m_actions.addAction(tr("Settings..."), "settings", this, &Window::openSettingsWindow, "tools");
1597
1598#ifdef USE_DEBUGGERS
1599 m_actions.addSeparator("tools");
1600 m_actions.addAction(tr("Open debugger console..."), "debuggerWindow", this, &Window::consoleOpen, "tools");
1601#ifdef USE_GDB_STUB
1602 Action* gdbWindow = addGameAction(tr("Start &GDB server..."), "gdbWindow", this, &Window::gdbOpen, "tools");
1603 m_platformActions.insert(PLATFORM_GBA, gdbWindow);
1604#endif
1605#endif
1606 m_actions.addSeparator("tools");
1607
1608 addGameAction(tr("View &palette..."), "paletteWindow", openControllerTView<PaletteView>(), "tools");
1609 addGameAction(tr("View &sprites..."), "spriteWindow", openControllerTView<ObjView>(), "tools");
1610 addGameAction(tr("View &tiles..."), "tileWindow", openControllerTView<TileView>(), "tools");
1611 addGameAction(tr("View &map..."), "mapWindow", openControllerTView<MapView>(), "tools");
1612
1613#ifdef M_CORE_GBA
1614 Action* frameWindow = addGameAction(tr("&Frame inspector..."), "frameWindow", [this]() {
1615 if (!m_frameView) {
1616 m_frameView = new FrameView(m_controller);
1617 connect(this, &Window::shutdown, this, [this]() {
1618 if (m_frameView) {
1619 m_frameView->close();
1620 }
1621 });
1622 connect(m_frameView, &QObject::destroyed, this, [this]() {
1623 m_frameView = nullptr;
1624 });
1625 m_frameView->setAttribute(Qt::WA_DeleteOnClose);
1626 }
1627 m_frameView->show();
1628 }, "tools");
1629 m_platformActions.insert(PLATFORM_GBA, frameWindow);
1630#endif
1631
1632 addGameAction(tr("View memory..."), "memoryView", openControllerTView<MemoryView>(), "tools");
1633 addGameAction(tr("Search memory..."), "memorySearch", openControllerTView<MemorySearch>(), "tools");
1634
1635#ifdef M_CORE_GBA
1636 Action* ioViewer = addGameAction(tr("View &I/O registers..."), "ioViewer", openControllerTView<IOViewer>(), "tools");
1637 m_platformActions.insert(PLATFORM_GBA, ioViewer);
1638#endif
1639
1640 m_actions.addSeparator("tools");
1641 addGameAction(tr("Record debug video log..."), "recordVL", this, &Window::startVideoLog, "tools");
1642 addGameAction(tr("Stop debug video log"), "stopVL", [this]() {
1643 m_controller->endVideoLog();
1644 }, "tools");
1645
1646 ConfigOption* skipBios = m_config->addOption("skipBios");
1647 skipBios->connect([this](const QVariant&) {
1648 reloadConfig();
1649 }, this);
1650
1651 ConfigOption* useBios = m_config->addOption("useBios");
1652 useBios->connect([this](const QVariant&) {
1653 reloadConfig();
1654 }, this);
1655
1656 ConfigOption* buffers = m_config->addOption("audioBuffers");
1657 buffers->connect([this](const QVariant&) {
1658 reloadConfig();
1659 }, this);
1660
1661 ConfigOption* sampleRate = m_config->addOption("sampleRate");
1662 sampleRate->connect([this](const QVariant&) {
1663 reloadConfig();
1664 }, this);
1665
1666 ConfigOption* volume = m_config->addOption("volume");
1667 volume->connect([this](const QVariant&) {
1668 reloadConfig();
1669 }, this);
1670
1671 ConfigOption* volumeFf = m_config->addOption("fastForwardVolume");
1672 volumeFf->connect([this](const QVariant&) {
1673 reloadConfig();
1674 }, this);
1675
1676 ConfigOption* muteFf = m_config->addOption("fastForwardMute");
1677 muteFf->connect([this](const QVariant&) {
1678 reloadConfig();
1679 }, this);
1680
1681 ConfigOption* rewindEnable = m_config->addOption("rewindEnable");
1682 rewindEnable->connect([this](const QVariant&) {
1683 reloadConfig();
1684 }, this);
1685
1686 ConfigOption* rewindBufferCapacity = m_config->addOption("rewindBufferCapacity");
1687 rewindBufferCapacity->connect([this](const QVariant&) {
1688 reloadConfig();
1689 }, this);
1690
1691 ConfigOption* allowOpposingDirections = m_config->addOption("allowOpposingDirections");
1692 allowOpposingDirections->connect([this](const QVariant&) {
1693 reloadConfig();
1694 }, this);
1695
1696 ConfigOption* saveStateExtdata = m_config->addOption("saveStateExtdata");
1697 saveStateExtdata->connect([this](const QVariant&) {
1698 reloadConfig();
1699 }, this);
1700
1701 ConfigOption* loadStateExtdata = m_config->addOption("loadStateExtdata");
1702 loadStateExtdata->connect([this](const QVariant&) {
1703 reloadConfig();
1704 }, this);
1705
1706 ConfigOption* preload = m_config->addOption("preload");
1707 preload->connect([this](const QVariant& value) {
1708 m_manager->setPreload(value.toBool());
1709 }, this);
1710 m_config->updateOption("preload");
1711
1712 ConfigOption* showFps = m_config->addOption("showFps");
1713 showFps->connect([this](const QVariant& value) {
1714 if (!value.toInt()) {
1715 m_fpsTimer.stop();
1716 updateTitle();
1717 } else if (m_controller) {
1718 m_fpsTimer.start();
1719 m_frameTimer.start();
1720 }
1721 }, this);
1722
1723 ConfigOption* showOSD = m_config->addOption("showOSD");
1724 showOSD->connect([this](const QVariant& value) {
1725 if (m_display) {
1726 m_display->showOSDMessages(value.toBool());
1727 }
1728 }, this);
1729
1730 ConfigOption* videoScale = m_config->addOption("videoScale");
1731 videoScale->connect([this](const QVariant& value) {
1732 if (m_display) {
1733 m_display->setVideoScale(value.toInt());
1734 }
1735 }, this);
1736
1737 m_actions.addHiddenAction(tr("Exit fullscreen"), "exitFullScreen", this, &Window::exitFullScreen, "frame", QKeySequence("Esc"));
1738
1739 m_actions.addHeldAction(tr("GameShark Button (held)"), "holdGSButton", [this](bool held) {
1740 if (m_controller) {
1741 mCheatPressButton(m_controller->cheatDevice(), held);
1742 }
1743 }, "tools", QKeySequence(Qt::Key_Apostrophe));
1744
1745 for (Action* action : m_gameActions) {
1746 action->setEnabled(false);
1747 }
1748
1749 m_shortcutController->rebuildItems();
1750 m_actions.rebuildMenu(menuBar(), this, *m_shortcutController);
1751}
1752
1753void Window::attachWidget(QWidget* widget) {
1754 m_screenWidget->layout()->addWidget(widget);
1755 m_screenWidget->unsetCursor();
1756 static_cast<QStackedLayout*>(m_screenWidget->layout())->setCurrentWidget(widget);
1757}
1758
1759void Window::detachWidget(QWidget* widget) {
1760 m_screenWidget->layout()->removeWidget(widget);
1761}
1762
1763void Window::appendMRU(const QString& fname) {
1764 int index = m_mruFiles.indexOf(fname);
1765 if (index >= 0) {
1766 m_mruFiles.removeAt(index);
1767 }
1768 m_mruFiles.prepend(fname);
1769 while (m_mruFiles.size() > ConfigController::MRU_LIST_SIZE) {
1770 m_mruFiles.removeLast();
1771 }
1772 updateMRU();
1773}
1774
1775void Window::clearMRU() {
1776 m_mruFiles.clear();
1777 updateMRU();
1778}
1779
1780void Window::updateMRU() {
1781 m_actions.clearMenu("mru");
1782 int i = 0;
1783 for (const QString& file : m_mruFiles) {
1784 QString displayName(QDir::toNativeSeparators(file).replace("&", "&&"));
1785 m_actions.addAction(displayName, QString("mru.%1").arg(QString::number(i)), [this, file]() {
1786 setController(m_manager->loadGame(file), file);
1787 }, "mru", QString("Ctrl+%1").arg(i));
1788 ++i;
1789 }
1790 m_config->setMRU(m_mruFiles);
1791 m_config->write();
1792 m_actions.addSeparator("mru");
1793 m_actions.addAction(tr("Clear"), "resetMru", this, &Window::clearMRU, "mru");
1794
1795 m_actions.rebuildMenu(menuBar(), this, *m_shortcutController);
1796}
1797
1798Action* Window::addGameAction(const QString& visibleName, const QString& name, Action::Function function, const QString& menu, const QKeySequence& shortcut) {
1799 Action* action = m_actions.addAction(visibleName, name, [this, function]() {
1800 if (m_controller) {
1801 function();
1802 }
1803 }, menu, shortcut);
1804 m_gameActions.append(action);
1805 return action;
1806}
1807
1808template<typename T, typename V>
1809Action* Window::addGameAction(const QString& visibleName, const QString& name, T* obj, V (T::*method)(), const QString& menu, const QKeySequence& shortcut) {
1810 return addGameAction(visibleName, name, [this, obj, method]() {
1811 (obj->*method)();
1812 }, menu, shortcut);
1813}
1814
1815template<typename V>
1816Action* Window::addGameAction(const QString& visibleName, const QString& name, V (CoreController::*method)(), const QString& menu, const QKeySequence& shortcut) {
1817 return addGameAction(visibleName, name, [this, method]() {
1818 (m_controller.get()->*method)();
1819 }, menu, shortcut);
1820}
1821
1822Action* Window::addGameAction(const QString& visibleName, const QString& name, Action::BooleanFunction function, const QString& menu, const QKeySequence& shortcut) {
1823 Action* action = m_actions.addBooleanAction(visibleName, name, [this, function](bool value) {
1824 if (m_controller) {
1825 function(value);
1826 }
1827 }, menu, shortcut);
1828 m_gameActions.append(action);
1829 return action;
1830}
1831
1832void Window::focusCheck() {
1833 if (!m_config->getOption("pauseOnFocusLost").toInt() || !m_controller) {
1834 return;
1835 }
1836 if (QGuiApplication::focusWindow() && m_autoresume) {
1837 m_controller->setPaused(false);
1838 m_autoresume = false;
1839 } else if (!QGuiApplication::focusWindow() && !m_controller->isPaused()) {
1840 m_autoresume = true;
1841 m_controller->setPaused(true);
1842 }
1843}
1844
1845void Window::updateFrame() {
1846 QPixmap pixmap;
1847 pixmap.convertFromImage(m_controller->getPixels());
1848 m_screenWidget->setPixmap(pixmap);
1849 emit paused(true);
1850}
1851
1852void Window::setController(CoreController* controller, const QString& fname) {
1853 if (!controller) {
1854 return;
1855 }
1856 if (m_pendingClose) {
1857 return;
1858 }
1859
1860 if (m_controller) {
1861 m_controller->stop();
1862 QTimer::singleShot(0, this, [this, controller, fname]() {
1863 setController(controller, fname);
1864 });
1865 return;
1866 }
1867 if (!fname.isEmpty()) {
1868 setWindowFilePath(fname);
1869 appendMRU(fname);
1870 }
1871
1872 if (!m_display) {
1873 reloadDisplayDriver();
1874 }
1875
1876 m_controller = std::shared_ptr<CoreController>(controller);
1877 m_inputController.recalibrateAxes();
1878 m_controller->setInputController(&m_inputController);
1879 m_controller->setLogger(&m_log);
1880 m_display->startDrawing(m_controller);
1881
1882 connect(this, &Window::shutdown, [this]() {
1883 if (!m_controller) {
1884 return;
1885 }
1886 m_controller->stop();
1887 disconnect(m_controller.get(), &CoreController::started, this, &Window::gameStarted);
1888 });
1889
1890 connect(m_controller.get(), &CoreController::started, this, &Window::gameStarted);
1891 connect(m_controller.get(), &CoreController::started, &m_inputController, &InputController::suspendScreensaver);
1892 connect(m_controller.get(), &CoreController::stopping, this, &Window::gameStopped);
1893 {
1894 connect(m_controller.get(), &CoreController::stopping, [this]() {
1895 m_controller.reset();
1896 });
1897 }
1898 connect(m_controller.get(), &CoreController::stopping, &m_inputController, &InputController::resumeScreensaver);
1899 connect(m_controller.get(), &CoreController::paused, this, &Window::updateFrame);
1900
1901#ifndef Q_OS_MAC
1902 connect(m_controller.get(), &CoreController::paused, menuBar(), &QWidget::show);
1903 connect(m_controller.get(), &CoreController::unpaused, [this]() {
1904 if(isFullScreen()) {
1905 menuBar()->hide();
1906 }
1907 });
1908#endif
1909
1910 connect(m_controller.get(), &CoreController::paused, &m_inputController, &InputController::resumeScreensaver);
1911 connect(m_controller.get(), &CoreController::unpaused, [this]() {
1912 emit paused(false);
1913 });
1914
1915 attachDisplay();
1916
1917 connect(m_controller.get(), &CoreController::unpaused, &m_inputController, &InputController::suspendScreensaver);
1918 connect(m_controller.get(), &CoreController::frameAvailable, this, &Window::recordFrame);
1919 connect(m_controller.get(), &CoreController::crashed, this, &Window::gameCrashed);
1920 connect(m_controller.get(), &CoreController::failed, this, &Window::gameFailed);
1921 connect(m_controller.get(), &CoreController::unimplementedBiosCall, this, &Window::unimplementedBiosCall);
1922
1923#ifdef USE_GDB_STUB
1924 if (m_gdbController) {
1925 m_gdbController->setController(m_controller);
1926 }
1927#endif
1928
1929#ifdef USE_DEBUGGERS
1930 if (m_console) {
1931 m_console->setController(m_controller);
1932 }
1933#endif
1934
1935#ifdef USE_FFMPEG
1936 if (m_gifView) {
1937 m_gifView->setController(m_controller);
1938 }
1939
1940 if (m_videoView) {
1941 m_videoView->setController(m_controller);
1942 }
1943#endif
1944
1945 if (m_sensorView) {
1946 m_sensorView->setController(m_controller);
1947 }
1948
1949 if (m_overrideView) {
1950 m_overrideView->setController(m_controller);
1951 }
1952
1953 if (!m_pendingPatch.isEmpty()) {
1954 m_controller->loadPatch(m_pendingPatch);
1955 m_pendingPatch = QString();
1956 }
1957
1958 m_controller->loadConfig(m_config);
1959 m_controller->start();
1960
1961 if (!m_pendingState.isEmpty()) {
1962 m_controller->loadState(m_pendingState);
1963 m_pendingState = QString();
1964 }
1965
1966 if (m_pendingPause) {
1967 m_controller->setPaused(true);
1968 m_pendingPause = false;
1969 }
1970}
1971
1972void Window::attachDisplay() {
1973 connect(m_controller.get(), &CoreController::stateLoaded, m_display.get(), &Display::resizeContext);
1974 connect(m_controller.get(), &CoreController::stateLoaded, m_display.get(), &Display::forceDraw);
1975 connect(m_controller.get(), &CoreController::rewound, m_display.get(), &Display::forceDraw);
1976 connect(m_controller.get(), &CoreController::paused, m_display.get(), &Display::pauseDrawing);
1977 connect(m_controller.get(), &CoreController::unpaused, m_display.get(), &Display::unpauseDrawing);
1978 connect(m_controller.get(), &CoreController::frameAvailable, m_display.get(), &Display::framePosted);
1979 connect(m_controller.get(), &CoreController::statusPosted, m_display.get(), &Display::showMessage);
1980 connect(m_controller.get(), &CoreController::didReset, m_display.get(), &Display::resizeContext);
1981 changeRenderer();
1982}
1983
1984WindowBackground::WindowBackground(QWidget* parent)
1985 : QWidget(parent)
1986{
1987 setLayout(new QStackedLayout());
1988 layout()->setContentsMargins(0, 0, 0, 0);
1989}
1990
1991void WindowBackground::setPixmap(const QPixmap& pmap) {
1992 m_pixmap = pmap;
1993 update();
1994}
1995
1996void WindowBackground::setSizeHint(const QSize& hint) {
1997 m_sizeHint = hint;
1998}
1999
2000QSize WindowBackground::sizeHint() const {
2001 return m_sizeHint;
2002}
2003
2004void WindowBackground::setCenteredAspectRatio(int width, int height) {
2005 m_centered = true;
2006 m_lockAspectRatio = true;
2007 setDimensions(width, height);
2008}
2009
2010void WindowBackground::setDimensions(int width, int height) {
2011 m_aspectWidth = width;
2012 m_aspectHeight = height;
2013}
2014
2015void WindowBackground::setLockIntegerScaling(bool lock) {
2016 m_lockIntegerScaling = lock;
2017}
2018
2019void WindowBackground::setLockAspectRatio(bool lock) {
2020 m_centered = false;
2021 m_lockAspectRatio = lock;
2022}
2023
2024void WindowBackground::filter(bool filter) {
2025 m_filter = filter;
2026}
2027
2028void WindowBackground::paintEvent(QPaintEvent* event) {
2029 QWidget::paintEvent(event);
2030 const QPixmap& logo = pixmap();
2031 QPainter painter(this);
2032 painter.setRenderHint(QPainter::SmoothPixmapTransform, m_filter);
2033 painter.fillRect(QRect(QPoint(), size()), Qt::black);
2034 QSize s = size();
2035 QSize ds = s;
2036 if (m_centered) {
2037 if (ds.width() * m_aspectHeight < ds.height() * m_aspectWidth) {
2038 ds.setWidth(ds.height() * m_aspectWidth / m_aspectHeight);
2039 } else if (ds.width() * m_aspectHeight > ds.height() * m_aspectWidth) {
2040 ds.setHeight(ds.width() * m_aspectHeight / m_aspectWidth);
2041 }
2042 } else if (m_lockAspectRatio) {
2043 if (ds.width() * m_aspectHeight > ds.height() * m_aspectWidth) {
2044 ds.setWidth(ds.height() * m_aspectWidth / m_aspectHeight);
2045 } else if (ds.width() * m_aspectHeight < ds.height() * m_aspectWidth) {
2046 ds.setHeight(ds.width() * m_aspectHeight / m_aspectWidth);
2047 }
2048 }
2049 if (m_lockIntegerScaling) {
2050 if (ds.width() >= m_aspectWidth) {
2051 ds.setWidth(ds.width() - ds.width() % m_aspectWidth);
2052 }
2053 if (ds.height() >= m_aspectHeight) {
2054 ds.setHeight(ds.height() - ds.height() % m_aspectHeight);
2055 }
2056 }
2057 QPoint origin = QPoint((s.width() - ds.width()) / 2, (s.height() - ds.height()) / 2);
2058 QRect full(origin, ds);
2059 painter.drawPixmap(full, logo);
2060}