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