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