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