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