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