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