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