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