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