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