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