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