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