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