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