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