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