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