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