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