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