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