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