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