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