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