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 addControlledAction(fileMenu, loadState, "loadState");
840
841 QAction* saveState = new QAction(tr("&Save state"), fileMenu);
842 saveState->setShortcut(tr("Shift+F10"));
843 connect(saveState, &QAction::triggered, [this]() { this->openStateWindow(LoadSave::SAVE); });
844 m_gameActions.append(saveState);
845 m_nonMpActions.append(saveState);
846 addControlledAction(fileMenu, saveState, "saveState");
847
848 QMenu* quickLoadMenu = fileMenu->addMenu(tr("Quick load"));
849 QMenu* quickSaveMenu = fileMenu->addMenu(tr("Quick save"));
850 m_shortcutController->addMenu(quickLoadMenu);
851 m_shortcutController->addMenu(quickSaveMenu);
852
853 QAction* quickLoad = new QAction(tr("Load recent"), quickLoadMenu);
854 connect(quickLoad, SIGNAL(triggered()), m_controller, SLOT(loadState()));
855 m_gameActions.append(quickLoad);
856 m_nonMpActions.append(quickLoad);
857 addControlledAction(quickLoadMenu, quickLoad, "quickLoad");
858
859 QAction* quickSave = new QAction(tr("Save recent"), quickSaveMenu);
860 connect(quickSave, SIGNAL(triggered()), m_controller, SLOT(saveState()));
861 m_gameActions.append(quickSave);
862 m_nonMpActions.append(quickSave);
863 addControlledAction(quickSaveMenu, quickSave, "quickSave");
864
865 quickLoadMenu->addSeparator();
866 quickSaveMenu->addSeparator();
867
868 QAction* undoLoadState = new QAction(tr("Undo load state"), quickLoadMenu);
869 undoLoadState->setShortcut(tr("F11"));
870 connect(undoLoadState, SIGNAL(triggered()), m_controller, SLOT(loadBackupState()));
871 m_gameActions.append(undoLoadState);
872 m_nonMpActions.append(undoLoadState);
873 addControlledAction(quickLoadMenu, undoLoadState, "undoLoadState");
874
875 QAction* undoSaveState = new QAction(tr("Undo save state"), quickSaveMenu);
876 undoSaveState->setShortcut(tr("Shift+F11"));
877 connect(undoSaveState, SIGNAL(triggered()), m_controller, SLOT(saveBackupState()));
878 m_gameActions.append(undoSaveState);
879 m_nonMpActions.append(undoSaveState);
880 addControlledAction(quickSaveMenu, undoSaveState, "undoSaveState");
881
882 quickLoadMenu->addSeparator();
883 quickSaveMenu->addSeparator();
884
885 int i;
886 for (i = 1; i < 10; ++i) {
887 quickLoad = new QAction(tr("State &%1").arg(i), quickLoadMenu);
888 quickLoad->setShortcut(tr("F%1").arg(i));
889 connect(quickLoad, &QAction::triggered, [this, i]() { m_controller->loadState(i); });
890 m_gameActions.append(quickLoad);
891 m_nonMpActions.append(quickLoad);
892 addControlledAction(quickLoadMenu, quickLoad, QString("quickLoad.%1").arg(i));
893
894 quickSave = new QAction(tr("State &%1").arg(i), quickSaveMenu);
895 quickSave->setShortcut(tr("Shift+F%1").arg(i));
896 connect(quickSave, &QAction::triggered, [this, i]() { m_controller->saveState(i); });
897 m_gameActions.append(quickSave);
898 m_nonMpActions.append(quickSave);
899 addControlledAction(quickSaveMenu, quickSave, QString("quickSave.%1").arg(i));
900 }
901
902 fileMenu->addSeparator();
903 QAction* importShark = new QAction(tr("Import GameShark Save"), fileMenu);
904 connect(importShark, SIGNAL(triggered()), this, SLOT(importSharkport()));
905 m_gameActions.append(importShark);
906 m_gbaActions.append(importShark);
907 addControlledAction(fileMenu, importShark, "importShark");
908
909 QAction* exportShark = new QAction(tr("Export GameShark Save"), fileMenu);
910 connect(exportShark, SIGNAL(triggered()), this, SLOT(exportSharkport()));
911 m_gameActions.append(exportShark);
912 m_gbaActions.append(exportShark);
913 addControlledAction(fileMenu, exportShark, "exportShark");
914
915 fileMenu->addSeparator();
916 QAction* multiWindow = new QAction(tr("New multiplayer window"), fileMenu);
917 connect(multiWindow, &QAction::triggered, [this]() {
918 GBAApp::app()->newWindow();
919 });
920 addControlledAction(fileMenu, multiWindow, "multiWindow");
921
922#ifndef Q_OS_MAC
923 fileMenu->addSeparator();
924#endif
925
926 QAction* about = new QAction(tr("About"), fileMenu);
927 connect(about, SIGNAL(triggered()), this, SLOT(openAboutScreen()));
928 fileMenu->addAction(about);
929
930#ifndef Q_OS_MAC
931 addControlledAction(fileMenu, fileMenu->addAction(tr("E&xit"), this, SLOT(close()), QKeySequence::Quit), "quit");
932#endif
933
934 QMenu* emulationMenu = menubar->addMenu(tr("&Emulation"));
935 m_shortcutController->addMenu(emulationMenu);
936 QAction* reset = new QAction(tr("&Reset"), emulationMenu);
937 reset->setShortcut(tr("Ctrl+R"));
938 connect(reset, SIGNAL(triggered()), m_controller, SLOT(reset()));
939 m_gameActions.append(reset);
940 addControlledAction(emulationMenu, reset, "reset");
941
942 QAction* shutdown = new QAction(tr("Sh&utdown"), emulationMenu);
943 connect(shutdown, SIGNAL(triggered()), m_controller, SLOT(closeGame()));
944 m_gameActions.append(shutdown);
945 addControlledAction(emulationMenu, shutdown, "shutdown");
946
947 QAction* yank = new QAction(tr("Yank game pak"), emulationMenu);
948 connect(yank, SIGNAL(triggered()), m_controller, SLOT(yankPak()));
949 m_gameActions.append(yank);
950 m_gbaActions.append(yank);
951 addControlledAction(emulationMenu, yank, "yank");
952 emulationMenu->addSeparator();
953
954 QAction* pause = new QAction(tr("&Pause"), emulationMenu);
955 pause->setChecked(false);
956 pause->setCheckable(true);
957 pause->setShortcut(tr("Ctrl+P"));
958 connect(pause, SIGNAL(triggered(bool)), m_controller, SLOT(setPaused(bool)));
959 connect(m_controller, &GameController::gamePaused, [this, pause]() {
960 pause->setChecked(true);
961 });
962 connect(m_controller, &GameController::gameUnpaused, [pause]() { pause->setChecked(false); });
963 m_gameActions.append(pause);
964 addControlledAction(emulationMenu, pause, "pause");
965
966 QAction* frameAdvance = new QAction(tr("&Next frame"), emulationMenu);
967 frameAdvance->setShortcut(tr("Ctrl+N"));
968 connect(frameAdvance, SIGNAL(triggered()), m_controller, SLOT(frameAdvance()));
969 m_gameActions.append(frameAdvance);
970 m_nonMpActions.append(frameAdvance);
971 addControlledAction(emulationMenu, frameAdvance, "frameAdvance");
972
973 emulationMenu->addSeparator();
974
975 m_shortcutController->addFunctions(emulationMenu, [this]() {
976 m_controller->setTurbo(true, false);
977 }, [this]() {
978 m_controller->setTurbo(false, false);
979 }, QKeySequence(Qt::Key_Tab), tr("Fast forward (held)"), "holdFastForward");
980
981 QAction* turbo = new QAction(tr("&Fast forward"), emulationMenu);
982 turbo->setCheckable(true);
983 turbo->setChecked(false);
984 turbo->setShortcut(tr("Shift+Tab"));
985 connect(turbo, SIGNAL(triggered(bool)), m_controller, SLOT(setTurbo(bool)));
986 addControlledAction(emulationMenu, turbo, "fastForward");
987
988 QMenu* ffspeedMenu = emulationMenu->addMenu(tr("Fast forward speed"));
989 ConfigOption* ffspeed = m_config->addOption("fastForwardRatio");
990 ffspeed->connect([this](const QVariant& value) {
991 m_controller->setTurboSpeed(value.toFloat());
992 }, this);
993 ffspeed->addValue(tr("Unbounded"), -1.0f, ffspeedMenu);
994 ffspeed->setValue(QVariant(-1.0f));
995 ffspeedMenu->addSeparator();
996 for (i = 2; i < 11; ++i) {
997 ffspeed->addValue(tr("%0x").arg(i), i, ffspeedMenu);
998 }
999 m_config->updateOption("fastForwardRatio");
1000
1001 m_shortcutController->addFunctions(emulationMenu, [this]() {
1002 m_controller->startRewinding();
1003 }, [this]() {
1004 m_controller->stopRewinding();
1005 }, QKeySequence("~"), tr("Rewind (held)"), "holdRewind");
1006
1007 QAction* rewind = new QAction(tr("Re&wind"), emulationMenu);
1008 rewind->setShortcut(tr("`"));
1009 connect(rewind, SIGNAL(triggered()), m_controller, SLOT(rewind()));
1010 m_gameActions.append(rewind);
1011 m_nonMpActions.append(rewind);
1012 addControlledAction(emulationMenu, rewind, "rewind");
1013
1014 QAction* frameRewind = new QAction(tr("Step backwards"), emulationMenu);
1015 frameRewind->setShortcut(tr("Ctrl+B"));
1016 connect(frameRewind, &QAction::triggered, [this] () {
1017 m_controller->rewind(1);
1018 });
1019 m_gameActions.append(frameRewind);
1020 m_nonMpActions.append(frameRewind);
1021 addControlledAction(emulationMenu, frameRewind, "frameRewind");
1022
1023 ConfigOption* videoSync = m_config->addOption("videoSync");
1024 videoSync->addBoolean(tr("Sync to &video"), emulationMenu);
1025 videoSync->connect([this](const QVariant& value) {
1026 reloadConfig();
1027 }, this);
1028 m_config->updateOption("videoSync");
1029
1030 ConfigOption* audioSync = m_config->addOption("audioSync");
1031 audioSync->addBoolean(tr("Sync to &audio"), emulationMenu);
1032 audioSync->connect([this](const QVariant& value) {
1033 reloadConfig();
1034 }, this);
1035 m_config->updateOption("audioSync");
1036
1037 emulationMenu->addSeparator();
1038
1039 QMenu* solarMenu = emulationMenu->addMenu(tr("Solar sensor"));
1040 m_shortcutController->addMenu(solarMenu);
1041 QAction* solarIncrease = new QAction(tr("Increase solar level"), solarMenu);
1042 connect(solarIncrease, SIGNAL(triggered()), m_controller, SLOT(increaseLuminanceLevel()));
1043 addControlledAction(solarMenu, solarIncrease, "increaseLuminanceLevel");
1044
1045 QAction* solarDecrease = new QAction(tr("Decrease solar level"), solarMenu);
1046 connect(solarDecrease, SIGNAL(triggered()), m_controller, SLOT(decreaseLuminanceLevel()));
1047 addControlledAction(solarMenu, solarDecrease, "decreaseLuminanceLevel");
1048
1049 QAction* maxSolar = new QAction(tr("Brightest solar level"), solarMenu);
1050 connect(maxSolar, &QAction::triggered, [this]() { m_controller->setLuminanceLevel(10); });
1051 addControlledAction(solarMenu, maxSolar, "maxLuminanceLevel");
1052
1053 QAction* minSolar = new QAction(tr("Darkest solar level"), solarMenu);
1054 connect(minSolar, &QAction::triggered, [this]() { m_controller->setLuminanceLevel(0); });
1055 addControlledAction(solarMenu, minSolar, "minLuminanceLevel");
1056
1057 solarMenu->addSeparator();
1058 for (int i = 0; i <= 10; ++i) {
1059 QAction* setSolar = new QAction(tr("Brightness %1").arg(QString::number(i)), solarMenu);
1060 connect(setSolar, &QAction::triggered, [this, i]() {
1061 m_controller->setLuminanceLevel(i);
1062 });
1063 addControlledAction(solarMenu, setSolar, QString("luminanceLevel.%1").arg(QString::number(i)));
1064 }
1065
1066 QMenu* avMenu = menubar->addMenu(tr("Audio/&Video"));
1067 m_shortcutController->addMenu(avMenu);
1068 QMenu* frameMenu = avMenu->addMenu(tr("Frame size"));
1069 m_shortcutController->addMenu(frameMenu, avMenu);
1070 for (int i = 1; i <= 6; ++i) {
1071 QAction* setSize = new QAction(tr("%1x").arg(QString::number(i)), avMenu);
1072 setSize->setCheckable(true);
1073 connect(setSize, &QAction::triggered, [this, i, setSize]() {
1074 showNormal();
1075 QSize size(VIDEO_HORIZONTAL_PIXELS, VIDEO_VERTICAL_PIXELS);
1076 if (m_controller->isLoaded()) {
1077 size = m_controller->screenDimensions();
1078 }
1079 size *= i;
1080 resizeFrame(size);
1081 bool enableSignals = setSize->blockSignals(true);
1082 setSize->setChecked(true);
1083 setSize->blockSignals(enableSignals);
1084 });
1085 m_frameSizes[i] = setSize;
1086 addControlledAction(frameMenu, setSize, QString("frame%1x").arg(QString::number(i)));
1087 }
1088 QKeySequence fullscreenKeys;
1089#ifdef Q_OS_WIN
1090 fullscreenKeys = QKeySequence("Alt+Return");
1091#else
1092 fullscreenKeys = QKeySequence("Ctrl+F");
1093#endif
1094 addControlledAction(frameMenu, frameMenu->addAction(tr("Toggle fullscreen"), this, SLOT(toggleFullScreen()), fullscreenKeys), "fullscreen");
1095
1096 ConfigOption* lockAspectRatio = m_config->addOption("lockAspectRatio");
1097 lockAspectRatio->addBoolean(tr("Lock aspect ratio"), avMenu);
1098 lockAspectRatio->connect([this](const QVariant& value) {
1099 m_display->lockAspectRatio(value.toBool());
1100 }, this);
1101 m_config->updateOption("lockAspectRatio");
1102
1103 ConfigOption* resampleVideo = m_config->addOption("resampleVideo");
1104 resampleVideo->addBoolean(tr("Resample video"), avMenu);
1105 resampleVideo->connect([this](const QVariant& value) {
1106 m_display->filter(value.toBool());
1107 }, this);
1108 m_config->updateOption("resampleVideo");
1109
1110 QMenu* skipMenu = avMenu->addMenu(tr("Frame&skip"));
1111 ConfigOption* skip = m_config->addOption("frameskip");
1112 skip->connect([this](const QVariant& value) {
1113 reloadConfig();
1114 }, this);
1115 for (int i = 0; i <= 10; ++i) {
1116 skip->addValue(QString::number(i), i, skipMenu);
1117 }
1118 m_config->updateOption("frameskip");
1119
1120 QAction* shaderView = new QAction(tr("Shader options..."), avMenu);
1121 connect(shaderView, SIGNAL(triggered()), m_shaderView, SLOT(show()));
1122 if (!m_display->supportsShaders()) {
1123 shaderView->setEnabled(false);
1124 }
1125 addControlledAction(avMenu, shaderView, "shaderSelector");
1126
1127 avMenu->addSeparator();
1128
1129 ConfigOption* mute = m_config->addOption("mute");
1130 mute->addBoolean(tr("Mute"), avMenu);
1131 mute->connect([this](const QVariant& value) {
1132 reloadConfig();
1133 }, this);
1134 m_config->updateOption("mute");
1135
1136 QMenu* target = avMenu->addMenu(tr("FPS target"));
1137 ConfigOption* fpsTargetOption = m_config->addOption("fpsTarget");
1138 fpsTargetOption->connect([this](const QVariant& value) {
1139 emit fpsTargetChanged(value.toFloat());
1140 }, this);
1141 fpsTargetOption->addValue(tr("15"), 15, target);
1142 fpsTargetOption->addValue(tr("30"), 30, target);
1143 fpsTargetOption->addValue(tr("45"), 45, target);
1144 fpsTargetOption->addValue(tr("Native (59.7)"), float(GBA_ARM7TDMI_FREQUENCY) / float(VIDEO_TOTAL_LENGTH), target);
1145 fpsTargetOption->addValue(tr("60"), 60, target);
1146 fpsTargetOption->addValue(tr("90"), 90, target);
1147 fpsTargetOption->addValue(tr("120"), 120, target);
1148 fpsTargetOption->addValue(tr("240"), 240, target);
1149 m_config->updateOption("fpsTarget");
1150
1151#if defined(USE_PNG) || defined(USE_FFMPEG) || defined(USE_MAGICK)
1152 avMenu->addSeparator();
1153#endif
1154
1155#ifdef USE_PNG
1156 QAction* screenshot = new QAction(tr("Take &screenshot"), avMenu);
1157 screenshot->setShortcut(tr("F12"));
1158 connect(screenshot, SIGNAL(triggered()), m_controller, SLOT(screenshot()));
1159 m_gameActions.append(screenshot);
1160 addControlledAction(avMenu, screenshot, "screenshot");
1161#endif
1162
1163#ifdef USE_FFMPEG
1164 QAction* recordOutput = new QAction(tr("Record output..."), avMenu);
1165 connect(recordOutput, SIGNAL(triggered()), this, SLOT(openVideoWindow()));
1166 addControlledAction(avMenu, recordOutput, "recordOutput");
1167#endif
1168
1169#ifdef USE_MAGICK
1170 QAction* recordGIF = new QAction(tr("Record GIF..."), avMenu);
1171 connect(recordGIF, SIGNAL(triggered()), this, SLOT(openGIFWindow()));
1172 addControlledAction(avMenu, recordGIF, "recordGIF");
1173#endif
1174
1175 avMenu->addSeparator();
1176 QMenu* videoLayers = avMenu->addMenu(tr("Video layers"));
1177
1178 for (int i = 0; i < 4; ++i) {
1179 QAction* enableBg = new QAction(tr("Background %0").arg(i), videoLayers);
1180 enableBg->setCheckable(true);
1181 enableBg->setChecked(true);
1182 connect(enableBg, &QAction::triggered, [this, i](bool enable) { m_controller->setVideoLayerEnabled(i, enable); });
1183 addControlledAction(videoLayers, enableBg, QString("enableBG%0").arg(i));
1184 }
1185
1186 QAction* enableObj = new QAction(tr("OBJ (sprites)"), videoLayers);
1187 enableObj->setCheckable(true);
1188 enableObj->setChecked(true);
1189 connect(enableObj, &QAction::triggered, [this](bool enable) { m_controller->setVideoLayerEnabled(4, enable); });
1190 addControlledAction(videoLayers, enableObj, "enableOBJ");
1191
1192 QMenu* audioChannels = avMenu->addMenu(tr("Audio channels"));
1193
1194 for (int i = 0; i < 4; ++i) {
1195 QAction* enableCh = new QAction(tr("Channel %0").arg(i + 1), audioChannels);
1196 enableCh->setCheckable(true);
1197 enableCh->setChecked(true);
1198 connect(enableCh, &QAction::triggered, [this, i](bool enable) { m_controller->setAudioChannelEnabled(i, enable); });
1199 addControlledAction(audioChannels, enableCh, QString("enableCh%0").arg(i + 1));
1200 }
1201
1202 QAction* enableChA = new QAction(tr("Channel A"), audioChannels);
1203 enableChA->setCheckable(true);
1204 enableChA->setChecked(true);
1205 connect(enableChA, &QAction::triggered, [this, i](bool enable) { m_controller->setAudioChannelEnabled(4, enable); });
1206 addControlledAction(audioChannels, enableChA, QString("enableChA"));
1207
1208 QAction* enableChB = new QAction(tr("Channel B"), audioChannels);
1209 enableChB->setCheckable(true);
1210 enableChB->setChecked(true);
1211 connect(enableChB, &QAction::triggered, [this, i](bool enable) { m_controller->setAudioChannelEnabled(5, enable); });
1212 addControlledAction(audioChannels, enableChB, QString("enableChB"));
1213
1214 QMenu* toolsMenu = menubar->addMenu(tr("&Tools"));
1215 m_shortcutController->addMenu(toolsMenu);
1216 QAction* viewLogs = new QAction(tr("View &logs..."), toolsMenu);
1217 connect(viewLogs, SIGNAL(triggered()), m_logView, SLOT(show()));
1218 addControlledAction(toolsMenu, viewLogs, "viewLogs");
1219
1220 QAction* overrides = new QAction(tr("Game &overrides..."), toolsMenu);
1221 connect(overrides, SIGNAL(triggered()), this, SLOT(openOverrideWindow()));
1222 m_gbaActions.append(overrides);
1223 addControlledAction(toolsMenu, overrides, "overrideWindow");
1224
1225 QAction* sensors = new QAction(tr("Game &Pak sensors..."), toolsMenu);
1226 connect(sensors, SIGNAL(triggered()), this, SLOT(openSensorWindow()));
1227 addControlledAction(toolsMenu, sensors, "sensorWindow");
1228
1229 QAction* cheats = new QAction(tr("&Cheats..."), toolsMenu);
1230 connect(cheats, SIGNAL(triggered()), this, SLOT(openCheatsWindow()));
1231 m_gameActions.append(cheats);
1232 addControlledAction(toolsMenu, cheats, "cheatsWindow");
1233
1234#ifdef USE_GDB_STUB
1235 QAction* gdbWindow = new QAction(tr("Start &GDB server..."), toolsMenu);
1236 connect(gdbWindow, SIGNAL(triggered()), this, SLOT(gdbOpen()));
1237 m_gbaActions.append(gdbWindow);
1238 addControlledAction(toolsMenu, gdbWindow, "gdbWindow");
1239#endif
1240
1241 toolsMenu->addSeparator();
1242 addControlledAction(toolsMenu, toolsMenu->addAction(tr("Settings..."), this, SLOT(openSettingsWindow())),
1243 "settings");
1244
1245 toolsMenu->addSeparator();
1246
1247 QAction* paletteView = new QAction(tr("View &palette..."), toolsMenu);
1248 connect(paletteView, SIGNAL(triggered()), this, SLOT(openPaletteWindow()));
1249 m_gameActions.append(paletteView);
1250 m_gbaActions.append(paletteView);
1251 addControlledAction(toolsMenu, paletteView, "paletteWindow");
1252
1253 QAction* memoryView = new QAction(tr("View memory..."), toolsMenu);
1254 connect(memoryView, SIGNAL(triggered()), this, SLOT(openMemoryWindow()));
1255 m_gameActions.append(memoryView);
1256 addControlledAction(toolsMenu, memoryView, "memoryView");
1257
1258 QAction* ioViewer = new QAction(tr("View &I/O registers..."), toolsMenu);
1259 connect(ioViewer, SIGNAL(triggered()), this, SLOT(openIOViewer()));
1260 m_gameActions.append(ioViewer);
1261 m_gbaActions.append(ioViewer);
1262 addControlledAction(toolsMenu, ioViewer, "ioViewer");
1263
1264 ConfigOption* skipBios = m_config->addOption("skipBios");
1265 skipBios->connect([this](const QVariant& value) {
1266 reloadConfig();
1267 }, this);
1268
1269 ConfigOption* useBios = m_config->addOption("useBios");
1270 useBios->connect([this](const QVariant& value) {
1271 m_controller->setUseBIOS(value.toBool());
1272 }, this);
1273
1274 ConfigOption* buffers = m_config->addOption("audioBuffers");
1275 buffers->connect([this](const QVariant& value) {
1276 emit audioBufferSamplesChanged(value.toInt());
1277 }, this);
1278
1279 ConfigOption* sampleRate = m_config->addOption("sampleRate");
1280 sampleRate->connect([this](const QVariant& value) {
1281 emit sampleRateChanged(value.toUInt());
1282 }, this);
1283
1284 ConfigOption* volume = m_config->addOption("volume");
1285 volume->connect([this](const QVariant& value) {
1286 reloadConfig();
1287 }, this);
1288
1289 ConfigOption* rewindEnable = m_config->addOption("rewindEnable");
1290 rewindEnable->connect([this](const QVariant& value) {
1291 m_controller->setRewind(value.toBool(), m_config->getOption("rewindBufferCapacity").toInt(), m_config->getOption("rewindBufferInterval").toInt());
1292 }, this);
1293
1294 ConfigOption* rewindBufferCapacity = m_config->addOption("rewindBufferCapacity");
1295 rewindBufferCapacity->connect([this](const QVariant& value) {
1296 m_controller->setRewind(m_config->getOption("rewindEnable").toInt(), value.toInt(), m_config->getOption("rewindBufferInterval").toInt());
1297 }, this);
1298
1299 ConfigOption* rewindBufferInterval = m_config->addOption("rewindBufferInterval");
1300 rewindBufferInterval->connect([this](const QVariant& value) {
1301 m_controller->setRewind(m_config->getOption("rewindEnable").toInt(), m_config->getOption("rewindBufferCapacity").toInt(), value.toInt());
1302 }, this);
1303
1304 ConfigOption* allowOpposingDirections = m_config->addOption("allowOpposingDirections");
1305 allowOpposingDirections->connect([this](const QVariant& value) {
1306 m_inputController.setAllowOpposing(value.toBool());
1307 }, this);
1308
1309 ConfigOption* saveStateExtdata = m_config->addOption("saveStateExtdata");
1310 saveStateExtdata->connect([this](const QVariant& value) {
1311 m_controller->setSaveStateExtdata(value.toInt());
1312 }, this);
1313
1314 ConfigOption* loadStateExtdata = m_config->addOption("loadStateExtdata");
1315 loadStateExtdata->connect([this](const QVariant& value) {
1316 m_controller->setLoadStateExtdata(value.toInt());
1317 }, this);
1318
1319 QAction* exitFullScreen = new QAction(tr("Exit fullscreen"), frameMenu);
1320 connect(exitFullScreen, SIGNAL(triggered()), this, SLOT(exitFullScreen()));
1321 exitFullScreen->setShortcut(QKeySequence("Esc"));
1322 addHiddenAction(frameMenu, exitFullScreen, "exitFullScreen");
1323
1324 QMenu* autofireMenu = new QMenu(tr("Autofire"), this);
1325 m_shortcutController->addMenu(autofireMenu);
1326
1327 m_shortcutController->addFunctions(autofireMenu, [this]() {
1328 m_controller->setAutofire(GBA_KEY_A, true);
1329 }, [this]() {
1330 m_controller->setAutofire(GBA_KEY_A, false);
1331 }, QKeySequence("W"), tr("Autofire A"), "autofireA");
1332
1333 m_shortcutController->addFunctions(autofireMenu, [this]() {
1334 m_controller->setAutofire(GBA_KEY_B, true);
1335 }, [this]() {
1336 m_controller->setAutofire(GBA_KEY_B, false);
1337 }, QKeySequence("Q"), tr("Autofire B"), "autofireB");
1338
1339 m_shortcutController->addFunctions(autofireMenu, [this]() {
1340 m_controller->setAutofire(GBA_KEY_L, true);
1341 }, [this]() {
1342 m_controller->setAutofire(GBA_KEY_L, false);
1343 }, QKeySequence(), tr("Autofire L"), "autofireL");
1344
1345 m_shortcutController->addFunctions(autofireMenu, [this]() {
1346 m_controller->setAutofire(GBA_KEY_R, true);
1347 }, [this]() {
1348 m_controller->setAutofire(GBA_KEY_R, false);
1349 }, QKeySequence(), tr("Autofire R"), "autofireR");
1350
1351 m_shortcutController->addFunctions(autofireMenu, [this]() {
1352 m_controller->setAutofire(GBA_KEY_START, true);
1353 }, [this]() {
1354 m_controller->setAutofire(GBA_KEY_START, false);
1355 }, QKeySequence(), tr("Autofire Start"), "autofireStart");
1356
1357 m_shortcutController->addFunctions(autofireMenu, [this]() {
1358 m_controller->setAutofire(GBA_KEY_SELECT, true);
1359 }, [this]() {
1360 m_controller->setAutofire(GBA_KEY_SELECT, false);
1361 }, QKeySequence(), tr("Autofire Select"), "autofireSelect");
1362
1363 m_shortcutController->addFunctions(autofireMenu, [this]() {
1364 m_controller->setAutofire(GBA_KEY_UP, true);
1365 }, [this]() {
1366 m_controller->setAutofire(GBA_KEY_UP, false);
1367 }, QKeySequence(), tr("Autofire Up"), "autofireUp");
1368
1369 m_shortcutController->addFunctions(autofireMenu, [this]() {
1370 m_controller->setAutofire(GBA_KEY_RIGHT, true);
1371 }, [this]() {
1372 m_controller->setAutofire(GBA_KEY_RIGHT, false);
1373 }, QKeySequence(), tr("Autofire Right"), "autofireRight");
1374
1375 m_shortcutController->addFunctions(autofireMenu, [this]() {
1376 m_controller->setAutofire(GBA_KEY_DOWN, true);
1377 }, [this]() {
1378 m_controller->setAutofire(GBA_KEY_DOWN, false);
1379 }, QKeySequence(), tr("Autofire Down"), "autofireDown");
1380
1381 m_shortcutController->addFunctions(autofireMenu, [this]() {
1382 m_controller->setAutofire(GBA_KEY_LEFT, true);
1383 }, [this]() {
1384 m_controller->setAutofire(GBA_KEY_LEFT, false);
1385 }, QKeySequence(), tr("Autofire Left"), "autofireLeft");
1386
1387 foreach (QAction* action, m_gameActions) {
1388 action->setDisabled(true);
1389 }
1390}
1391
1392void Window::attachWidget(QWidget* widget) {
1393 m_screenWidget->layout()->addWidget(widget);
1394 m_screenWidget->unsetCursor();
1395 static_cast<QStackedLayout*>(m_screenWidget->layout())->setCurrentWidget(widget);
1396}
1397
1398void Window::detachWidget(QWidget* widget) {
1399 m_screenWidget->layout()->removeWidget(widget);
1400}
1401
1402void Window::appendMRU(const QString& fname) {
1403 int index = m_mruFiles.indexOf(fname);
1404 if (index >= 0) {
1405 m_mruFiles.removeAt(index);
1406 }
1407 m_mruFiles.prepend(fname);
1408 while (m_mruFiles.size() > ConfigController::MRU_LIST_SIZE) {
1409 m_mruFiles.removeLast();
1410 }
1411 updateMRU();
1412}
1413
1414void Window::updateMRU() {
1415 if (!m_mruMenu) {
1416 return;
1417 }
1418 m_mruMenu->clear();
1419 int i = 0;
1420 for (const QString& file : m_mruFiles) {
1421 QAction* item = new QAction(file, m_mruMenu);
1422 item->setShortcut(QString("Ctrl+%1").arg(i));
1423 connect(item, &QAction::triggered, [this, file]() { m_controller->loadGame(file); });
1424 m_mruMenu->addAction(item);
1425 ++i;
1426 }
1427 m_config->setMRU(m_mruFiles);
1428 m_config->write();
1429 m_mruMenu->setEnabled(i > 0);
1430}
1431
1432QAction* Window::addControlledAction(QMenu* menu, QAction* action, const QString& name) {
1433 addHiddenAction(menu, action, name);
1434 menu->addAction(action);
1435 return action;
1436}
1437
1438QAction* Window::addHiddenAction(QMenu* menu, QAction* action, const QString& name) {
1439 m_shortcutController->addAction(menu, action, name);
1440 action->setShortcutContext(Qt::WidgetShortcut);
1441 addAction(action);
1442 return action;
1443}
1444
1445void Window::focusCheck() {
1446 if (!m_config->getOption("pauseOnFocusLost").toInt()) {
1447 return;
1448 }
1449 if (QGuiApplication::focusWindow() && m_autoresume) {
1450 m_controller->setPaused(false);
1451 } else if (!QGuiApplication::focusWindow() && !m_controller->isPaused()) {
1452 m_autoresume = true;
1453 m_controller->setPaused(true);
1454 }
1455}
1456
1457WindowBackground::WindowBackground(QWidget* parent)
1458 : QLabel(parent)
1459{
1460 setLayout(new QStackedLayout());
1461 layout()->setContentsMargins(0, 0, 0, 0);
1462 setAlignment(Qt::AlignCenter);
1463}
1464
1465void WindowBackground::setSizeHint(const QSize& hint) {
1466 m_sizeHint = hint;
1467}
1468
1469QSize WindowBackground::sizeHint() const {
1470 return m_sizeHint;
1471}
1472
1473void WindowBackground::setLockAspectRatio(int width, int height) {
1474 m_aspectWidth = width;
1475 m_aspectHeight = height;
1476}
1477
1478void WindowBackground::paintEvent(QPaintEvent*) {
1479 const QPixmap* logo = pixmap();
1480 if (!logo) {
1481 return;
1482 }
1483 QPainter painter(this);
1484 painter.setRenderHint(QPainter::SmoothPixmapTransform);
1485 painter.fillRect(QRect(QPoint(), size()), Qt::black);
1486 QSize s = size();
1487 QSize ds = s;
1488 if (ds.width() * m_aspectHeight > ds.height() * m_aspectWidth) {
1489 ds.setWidth(ds.height() * m_aspectWidth / m_aspectHeight);
1490 } else if (ds.width() * m_aspectHeight < ds.height() * m_aspectWidth) {
1491 ds.setHeight(ds.width() * m_aspectHeight / m_aspectWidth);
1492 }
1493 QPoint origin = QPoint((s.width() - ds.width()) / 2, (s.height() - ds.height()) / 2);
1494 QRect full(origin, ds);
1495 painter.drawPixmap(full, *logo);
1496}