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