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* loadTemporarySave = new QAction(tr("Load temporary save..."), fileMenu);
993 connect(loadTemporarySave, &QAction::triggered, [this]() { this->selectSave(true); });
994 m_gameActions.append(loadTemporarySave);
995 addControlledAction(fileMenu, loadTemporarySave, "loadTemporarySave");
996
997 addControlledAction(fileMenu, fileMenu->addAction(tr("Load &patch..."), this, SLOT(selectPatch())), "loadPatch");
998
999#ifdef M_CORE_GBA
1000 QAction* bootBIOS = new QAction(tr("Boot BIOS"), fileMenu);
1001 connect(bootBIOS, &QAction::triggered, [this]() {
1002 setController(m_manager->loadBIOS(PLATFORM_GBA, m_config->getOption("gba.bios")), QString());
1003 });
1004 addControlledAction(fileMenu, bootBIOS, "bootBIOS");
1005#endif
1006
1007 addControlledAction(fileMenu, fileMenu->addAction(tr("Replace ROM..."), this, SLOT(replaceROM())), "replaceROM");
1008
1009 QAction* romInfo = new QAction(tr("ROM &info..."), fileMenu);
1010 connect(romInfo, &QAction::triggered, openControllerTView<ROMInfo>());
1011 m_gameActions.append(romInfo);
1012 addControlledAction(fileMenu, romInfo, "romInfo");
1013
1014 m_mruMenu = fileMenu->addMenu(tr("Recent"));
1015
1016 fileMenu->addSeparator();
1017
1018 addControlledAction(fileMenu, fileMenu->addAction(tr("Make portable"), this, SLOT(tryMakePortable())), "makePortable");
1019
1020 fileMenu->addSeparator();
1021
1022 QAction* loadState = new QAction(tr("&Load state"), fileMenu);
1023 loadState->setShortcut(tr("F10"));
1024 connect(loadState, &QAction::triggered, [this]() { this->openStateWindow(LoadSave::LOAD); });
1025 m_gameActions.append(loadState);
1026 m_nonMpActions.append(loadState);
1027 addControlledAction(fileMenu, loadState, "loadState");
1028
1029 QAction* saveState = new QAction(tr("&Save state"), fileMenu);
1030 saveState->setShortcut(tr("Shift+F10"));
1031 connect(saveState, &QAction::triggered, [this]() { this->openStateWindow(LoadSave::SAVE); });
1032 m_gameActions.append(saveState);
1033 m_nonMpActions.append(saveState);
1034 addControlledAction(fileMenu, saveState, "saveState");
1035
1036 QMenu* quickLoadMenu = fileMenu->addMenu(tr("Quick load"));
1037 QMenu* quickSaveMenu = fileMenu->addMenu(tr("Quick save"));
1038 m_shortcutController->addMenu(quickLoadMenu);
1039 m_shortcutController->addMenu(quickSaveMenu);
1040
1041 QAction* quickLoad = new QAction(tr("Load recent"), quickLoadMenu);
1042 connect(quickLoad, &QAction::triggered, [this] {
1043 m_controller->loadState();
1044 });
1045 m_gameActions.append(quickLoad);
1046 m_nonMpActions.append(quickLoad);
1047 addControlledAction(quickLoadMenu, quickLoad, "quickLoad");
1048
1049 QAction* quickSave = new QAction(tr("Save recent"), quickSaveMenu);
1050 connect(quickLoad, &QAction::triggered, [this] {
1051 m_controller->saveState();
1052 });
1053 m_gameActions.append(quickSave);
1054 m_nonMpActions.append(quickSave);
1055 addControlledAction(quickSaveMenu, quickSave, "quickSave");
1056
1057 quickLoadMenu->addSeparator();
1058 quickSaveMenu->addSeparator();
1059
1060 QAction* undoLoadState = new QAction(tr("Undo load state"), quickLoadMenu);
1061 undoLoadState->setShortcut(tr("F11"));
1062 connect(undoLoadState, &QAction::triggered, [this]() {
1063 m_controller->loadBackupState();
1064 });
1065 m_gameActions.append(undoLoadState);
1066 m_nonMpActions.append(undoLoadState);
1067 addControlledAction(quickLoadMenu, undoLoadState, "undoLoadState");
1068
1069 QAction* undoSaveState = new QAction(tr("Undo save state"), quickSaveMenu);
1070 undoSaveState->setShortcut(tr("Shift+F11"));
1071 connect(undoSaveState, &QAction::triggered, [this]() {
1072 m_controller->saveBackupState();
1073 });
1074 m_gameActions.append(undoSaveState);
1075 m_nonMpActions.append(undoSaveState);
1076 addControlledAction(quickSaveMenu, undoSaveState, "undoSaveState");
1077
1078 quickLoadMenu->addSeparator();
1079 quickSaveMenu->addSeparator();
1080
1081 int i;
1082 for (i = 1; i < 10; ++i) {
1083 quickLoad = new QAction(tr("State &%1").arg(i), quickLoadMenu);
1084 quickLoad->setShortcut(tr("F%1").arg(i));
1085 connect(quickLoad, &QAction::triggered, [this, i]() {
1086 m_controller->loadState(i);
1087 });
1088 m_gameActions.append(quickLoad);
1089 m_nonMpActions.append(quickLoad);
1090 addControlledAction(quickLoadMenu, quickLoad, QString("quickLoad.%1").arg(i));
1091
1092 quickSave = new QAction(tr("State &%1").arg(i), quickSaveMenu);
1093 quickSave->setShortcut(tr("Shift+F%1").arg(i));
1094 connect(quickSave, &QAction::triggered, [this, i]() {
1095 m_controller->saveState(i);
1096 });
1097 m_gameActions.append(quickSave);
1098 m_nonMpActions.append(quickSave);
1099 addControlledAction(quickSaveMenu, quickSave, QString("quickSave.%1").arg(i));
1100 }
1101
1102 fileMenu->addSeparator();
1103 QAction* camImage = new QAction(tr("Load camera image..."), fileMenu);
1104 connect(camImage, &QAction::triggered, this, &Window::loadCamImage);
1105 addControlledAction(fileMenu, camImage, "loadCamImage");
1106
1107#ifdef M_CORE_GBA
1108 fileMenu->addSeparator();
1109 QAction* importShark = new QAction(tr("Import GameShark Save"), fileMenu);
1110 connect(importShark, &QAction::triggered, this, &Window::importSharkport);
1111 m_gameActions.append(importShark);
1112 m_gbaActions.append(importShark);
1113 addControlledAction(fileMenu, importShark, "importShark");
1114
1115 QAction* exportShark = new QAction(tr("Export GameShark Save"), fileMenu);
1116 connect(exportShark, &QAction::triggered, this, &Window::exportSharkport);
1117 m_gameActions.append(exportShark);
1118 m_gbaActions.append(exportShark);
1119 addControlledAction(fileMenu, exportShark, "exportShark");
1120#endif
1121
1122 fileMenu->addSeparator();
1123 m_multiWindow = new QAction(tr("New multiplayer window"), fileMenu);
1124 connect(m_multiWindow, &QAction::triggered, [this]() {
1125 GBAApp::app()->newWindow();
1126 });
1127 addControlledAction(fileMenu, m_multiWindow, "multiWindow");
1128
1129#ifndef Q_OS_MAC
1130 fileMenu->addSeparator();
1131#endif
1132
1133 QAction* about = new QAction(tr("About"), fileMenu);
1134 connect(about, &QAction::triggered, openTView<AboutScreen>());
1135 fileMenu->addAction(about);
1136
1137#ifndef Q_OS_MAC
1138 addControlledAction(fileMenu, fileMenu->addAction(tr("E&xit"), this, SLOT(close()), QKeySequence::Quit), "quit");
1139#endif
1140
1141 QMenu* emulationMenu = menubar->addMenu(tr("&Emulation"));
1142 m_shortcutController->addMenu(emulationMenu);
1143 QAction* reset = new QAction(tr("&Reset"), emulationMenu);
1144 reset->setShortcut(tr("Ctrl+R"));
1145 connect(reset, &QAction::triggered, [this]() {
1146 m_controller->reset();
1147 });
1148 m_gameActions.append(reset);
1149 addControlledAction(emulationMenu, reset, "reset");
1150
1151 QAction* shutdown = new QAction(tr("Sh&utdown"), emulationMenu);
1152 connect(shutdown, &QAction::triggered, [this]() {
1153 m_controller->stop();
1154 });
1155 m_gameActions.append(shutdown);
1156 addControlledAction(emulationMenu, shutdown, "shutdown");
1157
1158#ifdef M_CORE_GBA
1159 QAction* yank = new QAction(tr("Yank game pak"), emulationMenu);
1160 connect(yank, &QAction::triggered, [this]() {
1161 m_controller->yankPak();
1162 });
1163 m_gameActions.append(yank);
1164 m_gbaActions.append(yank);
1165 addControlledAction(emulationMenu, yank, "yank");
1166#endif
1167 emulationMenu->addSeparator();
1168
1169 QAction* pause = new QAction(tr("&Pause"), emulationMenu);
1170 pause->setChecked(false);
1171 pause->setCheckable(true);
1172 pause->setShortcut(tr("Ctrl+P"));
1173 connect(pause, &QAction::triggered, [this](bool paused) {
1174 m_controller->setPaused(paused);
1175 });
1176 connect(this, &Window::paused, [pause](bool paused) {
1177 pause->setChecked(paused);
1178 });
1179 m_gameActions.append(pause);
1180 addControlledAction(emulationMenu, pause, "pause");
1181
1182 QAction* frameAdvance = new QAction(tr("&Next frame"), emulationMenu);
1183 frameAdvance->setShortcut(tr("Ctrl+N"));
1184 connect(frameAdvance, &QAction::triggered, [this]() {
1185 m_controller->frameAdvance();
1186 });
1187 m_gameActions.append(frameAdvance);
1188 addControlledAction(emulationMenu, frameAdvance, "frameAdvance");
1189
1190 emulationMenu->addSeparator();
1191
1192 m_shortcutController->addFunctions(emulationMenu, [this]() {
1193 if (m_controller) {
1194 m_controller->setFastForward(true);
1195 }
1196 }, [this]() {
1197 if (m_controller) {
1198 m_controller->setFastForward(false);
1199 }
1200 }, QKeySequence(Qt::Key_Tab), tr("Fast forward (held)"), "holdFastForward");
1201
1202 QAction* turbo = new QAction(tr("&Fast forward"), emulationMenu);
1203 turbo->setCheckable(true);
1204 turbo->setChecked(false);
1205 turbo->setShortcut(tr("Shift+Tab"));
1206 connect(turbo, &QAction::triggered, [this](bool value) {
1207 m_controller->forceFastForward(value);
1208 });
1209 addControlledAction(emulationMenu, turbo, "fastForward");
1210 m_gameActions.append(turbo);
1211
1212 QMenu* ffspeedMenu = emulationMenu->addMenu(tr("Fast forward speed"));
1213 ConfigOption* ffspeed = m_config->addOption("fastForwardRatio");
1214 ffspeed->connect([this](const QVariant& value) {
1215 reloadConfig();
1216 }, this);
1217 ffspeed->addValue(tr("Unbounded"), -1.0f, ffspeedMenu);
1218 ffspeed->setValue(QVariant(-1.0f));
1219 ffspeedMenu->addSeparator();
1220 for (i = 2; i < 11; ++i) {
1221 ffspeed->addValue(tr("%0x").arg(i), i, ffspeedMenu);
1222 }
1223 m_config->updateOption("fastForwardRatio");
1224
1225 m_shortcutController->addFunctions(emulationMenu, [this]() {
1226 if (m_controller) {
1227 m_controller->setRewinding(true);
1228 }
1229 }, [this]() {
1230 if (m_controller) {
1231 m_controller->setRewinding(false);
1232 }
1233 }, QKeySequence("`"), tr("Rewind (held)"), "holdRewind");
1234
1235 QAction* rewind = new QAction(tr("Re&wind"), emulationMenu);
1236 rewind->setShortcut(tr("~"));
1237 connect(rewind, &QAction::triggered, [this]() {
1238 m_controller->rewind();
1239 });
1240 m_gameActions.append(rewind);
1241 m_nonMpActions.append(rewind);
1242 addControlledAction(emulationMenu, rewind, "rewind");
1243
1244 QAction* frameRewind = new QAction(tr("Step backwards"), emulationMenu);
1245 frameRewind->setShortcut(tr("Ctrl+B"));
1246 connect(frameRewind, &QAction::triggered, [this] () {
1247 m_controller->rewind(1);
1248 });
1249 m_gameActions.append(frameRewind);
1250 m_nonMpActions.append(frameRewind);
1251 addControlledAction(emulationMenu, frameRewind, "frameRewind");
1252
1253 ConfigOption* videoSync = m_config->addOption("videoSync");
1254 videoSync->addBoolean(tr("Sync to &video"), emulationMenu);
1255 videoSync->connect([this](const QVariant& value) {
1256 reloadConfig();
1257 }, this);
1258 m_config->updateOption("videoSync");
1259
1260 ConfigOption* audioSync = m_config->addOption("audioSync");
1261 audioSync->addBoolean(tr("Sync to &audio"), emulationMenu);
1262 audioSync->connect([this](const QVariant& value) {
1263 reloadConfig();
1264 }, this);
1265 m_config->updateOption("audioSync");
1266
1267 emulationMenu->addSeparator();
1268
1269 QMenu* solarMenu = emulationMenu->addMenu(tr("Solar sensor"));
1270 m_shortcutController->addMenu(solarMenu);
1271 QAction* solarIncrease = new QAction(tr("Increase solar level"), solarMenu);
1272 connect(solarIncrease, &QAction::triggered, &m_inputController, &InputController::increaseLuminanceLevel);
1273 addControlledAction(solarMenu, solarIncrease, "increaseLuminanceLevel");
1274
1275 QAction* solarDecrease = new QAction(tr("Decrease solar level"), solarMenu);
1276 connect(solarDecrease, &QAction::triggered, &m_inputController, &InputController::decreaseLuminanceLevel);
1277 addControlledAction(solarMenu, solarDecrease, "decreaseLuminanceLevel");
1278
1279 QAction* maxSolar = new QAction(tr("Brightest solar level"), solarMenu);
1280 connect(maxSolar, &QAction::triggered, [this]() { m_inputController.setLuminanceLevel(10); });
1281 addControlledAction(solarMenu, maxSolar, "maxLuminanceLevel");
1282
1283 QAction* minSolar = new QAction(tr("Darkest solar level"), solarMenu);
1284 connect(minSolar, &QAction::triggered, [this]() { m_inputController.setLuminanceLevel(0); });
1285 addControlledAction(solarMenu, minSolar, "minLuminanceLevel");
1286
1287 solarMenu->addSeparator();
1288 for (int i = 0; i <= 10; ++i) {
1289 QAction* setSolar = new QAction(tr("Brightness %1").arg(QString::number(i)), solarMenu);
1290 connect(setSolar, &QAction::triggered, [this, i]() {
1291 m_inputController.setLuminanceLevel(i);
1292 });
1293 addControlledAction(solarMenu, setSolar, QString("luminanceLevel.%1").arg(QString::number(i)));
1294 }
1295
1296 QMenu* avMenu = menubar->addMenu(tr("Audio/&Video"));
1297 m_shortcutController->addMenu(avMenu);
1298 QMenu* frameMenu = avMenu->addMenu(tr("Frame size"));
1299 m_shortcutController->addMenu(frameMenu, avMenu);
1300 for (int i = 1; i <= 6; ++i) {
1301 QAction* setSize = new QAction(tr("%1x").arg(QString::number(i)), avMenu);
1302 setSize->setCheckable(true);
1303 if (m_savedScale == i) {
1304 setSize->setChecked(true);
1305 }
1306 connect(setSize, &QAction::triggered, [this, i, setSize]() {
1307 showNormal();
1308 QSize size(VIDEO_HORIZONTAL_PIXELS, VIDEO_VERTICAL_PIXELS);
1309 if (m_controller) {
1310 size = m_controller->screenDimensions();
1311 }
1312 size *= i;
1313 m_savedScale = i;
1314 m_config->setOption("scaleMultiplier", i); // TODO: Port to other
1315 resizeFrame(size);
1316 bool enableSignals = setSize->blockSignals(true);
1317 setSize->setChecked(true);
1318 setSize->blockSignals(enableSignals);
1319 });
1320 m_frameSizes[i] = setSize;
1321 addControlledAction(frameMenu, setSize, QString("frame%1x").arg(QString::number(i)));
1322 }
1323 QKeySequence fullscreenKeys;
1324#ifdef Q_OS_WIN
1325 fullscreenKeys = QKeySequence("Alt+Return");
1326#else
1327 fullscreenKeys = QKeySequence("Ctrl+F");
1328#endif
1329 addControlledAction(frameMenu, frameMenu->addAction(tr("Toggle fullscreen"), this, SLOT(toggleFullScreen()), fullscreenKeys), "fullscreen");
1330
1331 ConfigOption* lockAspectRatio = m_config->addOption("lockAspectRatio");
1332 lockAspectRatio->addBoolean(tr("Lock aspect ratio"), avMenu);
1333 lockAspectRatio->connect([this](const QVariant& value) {
1334 m_display->lockAspectRatio(value.toBool());
1335 if (m_controller) {
1336 m_screenWidget->setLockAspectRatio(value.toBool());
1337 }
1338 }, this);
1339 m_config->updateOption("lockAspectRatio");
1340
1341 ConfigOption* lockIntegerScaling = m_config->addOption("lockIntegerScaling");
1342 lockIntegerScaling->addBoolean(tr("Force integer scaling"), avMenu);
1343 lockIntegerScaling->connect([this](const QVariant& value) {
1344 m_display->lockIntegerScaling(value.toBool());
1345 if (m_controller) {
1346 m_screenWidget->setLockIntegerScaling(value.toBool());
1347 }
1348 }, this);
1349 m_config->updateOption("lockIntegerScaling");
1350
1351 ConfigOption* resampleVideo = m_config->addOption("resampleVideo");
1352 resampleVideo->addBoolean(tr("Bilinear filtering"), avMenu);
1353 resampleVideo->connect([this](const QVariant& value) {
1354 m_display->filter(value.toBool());
1355 }, this);
1356 m_config->updateOption("resampleVideo");
1357
1358 QMenu* skipMenu = avMenu->addMenu(tr("Frame&skip"));
1359 ConfigOption* skip = m_config->addOption("frameskip");
1360 skip->connect([this](const QVariant& value) {
1361 reloadConfig();
1362 }, this);
1363 for (int i = 0; i <= 10; ++i) {
1364 skip->addValue(QString::number(i), i, skipMenu);
1365 }
1366 m_config->updateOption("frameskip");
1367
1368 avMenu->addSeparator();
1369
1370 ConfigOption* mute = m_config->addOption("mute");
1371 QAction* muteAction = mute->addBoolean(tr("Mute"), avMenu);
1372 mute->connect([this](const QVariant& value) {
1373 reloadConfig();
1374 }, this);
1375 m_config->updateOption("mute");
1376 addControlledAction(avMenu, muteAction, "mute");
1377
1378 QMenu* target = avMenu->addMenu(tr("FPS target"));
1379 ConfigOption* fpsTargetOption = m_config->addOption("fpsTarget");
1380 fpsTargetOption->connect([this](const QVariant& value) {
1381 reloadConfig();
1382 }, this);
1383 fpsTargetOption->addValue(tr("15"), 15, target);
1384 fpsTargetOption->addValue(tr("30"), 30, target);
1385 fpsTargetOption->addValue(tr("45"), 45, target);
1386 fpsTargetOption->addValue(tr("Native (59.7)"), float(GBA_ARM7TDMI_FREQUENCY) / float(VIDEO_TOTAL_LENGTH), target);
1387 fpsTargetOption->addValue(tr("60"), 60, target);
1388 fpsTargetOption->addValue(tr("90"), 90, target);
1389 fpsTargetOption->addValue(tr("120"), 120, target);
1390 fpsTargetOption->addValue(tr("240"), 240, target);
1391 m_config->updateOption("fpsTarget");
1392
1393 avMenu->addSeparator();
1394
1395#ifdef USE_PNG
1396 QAction* screenshot = new QAction(tr("Take &screenshot"), avMenu);
1397 screenshot->setShortcut(tr("F12"));
1398 connect(screenshot, &QAction::triggered, [this]() {
1399 m_controller->screenshot();
1400 });
1401 m_gameActions.append(screenshot);
1402 addControlledAction(avMenu, screenshot, "screenshot");
1403#endif
1404
1405#ifdef USE_FFMPEG
1406 QAction* recordOutput = new QAction(tr("Record output..."), avMenu);
1407 connect(recordOutput, &QAction::triggered, this, &Window::openVideoWindow);
1408 addControlledAction(avMenu, recordOutput, "recordOutput");
1409 m_gameActions.append(recordOutput);
1410#endif
1411
1412#ifdef USE_MAGICK
1413 QAction* recordGIF = new QAction(tr("Record GIF..."), avMenu);
1414 connect(recordGIF, &QAction::triggered, this, &Window::openGIFWindow);
1415 addControlledAction(avMenu, recordGIF, "recordGIF");
1416#endif
1417
1418 QAction* recordVL = new QAction(tr("Record video log..."), avMenu);
1419 connect(recordVL, &QAction::triggered, this, &Window::startVideoLog);
1420 addControlledAction(avMenu, recordVL, "recordVL");
1421 m_gameActions.append(recordVL);
1422
1423 QAction* stopVL = new QAction(tr("Stop video log"), avMenu);
1424 connect(stopVL, &QAction::triggered, [this]() {
1425 m_controller->endVideoLog();
1426 });
1427 addControlledAction(avMenu, stopVL, "stopVL");
1428 m_gameActions.append(stopVL);
1429
1430#ifdef M_CORE_GB
1431 QAction* gbPrint = new QAction(tr("Game Boy Printer..."), avMenu);
1432 connect(gbPrint, &QAction::triggered, [this]() {
1433 PrinterView* view = new PrinterView(m_controller);
1434 openView(view);
1435 m_controller->attachPrinter();
1436
1437 });
1438 addControlledAction(avMenu, gbPrint, "gbPrint");
1439 m_gameActions.append(gbPrint);
1440#endif
1441
1442 avMenu->addSeparator();
1443 m_videoLayers = avMenu->addMenu(tr("Video layers"));
1444 m_shortcutController->addMenu(m_videoLayers, avMenu);
1445
1446 m_audioChannels = avMenu->addMenu(tr("Audio channels"));
1447 m_shortcutController->addMenu(m_audioChannels, avMenu);
1448
1449 QAction* placementControl = new QAction(tr("Adjust layer placement..."), avMenu);
1450 connect(placementControl, &QAction::triggered, openControllerTView<PlacementControl>());
1451 m_gameActions.append(placementControl);
1452 addControlledAction(avMenu, placementControl, "placementControl");
1453
1454 QMenu* toolsMenu = menubar->addMenu(tr("&Tools"));
1455 m_shortcutController->addMenu(toolsMenu);
1456 QAction* viewLogs = new QAction(tr("View &logs..."), toolsMenu);
1457 connect(viewLogs, &QAction::triggered, m_logView, &QWidget::show);
1458 addControlledAction(toolsMenu, viewLogs, "viewLogs");
1459
1460 QAction* overrides = new QAction(tr("Game &overrides..."), toolsMenu);
1461 connect(overrides, &QAction::triggered, [this]() {
1462 if (!m_overrideView) {
1463 m_overrideView = std::move(std::make_unique<OverrideView>(m_config));
1464 if (m_controller) {
1465 m_overrideView->setController(m_controller);
1466 }
1467 connect(this, &Window::shutdown, m_overrideView.get(), &QWidget::close);
1468 }
1469 m_overrideView->show();
1470 m_overrideView->recheck();
1471 });
1472 addControlledAction(toolsMenu, overrides, "overrideWindow");
1473
1474 QAction* sensors = new QAction(tr("Game &Pak sensors..."), toolsMenu);
1475 connect(sensors, &QAction::triggered, [this]() {
1476 if (!m_sensorView) {
1477 m_sensorView = std::move(std::make_unique<SensorView>(&m_inputController));
1478 if (m_controller) {
1479 m_sensorView->setController(m_controller);
1480 }
1481 connect(this, &Window::shutdown, m_sensorView.get(), &QWidget::close);
1482 }
1483 m_sensorView->show();
1484 });
1485 addControlledAction(toolsMenu, sensors, "sensorWindow");
1486
1487 QAction* cheats = new QAction(tr("&Cheats..."), toolsMenu);
1488 connect(cheats, &QAction::triggered, openControllerTView<CheatsView>());
1489 m_gameActions.append(cheats);
1490 addControlledAction(toolsMenu, cheats, "cheatsWindow");
1491
1492 toolsMenu->addSeparator();
1493 addControlledAction(toolsMenu, toolsMenu->addAction(tr("Settings..."), this, SLOT(openSettingsWindow())),
1494 "settings");
1495
1496 toolsMenu->addSeparator();
1497
1498#ifdef USE_DEBUGGERS
1499 QAction* consoleWindow = new QAction(tr("Open debugger console..."), toolsMenu);
1500 connect(consoleWindow, &QAction::triggered, this, &Window::consoleOpen);
1501 addControlledAction(toolsMenu, consoleWindow, "debuggerWindow");
1502#endif
1503
1504#ifdef USE_GDB_STUB
1505 QAction* gdbWindow = new QAction(tr("Start &GDB server..."), toolsMenu);
1506 connect(gdbWindow, &QAction::triggered, this, &Window::gdbOpen);
1507 m_gbaActions.append(gdbWindow);
1508 m_gameActions.append(gdbWindow);
1509 addControlledAction(toolsMenu, gdbWindow, "gdbWindow");
1510#endif
1511 toolsMenu->addSeparator();
1512
1513 QAction* paletteView = new QAction(tr("View &palette..."), toolsMenu);
1514 connect(paletteView, &QAction::triggered, openControllerTView<PaletteView>());
1515 m_gameActions.append(paletteView);
1516 addControlledAction(toolsMenu, paletteView, "paletteWindow");
1517
1518 QAction* objView = new QAction(tr("View &sprites..."), toolsMenu);
1519 connect(objView, &QAction::triggered, openControllerTView<ObjView>());
1520 m_gameActions.append(objView);
1521 addControlledAction(toolsMenu, objView, "spriteWindow");
1522
1523 QAction* tileView = new QAction(tr("View &tiles..."), toolsMenu);
1524 connect(tileView, &QAction::triggered, openControllerTView<TileView>());
1525 m_gameActions.append(tileView);
1526 addControlledAction(toolsMenu, tileView, "tileWindow");
1527
1528 QAction* mapView = new QAction(tr("View &map..."), toolsMenu);
1529 connect(mapView, &QAction::triggered, openControllerTView<MapView>());
1530 m_gameActions.append(mapView);
1531 addControlledAction(toolsMenu, mapView, "mapWindow");
1532
1533 QAction* memoryView = new QAction(tr("View memory..."), toolsMenu);
1534 connect(memoryView, &QAction::triggered, openControllerTView<MemoryView>());
1535 m_gameActions.append(memoryView);
1536 addControlledAction(toolsMenu, memoryView, "memoryView");
1537
1538 QAction* memorySearch = new QAction(tr("Search memory..."), toolsMenu);
1539 connect(memorySearch, &QAction::triggered, openControllerTView<MemorySearch>());
1540 m_gameActions.append(memorySearch);
1541 addControlledAction(toolsMenu, memorySearch, "memorySearch");
1542
1543#ifdef M_CORE_GBA
1544 QAction* ioViewer = new QAction(tr("View &I/O registers..."), toolsMenu);
1545 connect(ioViewer, &QAction::triggered, openControllerTView<IOViewer>());
1546 m_gameActions.append(ioViewer);
1547 m_gbaActions.append(ioViewer);
1548 addControlledAction(toolsMenu, ioViewer, "ioViewer");
1549#endif
1550
1551 ConfigOption* skipBios = m_config->addOption("skipBios");
1552 skipBios->connect([this](const QVariant& value) {
1553 reloadConfig();
1554 }, this);
1555
1556 ConfigOption* useBios = m_config->addOption("useBios");
1557 useBios->connect([this](const QVariant& value) {
1558 reloadConfig();
1559 }, this);
1560
1561 ConfigOption* buffers = m_config->addOption("audioBuffers");
1562 buffers->connect([this](const QVariant& value) {
1563 reloadConfig();
1564 }, this);
1565
1566 ConfigOption* sampleRate = m_config->addOption("sampleRate");
1567 sampleRate->connect([this](const QVariant& value) {
1568 reloadConfig();
1569 }, this);
1570
1571 ConfigOption* volume = m_config->addOption("volume");
1572 volume->connect([this](const QVariant& value) {
1573 reloadConfig();
1574 }, this);
1575
1576 ConfigOption* rewindEnable = m_config->addOption("rewindEnable");
1577 rewindEnable->connect([this](const QVariant& value) {
1578 reloadConfig();
1579 }, this);
1580
1581 ConfigOption* rewindBufferCapacity = m_config->addOption("rewindBufferCapacity");
1582 rewindBufferCapacity->connect([this](const QVariant& value) {
1583 reloadConfig();
1584 }, this);
1585
1586 ConfigOption* rewindSave = m_config->addOption("rewindSave");
1587 rewindBufferCapacity->connect([this](const QVariant& value) {
1588 reloadConfig();
1589 }, this);
1590
1591 ConfigOption* allowOpposingDirections = m_config->addOption("allowOpposingDirections");
1592 allowOpposingDirections->connect([this](const QVariant& value) {
1593 reloadConfig();
1594 }, this);
1595
1596 ConfigOption* saveStateExtdata = m_config->addOption("saveStateExtdata");
1597 saveStateExtdata->connect([this](const QVariant& value) {
1598 reloadConfig();
1599 }, this);
1600
1601 ConfigOption* loadStateExtdata = m_config->addOption("loadStateExtdata");
1602 loadStateExtdata->connect([this](const QVariant& value) {
1603 reloadConfig();
1604 }, this);
1605
1606 ConfigOption* preload = m_config->addOption("preload");
1607 preload->connect([this](const QVariant& value) {
1608 m_manager->setPreload(value.toBool());
1609 }, this);
1610 m_config->updateOption("preload");
1611
1612 ConfigOption* showFps = m_config->addOption("showFps");
1613 showFps->connect([this](const QVariant& value) {
1614 if (!value.toInt()) {
1615 m_fpsTimer.stop();
1616 updateTitle();
1617 } else if (m_controller) {
1618 m_fpsTimer.start();
1619 }
1620 }, this);
1621
1622 QAction* exitFullScreen = new QAction(tr("Exit fullscreen"), frameMenu);
1623 connect(exitFullScreen, &QAction::triggered, this, &Window::exitFullScreen);
1624 exitFullScreen->setShortcut(QKeySequence("Esc"));
1625 addHiddenAction(frameMenu, exitFullScreen, "exitFullScreen");
1626
1627 m_shortcutController->addFunctions(toolsMenu, [this]() {
1628 if (m_controller) {
1629 mCheatPressButton(m_controller->cheatDevice(), true);
1630 }
1631 }, [this]() {
1632 if (m_controller) {
1633 mCheatPressButton(m_controller->cheatDevice(), false);
1634 }
1635 }, QKeySequence(Qt::Key_Apostrophe), tr("GameShark Button (held)"), "holdGSButton");
1636
1637 QMenu* autofireMenu = new QMenu(tr("Autofire"), this);
1638 m_shortcutController->addMenu(autofireMenu);
1639
1640 m_shortcutController->addFunctions(autofireMenu, [this]() {
1641 m_controller->setAutofire(GBA_KEY_A, true);
1642 }, [this]() {
1643 m_controller->setAutofire(GBA_KEY_A, false);
1644 }, QKeySequence(), tr("Autofire A"), "autofireA");
1645
1646 m_shortcutController->addFunctions(autofireMenu, [this]() {
1647 m_controller->setAutofire(GBA_KEY_B, true);
1648 }, [this]() {
1649 m_controller->setAutofire(GBA_KEY_B, false);
1650 }, QKeySequence(), tr("Autofire B"), "autofireB");
1651
1652 m_shortcutController->addFunctions(autofireMenu, [this]() {
1653 m_controller->setAutofire(GBA_KEY_L, true);
1654 }, [this]() {
1655 m_controller->setAutofire(GBA_KEY_L, false);
1656 }, QKeySequence(), tr("Autofire L"), "autofireL");
1657
1658 m_shortcutController->addFunctions(autofireMenu, [this]() {
1659 m_controller->setAutofire(GBA_KEY_R, true);
1660 }, [this]() {
1661 m_controller->setAutofire(GBA_KEY_R, false);
1662 }, QKeySequence(), tr("Autofire R"), "autofireR");
1663
1664 m_shortcutController->addFunctions(autofireMenu, [this]() {
1665 m_controller->setAutofire(GBA_KEY_START, true);
1666 }, [this]() {
1667 m_controller->setAutofire(GBA_KEY_START, false);
1668 }, QKeySequence(), tr("Autofire Start"), "autofireStart");
1669
1670 m_shortcutController->addFunctions(autofireMenu, [this]() {
1671 m_controller->setAutofire(GBA_KEY_SELECT, true);
1672 }, [this]() {
1673 m_controller->setAutofire(GBA_KEY_SELECT, false);
1674 }, QKeySequence(), tr("Autofire Select"), "autofireSelect");
1675
1676 m_shortcutController->addFunctions(autofireMenu, [this]() {
1677 m_controller->setAutofire(GBA_KEY_UP, true);
1678 }, [this]() {
1679 m_controller->setAutofire(GBA_KEY_UP, false);
1680 }, QKeySequence(), tr("Autofire Up"), "autofireUp");
1681
1682 m_shortcutController->addFunctions(autofireMenu, [this]() {
1683 m_controller->setAutofire(GBA_KEY_RIGHT, true);
1684 }, [this]() {
1685 m_controller->setAutofire(GBA_KEY_RIGHT, false);
1686 }, QKeySequence(), tr("Autofire Right"), "autofireRight");
1687
1688 m_shortcutController->addFunctions(autofireMenu, [this]() {
1689 m_controller->setAutofire(GBA_KEY_DOWN, true);
1690 }, [this]() {
1691 m_controller->setAutofire(GBA_KEY_DOWN, false);
1692 }, QKeySequence(), tr("Autofire Down"), "autofireDown");
1693
1694 m_shortcutController->addFunctions(autofireMenu, [this]() {
1695 m_controller->setAutofire(GBA_KEY_LEFT, true);
1696 }, [this]() {
1697 m_controller->setAutofire(GBA_KEY_LEFT, false);
1698 }, QKeySequence(), tr("Autofire Left"), "autofireLeft");
1699
1700 for (QAction* action : m_gameActions) {
1701 action->setDisabled(true);
1702 }
1703}
1704
1705void Window::attachWidget(QWidget* widget) {
1706 m_screenWidget->layout()->addWidget(widget);
1707 m_screenWidget->unsetCursor();
1708 static_cast<QStackedLayout*>(m_screenWidget->layout())->setCurrentWidget(widget);
1709}
1710
1711void Window::detachWidget(QWidget* widget) {
1712 m_screenWidget->layout()->removeWidget(widget);
1713}
1714
1715void Window::appendMRU(const QString& fname) {
1716 int index = m_mruFiles.indexOf(fname);
1717 if (index >= 0) {
1718 m_mruFiles.removeAt(index);
1719 }
1720 m_mruFiles.prepend(fname);
1721 while (m_mruFiles.size() > ConfigController::MRU_LIST_SIZE) {
1722 m_mruFiles.removeLast();
1723 }
1724 updateMRU();
1725}
1726
1727void Window::updateMRU() {
1728 if (!m_mruMenu) {
1729 return;
1730 }
1731 for (QAction* action : m_mruMenu->actions()) {
1732 delete action;
1733 }
1734 m_mruMenu->clear();
1735 int i = 0;
1736 for (const QString& file : m_mruFiles) {
1737 QAction* item = new QAction(QDir::toNativeSeparators(file).replace("&", "&&"), m_mruMenu);
1738 item->setShortcut(QString("Ctrl+%1").arg(i));
1739 connect(item, &QAction::triggered, [this, file]() {
1740 setController(m_manager->loadGame(file), file);
1741 });
1742 m_mruMenu->addAction(item);
1743 ++i;
1744 }
1745 m_config->setMRU(m_mruFiles);
1746 m_config->write();
1747 m_mruMenu->setEnabled(i > 0);
1748}
1749
1750QAction* Window::addControlledAction(QMenu* menu, QAction* action, const QString& name) {
1751 addHiddenAction(menu, action, name);
1752 menu->addAction(action);
1753 return action;
1754}
1755
1756QAction* Window::addHiddenAction(QMenu* menu, QAction* action, const QString& name) {
1757 m_shortcutController->addAction(menu, action, name);
1758 action->setShortcutContext(Qt::WidgetShortcut);
1759 addAction(action);
1760 return action;
1761}
1762
1763void Window::focusCheck() {
1764 if (!m_config->getOption("pauseOnFocusLost").toInt() || !m_controller) {
1765 return;
1766 }
1767 if (QGuiApplication::focusWindow() && m_autoresume) {
1768 m_controller->setPaused(false);
1769 m_autoresume = false;
1770 } else if (!QGuiApplication::focusWindow() && !m_controller->isPaused()) {
1771 m_autoresume = true;
1772 m_controller->setPaused(true);
1773 }
1774}
1775
1776void Window::updateFrame() {
1777 QSize size = m_controller->screenDimensions();
1778 QImage currentImage(reinterpret_cast<const uchar*>(m_controller->drawContext()), size.width(), size.height(),
1779 size.width() * BYTES_PER_PIXEL, QImage::Format_RGBX8888);
1780 QPixmap pixmap;
1781 pixmap.convertFromImage(currentImage);
1782 m_screenWidget->setPixmap(pixmap);
1783 emit paused(true);
1784}
1785
1786void Window::setController(CoreController* controller, const QString& fname) {
1787 if (!controller) {
1788 return;
1789 }
1790 if (!fname.isEmpty()) {
1791 setWindowFilePath(fname);
1792 appendMRU(fname);
1793 }
1794
1795 if (m_controller) {
1796 m_controller->disconnect(this);
1797 m_controller->stop();
1798 m_controller.reset();
1799 }
1800
1801 m_controller = std::shared_ptr<CoreController>(controller);
1802 m_inputController.recalibrateAxes();
1803 m_controller->setInputController(&m_inputController);
1804 m_controller->setLogger(&m_log);
1805
1806 connect(this, &Window::shutdown, [this]() {
1807 if (!m_controller) {
1808 return;
1809 }
1810 m_controller->stop();
1811 });
1812
1813 connect(m_controller.get(), &CoreController::started, this, &Window::gameStarted);
1814 connect(m_controller.get(), &CoreController::started, &m_inputController, &InputController::suspendScreensaver);
1815 connect(m_controller.get(), &CoreController::stopping, this, &Window::gameStopped);
1816 {
1817 connect(m_controller.get(), &CoreController::stopping, [this]() {
1818 m_controller.reset();
1819 });
1820 }
1821 connect(m_controller.get(), &CoreController::stopping, &m_inputController, &InputController::resumeScreensaver);
1822 connect(m_controller.get(), &CoreController::paused, this, &Window::updateFrame);
1823
1824#ifndef Q_OS_MAC
1825 connect(m_controller.get(), &CoreController::paused, menuBar(), &QWidget::show);
1826 connect(m_controller.get(), &CoreController::unpaused, [this]() {
1827 if(isFullScreen()) {
1828 menuBar()->hide();
1829 }
1830 });
1831#endif
1832
1833 connect(m_controller.get(), &CoreController::paused, &m_inputController, &InputController::resumeScreensaver);
1834 connect(m_controller.get(), &CoreController::unpaused, [this]() {
1835 emit paused(false);
1836 });
1837
1838 connect(m_controller.get(), &CoreController::stopping, m_display.get(), &Display::stopDrawing);
1839 connect(m_controller.get(), &CoreController::stateLoaded, m_display.get(), &Display::forceDraw);
1840 connect(m_controller.get(), &CoreController::rewound, m_display.get(), &Display::forceDraw);
1841 connect(m_controller.get(), &CoreController::paused, m_display.get(), &Display::pauseDrawing);
1842 connect(m_controller.get(), &CoreController::unpaused, m_display.get(), &Display::unpauseDrawing);
1843 connect(m_controller.get(), &CoreController::frameAvailable, m_display.get(), &Display::framePosted);
1844 connect(m_controller.get(), &CoreController::statusPosted, m_display.get(), &Display::showMessage);
1845
1846 connect(m_controller.get(), &CoreController::unpaused, &m_inputController, &InputController::suspendScreensaver);
1847 connect(m_controller.get(), &CoreController::frameAvailable, this, &Window::recordFrame);
1848 connect(m_controller.get(), &CoreController::crashed, this, &Window::gameCrashed);
1849 connect(m_controller.get(), &CoreController::failed, this, &Window::gameFailed);
1850 connect(m_controller.get(), &CoreController::unimplementedBiosCall, this, &Window::unimplementedBiosCall);
1851
1852#ifdef USE_GDB_STUB
1853 if (m_gdbController) {
1854 m_gdbController->setController(m_controller);
1855 }
1856#endif
1857
1858#ifdef USE_DEBUGGERS
1859 if (m_console) {
1860 m_console->setController(m_controller);
1861 }
1862#endif
1863
1864#ifdef USE_MAGICK
1865 if (m_gifView) {
1866 m_gifView->setController(m_controller);
1867 }
1868#endif
1869
1870#ifdef USE_FFMPEG
1871 if (m_videoView) {
1872 m_videoView->setController(m_controller);
1873 }
1874#endif
1875
1876 if (m_sensorView) {
1877 m_sensorView->setController(m_controller);
1878 }
1879
1880 if (m_overrideView) {
1881 m_overrideView->setController(m_controller);
1882 }
1883
1884 if (!m_pendingPatch.isEmpty()) {
1885 m_controller->loadPatch(m_pendingPatch);
1886 m_pendingPatch = QString();
1887 }
1888
1889 m_controller->loadConfig(m_config);
1890 m_controller->start();
1891}
1892
1893WindowBackground::WindowBackground(QWidget* parent)
1894 : QWidget(parent)
1895{
1896 setLayout(new QStackedLayout());
1897 layout()->setContentsMargins(0, 0, 0, 0);
1898}
1899
1900void WindowBackground::setPixmap(const QPixmap& pmap) {
1901 m_pixmap = pmap;
1902 update();
1903}
1904
1905void WindowBackground::setSizeHint(const QSize& hint) {
1906 m_sizeHint = hint;
1907}
1908
1909QSize WindowBackground::sizeHint() const {
1910 return m_sizeHint;
1911}
1912
1913void WindowBackground::setDimensions(int width, int height) {
1914 m_aspectWidth = width;
1915 m_aspectHeight = height;
1916}
1917
1918void WindowBackground::setLockIntegerScaling(bool lock) {
1919 m_lockIntegerScaling = lock;
1920}
1921
1922void WindowBackground::setLockAspectRatio(bool lock) {
1923 m_lockAspectRatio = lock;
1924}
1925
1926void WindowBackground::paintEvent(QPaintEvent* event) {
1927 QWidget::paintEvent(event);
1928 const QPixmap& logo = pixmap();
1929 QPainter painter(this);
1930 painter.setRenderHint(QPainter::SmoothPixmapTransform);
1931 painter.fillRect(QRect(QPoint(), size()), Qt::black);
1932 QSize s = size();
1933 QSize ds = s;
1934 if (m_lockAspectRatio) {
1935 if (ds.width() * m_aspectHeight > ds.height() * m_aspectWidth) {
1936 ds.setWidth(ds.height() * m_aspectWidth / m_aspectHeight);
1937 } else if (ds.width() * m_aspectHeight < ds.height() * m_aspectWidth) {
1938 ds.setHeight(ds.width() * m_aspectHeight / m_aspectWidth);
1939 }
1940 }
1941 if (m_lockIntegerScaling) {
1942 ds.setWidth(ds.width() - ds.width() % m_aspectWidth);
1943 ds.setHeight(ds.height() - ds.height() % m_aspectHeight);
1944 }
1945 QPoint origin = QPoint((s.width() - ds.width()) / 2, (s.height() - ds.height()) / 2);
1946 QRect full(origin, ds);
1947 painter.drawPixmap(full, logo);
1948}