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