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