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