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