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