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