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 <QFileDialog>
9#include <QFileInfo>
10#include <QKeyEvent>
11#include <QKeySequence>
12#include <QMenuBar>
13#include <QMessageBox>
14#include <QMimeData>
15#include <QPainter>
16#include <QStackedLayout>
17
18#include "CheatsView.h"
19#include "ConfigController.h"
20#include "DisplayGL.h"
21#include "GameController.h"
22#include "GBAKeyEditor.h"
23#include "GDBController.h"
24#include "GDBWindow.h"
25#include "GIFView.h"
26#include "LoadSaveState.h"
27#include "LogView.h"
28#include "MultiplayerController.h"
29#include "OverrideView.h"
30#include "PaletteView.h"
31#include "SensorView.h"
32#include "SettingsView.h"
33#include "ShortcutController.h"
34#include "ShortcutView.h"
35#include "VideoView.h"
36
37extern "C" {
38#include "platform/commandline.h"
39}
40
41using namespace QGBA;
42
43Window::Window(ConfigController* config, int playerId, QWidget* parent)
44 : QMainWindow(parent)
45 , m_logView(new LogView())
46 , m_stateWindow(nullptr)
47 , m_screenWidget(new WindowBackground())
48 , m_logo(":/res/mgba-1024.png")
49 , m_config(config)
50 , m_inputController(playerId)
51#ifdef USE_FFMPEG
52 , m_videoView(nullptr)
53#endif
54#ifdef USE_MAGICK
55 , m_gifView(nullptr)
56#endif
57#ifdef USE_GDB_STUB
58 , m_gdbController(nullptr)
59#endif
60 , m_mruMenu(nullptr)
61 , m_shortcutController(new ShortcutController(this))
62 , m_playerId(playerId)
63{
64 setWindowTitle(PROJECT_NAME);
65 setFocusPolicy(Qt::StrongFocus);
66 setAcceptDrops(true);
67 m_controller = new GameController(this);
68 m_controller->setInputController(&m_inputController);
69 m_controller->setOverrides(m_config->overrides());
70
71 QGLFormat format(QGLFormat(QGL::Rgba | QGL::DoubleBuffer));
72 format.setSwapInterval(1);
73 m_display = new DisplayGL(format, this);
74
75 m_logo.setDevicePixelRatio(m_screenWidget->devicePixelRatio());
76 m_logo = m_logo; // Free memory left over in old pixmap
77
78 m_screenWidget->setMinimumSize(m_display->minimumSize());
79 m_screenWidget->setSizePolicy(m_display->sizePolicy());
80 m_screenWidget->setSizeHint(m_display->minimumSize() * 2);
81 m_screenWidget->setPixmap(m_logo);
82 m_screenWidget->setLockAspectRatio(m_logo.width(), m_logo.height());
83 setCentralWidget(m_screenWidget);
84
85 QVariant windowPos = m_config->getQtOption("windowPos");
86 if (!windowPos.isNull()) {
87 move(windowPos.toPoint());
88 }
89
90 connect(m_controller, SIGNAL(gameStarted(GBAThread*)), this, SLOT(gameStarted(GBAThread*)));
91 connect(m_controller, SIGNAL(gameStopped(GBAThread*)), m_display, SLOT(stopDrawing()));
92 connect(m_controller, SIGNAL(gameStopped(GBAThread*)), this, SLOT(gameStopped()));
93 connect(m_controller, SIGNAL(stateLoaded(GBAThread*)), m_display, SLOT(forceDraw()));
94 connect(m_controller, SIGNAL(rewound(GBAThread*)), m_display, SLOT(forceDraw()));
95 connect(m_controller, SIGNAL(gamePaused(GBAThread*)), m_display, SLOT(pauseDrawing()));
96#ifndef Q_OS_MAC
97 connect(m_controller, SIGNAL(gamePaused(GBAThread*)), menuBar(), SLOT(show()));
98 connect(m_controller, &GameController::gameUnpaused, [this]() {
99 if(isFullScreen()) {
100 menuBar()->hide();
101 }
102 });
103#endif
104 connect(m_controller, SIGNAL(gameUnpaused(GBAThread*)), m_display, SLOT(unpauseDrawing()));
105 connect(m_controller, SIGNAL(postLog(int, const QString&)), m_logView, SLOT(postLog(int, const QString&)));
106 connect(m_controller, SIGNAL(frameAvailable(const uint32_t*)), this, SLOT(recordFrame()));
107 connect(m_controller, SIGNAL(frameAvailable(const uint32_t*)), m_display, SLOT(framePosted(const uint32_t*)));
108 connect(m_controller, SIGNAL(gameCrashed(const QString&)), this, SLOT(gameCrashed(const QString&)));
109 connect(m_controller, SIGNAL(gameFailed()), this, SLOT(gameFailed()));
110 connect(m_controller, SIGNAL(unimplementedBiosCall(int)), this, SLOT(unimplementedBiosCall(int)));
111 connect(m_logView, SIGNAL(levelsSet(int)), m_controller, SLOT(setLogLevel(int)));
112 connect(m_logView, SIGNAL(levelsEnabled(int)), m_controller, SLOT(enableLogLevel(int)));
113 connect(m_logView, SIGNAL(levelsDisabled(int)), m_controller, SLOT(disableLogLevel(int)));
114 connect(this, SIGNAL(startDrawing(const uint32_t*, GBAThread*)), m_display, SLOT(startDrawing(const uint32_t*, GBAThread*)), Qt::QueuedConnection);
115 connect(this, SIGNAL(shutdown()), m_display, SLOT(stopDrawing()));
116 connect(this, SIGNAL(shutdown()), m_controller, SLOT(closeGame()));
117 connect(this, SIGNAL(shutdown()), m_logView, SLOT(hide()));
118 connect(this, SIGNAL(audioBufferSamplesChanged(int)), m_controller, SLOT(setAudioBufferSamples(int)));
119 connect(this, SIGNAL(fpsTargetChanged(float)), m_controller, SLOT(setFPSTarget(float)));
120 connect(&m_fpsTimer, SIGNAL(timeout()), this, SLOT(showFPS()));
121
122 m_logView->setLevels(GBA_LOG_WARN | GBA_LOG_ERROR | GBA_LOG_FATAL);
123 m_fpsTimer.setInterval(FPS_TIMER_INTERVAL);
124
125 m_shortcutController->setConfigController(m_config);
126 setupMenu(menuBar());
127}
128
129Window::~Window() {
130 delete m_logView;
131
132#ifdef USE_FFMPEG
133 delete m_videoView;
134#endif
135
136#ifdef USE_MAGICK
137 delete m_gifView;
138#endif
139}
140
141void Window::argumentsPassed(GBAArguments* args) {
142 loadConfig();
143
144 if (args->patch) {
145 m_controller->loadPatch(args->patch);
146 }
147
148 if (args->fname) {
149 m_controller->loadGame(args->fname, args->dirmode);
150 }
151}
152
153void Window::resizeFrame(int width, int height) {
154 QSize newSize(width, height);
155 newSize -= m_screenWidget->size();
156 newSize += size();
157 resize(newSize);
158}
159
160void Window::setConfig(ConfigController* config) {
161 m_config = config;
162}
163
164void Window::loadConfig() {
165 const GBAOptions* opts = m_config->options();
166
167 m_logView->setLevels(opts->logLevel);
168
169 m_controller->setOptions(opts);
170 m_display->lockAspectRatio(opts->lockAspectRatio);
171 m_display->filter(opts->resampleVideo);
172
173 if (opts->bios) {
174 m_controller->loadBIOS(opts->bios);
175 }
176
177 if (opts->fpsTarget) {
178 emit fpsTargetChanged(opts->fpsTarget);
179 }
180
181 if (opts->audioBuffers) {
182 emit audioBufferSamplesChanged(opts->audioBuffers);
183 }
184
185 if (opts->width && opts->height) {
186 resizeFrame(opts->width, opts->height);
187 }
188
189 if (opts->fullscreen) {
190 enterFullScreen();
191 }
192
193 m_mruFiles = m_config->getMRU();
194 updateMRU();
195
196 m_inputController.setConfiguration(m_config);
197}
198
199void Window::saveConfig() {
200 m_config->write();
201}
202
203void Window::selectROM() {
204 bool doPause = m_controller->isLoaded() && !m_controller->isPaused();
205 if (doPause) {
206 m_controller->setPaused(true);
207 }
208 QString filename = QFileDialog::getOpenFileName(this, tr("Select ROM"), m_config->getQtOption("lastDirectory").toString(), tr("Game Boy Advance ROMs (*.gba *.zip *.rom *.bin)"));
209 if (doPause) {
210 m_controller->setPaused(false);
211 }
212 if (!filename.isEmpty()) {
213 m_config->setQtOption("lastDirectory", QFileInfo(filename).dir().path());
214 m_controller->loadGame(filename);
215 }
216}
217
218void Window::selectBIOS() {
219 bool doPause = m_controller->isLoaded() && !m_controller->isPaused();
220 if (doPause) {
221 m_controller->setPaused(true);
222 }
223 QString filename = QFileDialog::getOpenFileName(this, tr("Select BIOS"), m_config->getQtOption("lastDirectory").toString());
224 if (doPause) {
225 m_controller->setPaused(false);
226 }
227 if (!filename.isEmpty()) {
228 m_config->setQtOption("lastDirectory", QFileInfo(filename).dir().path());
229 m_config->setOption("bios", filename);
230 m_config->updateOption("bios");
231 m_config->setOption("useBios", true);
232 m_config->updateOption("useBios");
233 m_controller->loadBIOS(filename);
234 }
235}
236
237void Window::selectPatch() {
238 bool doPause = m_controller->isLoaded() && !m_controller->isPaused();
239 if (doPause) {
240 m_controller->setPaused(true);
241 }
242 QString filename = QFileDialog::getOpenFileName(this, tr("Select patch"), m_config->getQtOption("lastDirectory").toString(), tr("Patches (*.ips *.ups *.bps)"));
243 if (doPause) {
244 m_controller->setPaused(false);
245 }
246 if (!filename.isEmpty()) {
247 m_config->setQtOption("lastDirectory", QFileInfo(filename).dir().path());
248 m_controller->loadPatch(filename);
249 }
250}
251
252void Window::openView(QWidget* widget) {
253 connect(this, SIGNAL(shutdown()), widget, SLOT(close()));
254 widget->setAttribute(Qt::WA_DeleteOnClose);
255 widget->show();
256}
257
258void Window::importSharkport() {
259 bool doPause = m_controller->isLoaded() && !m_controller->isPaused();
260 if (doPause) {
261 m_controller->setPaused(true);
262 }
263 QString filename = QFileDialog::getOpenFileName(this, tr("Select save"), m_config->getQtOption("lastDirectory").toString(), tr("GameShark saves (*.sps *.xps)"));
264 if (doPause) {
265 m_controller->setPaused(false);
266 }
267 if (!filename.isEmpty()) {
268 m_config->setQtOption("lastDirectory", QFileInfo(filename).dir().path());
269 m_controller->importSharkport(filename);
270 }
271}
272
273void Window::exportSharkport() {
274 bool doPause = m_controller->isLoaded() && !m_controller->isPaused();
275 if (doPause) {
276 m_controller->setPaused(true);
277 }
278 QString filename = QFileDialog::getSaveFileName(this, tr("Select save"), m_config->getQtOption("lastDirectory").toString(), tr("GameShark saves (*.sps *.xps)"));
279 if (doPause) {
280 m_controller->setPaused(false);
281 }
282 if (!filename.isEmpty()) {
283 m_config->setQtOption("lastDirectory", QFileInfo(filename).dir().path());
284 m_controller->exportSharkport(filename);
285 }
286}
287
288void Window::openKeymapWindow() {
289 GBAKeyEditor* keyEditor = new GBAKeyEditor(&m_inputController, InputController::KEYBOARD);
290 openView(keyEditor);
291}
292
293void Window::openSettingsWindow() {
294 SettingsView* settingsWindow = new SettingsView(m_config);
295 connect(settingsWindow, SIGNAL(biosLoaded(const QString&)), m_controller, SLOT(loadBIOS(const QString&)));
296 connect(settingsWindow, SIGNAL(audioDriverChanged()), m_controller, SLOT(reloadAudioDriver()));
297 openView(settingsWindow);
298}
299
300void Window::openShortcutWindow() {
301 ShortcutView* shortcutView = new ShortcutView();
302 shortcutView->setController(m_shortcutController);
303 openView(shortcutView);
304}
305
306void Window::openOverrideWindow() {
307 OverrideView* overrideWindow = new OverrideView(m_controller, m_config);
308 openView(overrideWindow);
309}
310
311void Window::openSensorWindow() {
312 SensorView* sensorWindow = new SensorView(m_controller);
313 openView(sensorWindow);
314}
315
316void Window::openCheatsWindow() {
317 CheatsView* cheatsWindow = new CheatsView(m_controller);
318 openView(cheatsWindow);
319}
320
321void Window::openPaletteWindow() {
322 PaletteView* paletteWindow = new PaletteView(m_controller);
323 openView(paletteWindow);
324}
325
326#ifdef BUILD_SDL
327void Window::openGamepadWindow() {
328 const char* profile = m_inputController.profileForType(SDL_BINDING_BUTTON);
329 GBAKeyEditor* keyEditor = new GBAKeyEditor(&m_inputController, SDL_BINDING_BUTTON, profile);
330 openView(keyEditor);
331}
332#endif
333
334#ifdef USE_FFMPEG
335void Window::openVideoWindow() {
336 if (!m_videoView) {
337 m_videoView = new VideoView();
338 connect(m_videoView, SIGNAL(recordingStarted(GBAAVStream*)), m_controller, SLOT(setAVStream(GBAAVStream*)));
339 connect(m_videoView, SIGNAL(recordingStopped()), m_controller, SLOT(clearAVStream()), Qt::DirectConnection);
340 connect(m_controller, SIGNAL(gameStopped(GBAThread*)), m_videoView, SLOT(stopRecording()));
341 connect(m_controller, SIGNAL(gameStopped(GBAThread*)), m_videoView, SLOT(close()));
342 connect(this, SIGNAL(shutdown()), m_videoView, SLOT(close()));
343 }
344 m_videoView->show();
345}
346#endif
347
348#ifdef USE_MAGICK
349void Window::openGIFWindow() {
350 if (!m_gifView) {
351 m_gifView = new GIFView();
352 connect(m_gifView, SIGNAL(recordingStarted(GBAAVStream*)), m_controller, SLOT(setAVStream(GBAAVStream*)));
353 connect(m_gifView, SIGNAL(recordingStopped()), m_controller, SLOT(clearAVStream()), Qt::DirectConnection);
354 connect(m_controller, SIGNAL(gameStopped(GBAThread*)), m_gifView, SLOT(stopRecording()));
355 connect(m_controller, SIGNAL(gameStopped(GBAThread*)), m_gifView, SLOT(close()));
356 connect(this, SIGNAL(shutdown()), m_gifView, SLOT(close()));
357 }
358 m_gifView->show();
359}
360#endif
361
362#ifdef USE_GDB_STUB
363void Window::gdbOpen() {
364 if (!m_gdbController) {
365 m_gdbController = new GDBController(m_controller, this);
366 }
367 GDBWindow* window = new GDBWindow(m_gdbController);
368 connect(this, SIGNAL(shutdown()), window, SLOT(close()));
369 window->setAttribute(Qt::WA_DeleteOnClose);
370 window->show();
371}
372#endif
373
374void Window::keyPressEvent(QKeyEvent* event) {
375 if (event->isAutoRepeat()) {
376 QWidget::keyPressEvent(event);
377 return;
378 }
379 GBAKey key = m_inputController.mapKeyboard(event->key());
380 if (key == GBA_KEY_NONE) {
381 QWidget::keyPressEvent(event);
382 return;
383 }
384 m_controller->keyPressed(key);
385 event->accept();
386}
387
388void Window::keyReleaseEvent(QKeyEvent* event) {
389 if (event->isAutoRepeat()) {
390 QWidget::keyReleaseEvent(event);
391 return;
392 }
393 GBAKey key = m_inputController.mapKeyboard(event->key());
394 if (key == GBA_KEY_NONE) {
395 QWidget::keyPressEvent(event);
396 return;
397 }
398 m_controller->keyReleased(key);
399 event->accept();
400}
401
402void Window::resizeEvent(QResizeEvent*) {
403 m_config->setOption("height", m_screenWidget->height());
404 m_config->setOption("width", m_screenWidget->width());
405 m_config->setOption("fullscreen", isFullScreen());
406}
407
408void Window::closeEvent(QCloseEvent* event) {
409 emit shutdown();
410 m_config->setQtOption("windowPos", pos());
411 QMainWindow::closeEvent(event);
412}
413
414void Window::focusOutEvent(QFocusEvent*) {
415 m_controller->setTurbo(false, false);
416 m_controller->clearKeys();
417}
418
419void Window::dragEnterEvent(QDragEnterEvent* event) {
420 if (event->mimeData()->hasFormat("text/uri-list")) {
421 event->acceptProposedAction();
422 }
423}
424
425void Window::dropEvent(QDropEvent* event) {
426 QString uris = event->mimeData()->data("text/uri-list");
427 uris = uris.trimmed();
428 if (uris.contains("\n")) {
429 // Only one file please
430 return;
431 }
432 QUrl url(uris);
433 if (!url.isLocalFile()) {
434 // No remote loading
435 return;
436 }
437 event->accept();
438 m_controller->loadGame(url.path());
439}
440
441void Window::mouseDoubleClickEvent(QMouseEvent* event) {
442 if (event->button() != Qt::LeftButton) {
443 return;
444 }
445 toggleFullScreen();
446}
447
448void Window::enterFullScreen() {
449 if (isFullScreen()) {
450 return;
451 }
452 showFullScreen();
453#ifndef Q_OS_MAC
454 if (m_controller->isLoaded() && !m_controller->isPaused()) {
455 menuBar()->hide();
456 }
457#endif
458}
459
460void Window::exitFullScreen() {
461 if (!isFullScreen()) {
462 return;
463 }
464 showNormal();
465 menuBar()->show();
466}
467
468void Window::toggleFullScreen() {
469 if (isFullScreen()) {
470 exitFullScreen();
471 } else {
472 enterFullScreen();
473 }
474}
475
476void Window::gameStarted(GBAThread* context) {
477 char title[13] = { '\0' };
478 MutexLock(&context->stateMutex);
479 if (context->state < THREAD_EXITING) {
480 emit startDrawing(m_controller->drawContext(), context);
481 GBAGetGameTitle(context->gba, title);
482 } else {
483 MutexUnlock(&context->stateMutex);
484 return;
485 }
486 MutexUnlock(&context->stateMutex);
487 foreach (QAction* action, m_gameActions) {
488 action->setDisabled(false);
489 }
490 appendMRU(context->fname);
491 setWindowTitle(tr(PROJECT_NAME " - %1").arg(title));
492 attachWidget(m_display);
493
494#ifndef Q_OS_MAC
495 if(isFullScreen()) {
496 menuBar()->hide();
497 }
498#endif
499
500 m_hitUnimplementedBiosCall = false;
501 m_fpsTimer.start();
502}
503
504void Window::gameStopped() {
505 foreach (QAction* action, m_gameActions) {
506 action->setDisabled(true);
507 }
508 setWindowTitle(tr(PROJECT_NAME));
509 detachWidget(m_display);
510 m_screenWidget->setLockAspectRatio(m_logo.width(), m_logo.height());
511 m_screenWidget->setPixmap(m_logo);
512
513 m_fpsTimer.stop();
514}
515
516void Window::gameCrashed(const QString& errorMessage) {
517 QMessageBox* crash = new QMessageBox(QMessageBox::Critical, tr("Crash"),
518 tr("The game has crashed with the following error:\n\n%1").arg(errorMessage),
519 QMessageBox::Ok, this, Qt::Sheet);
520 crash->setAttribute(Qt::WA_DeleteOnClose);
521 crash->show();
522}
523
524void Window::gameFailed() {
525 QMessageBox* fail = new QMessageBox(QMessageBox::Warning, tr("Couldn't Load"),
526 tr("Could not load game. Are you sure it's in the correct format?"),
527 QMessageBox::Ok, this, Qt::Sheet);
528 fail->setAttribute(Qt::WA_DeleteOnClose);
529 fail->show();
530}
531
532void Window::unimplementedBiosCall(int call) {
533 if (m_hitUnimplementedBiosCall) {
534 return;
535 }
536 m_hitUnimplementedBiosCall = true;
537
538 QMessageBox* fail = new QMessageBox(QMessageBox::Warning, tr("Unimplemented BIOS call"),
539 tr("This game uses a BIOS call that is not implemented. Please use the official BIOS for best experience."),
540 QMessageBox::Ok, this, Qt::Sheet);
541 fail->setAttribute(Qt::WA_DeleteOnClose);
542 fail->show();
543}
544
545void Window::recordFrame() {
546 m_frameList.append(QDateTime::currentDateTime());
547 while (m_frameList.count() > FRAME_LIST_SIZE) {
548 m_frameList.removeFirst();
549 }
550}
551
552void Window::showFPS() {
553 char gameTitle[13] = { '\0' };
554 GBAGetGameTitle(m_controller->thread()->gba, gameTitle);
555
556 QString title(gameTitle);
557 std::shared_ptr<MultiplayerController> multiplayer = m_controller->multiplayerController();
558 if (multiplayer && multiplayer->attached() > 1) {
559 title += tr(" - Player %1 of %2").arg(m_playerId + 1).arg(multiplayer->attached());
560 }
561 if (m_frameList.isEmpty()) {
562 setWindowTitle(tr(PROJECT_NAME " - %1").arg(title));
563 return;
564 }
565 qint64 interval = m_frameList.first().msecsTo(m_frameList.last());
566 float fps = (m_frameList.count() - 1) * 10000.f / interval;
567 fps = round(fps) / 10.f;
568 setWindowTitle(tr(PROJECT_NAME " - %1 (%2 fps)").arg(title).arg(fps));
569}
570
571void Window::openStateWindow(LoadSave ls) {
572 if (m_stateWindow) {
573 return;
574 }
575 bool wasPaused = m_controller->isPaused();
576 m_stateWindow = new LoadSaveState(m_controller);
577 connect(this, SIGNAL(shutdown()), m_stateWindow, SLOT(close()));
578 connect(m_controller, SIGNAL(gameStopped(GBAThread*)), m_stateWindow, SLOT(close()));
579 connect(m_stateWindow, &LoadSaveState::closed, [this]() {
580 m_screenWidget->layout()->removeWidget(m_stateWindow);
581 m_stateWindow = nullptr;
582 QMetaObject::invokeMethod(this, "setFocus", Qt::QueuedConnection);
583 });
584 if (!wasPaused) {
585 m_controller->setPaused(true);
586 connect(m_stateWindow, &LoadSaveState::closed, [this]() { m_controller->setPaused(false); });
587 }
588 m_stateWindow->setAttribute(Qt::WA_DeleteOnClose);
589 m_stateWindow->setMode(ls);
590 attachWidget(m_stateWindow);
591}
592
593void Window::setupMenu(QMenuBar* menubar) {
594 menubar->clear();
595 QMenu* fileMenu = menubar->addMenu(tr("&File"));
596 m_shortcutController->addMenu(fileMenu);
597 installEventFilter(m_shortcutController);
598 addControlledAction(fileMenu, fileMenu->addAction(tr("Load &ROM..."), this, SLOT(selectROM()), QKeySequence::Open), "loadROM");
599 addControlledAction(fileMenu, fileMenu->addAction(tr("Load &BIOS..."), this, SLOT(selectBIOS())), "loadBIOS");
600 addControlledAction(fileMenu, fileMenu->addAction(tr("Load &patch..."), this, SLOT(selectPatch())), "loadPatch");
601
602 m_mruMenu = fileMenu->addMenu(tr("Recent"));
603
604 fileMenu->addSeparator();
605
606 QAction* loadState = new QAction(tr("&Load state"), fileMenu);
607 loadState->setShortcut(tr("F10"));
608 connect(loadState, &QAction::triggered, [this]() { this->openStateWindow(LoadSave::LOAD); });
609 m_gameActions.append(loadState);
610 addControlledAction(fileMenu, loadState, "loadState");
611
612 QAction* saveState = new QAction(tr("&Save state"), fileMenu);
613 saveState->setShortcut(tr("Shift+F10"));
614 connect(saveState, &QAction::triggered, [this]() { this->openStateWindow(LoadSave::SAVE); });
615 m_gameActions.append(saveState);
616 addControlledAction(fileMenu, saveState, "saveState");
617
618 QMenu* quickLoadMenu = fileMenu->addMenu(tr("Quick load"));
619 QMenu* quickSaveMenu = fileMenu->addMenu(tr("Quick save"));
620 m_shortcutController->addMenu(quickLoadMenu);
621 m_shortcutController->addMenu(quickSaveMenu);
622 int i;
623 for (i = 1; i < 10; ++i) {
624 QAction* quickLoad = new QAction(tr("State &%1").arg(i), quickLoadMenu);
625 quickLoad->setShortcut(tr("F%1").arg(i));
626 connect(quickLoad, &QAction::triggered, [this, i]() { m_controller->loadState(i); });
627 m_gameActions.append(quickLoad);
628 addControlledAction(quickLoadMenu, quickLoad, QString("quickLoad.%1").arg(i));
629
630 QAction* quickSave = new QAction(tr("State &%1").arg(i), quickSaveMenu);
631 quickSave->setShortcut(tr("Shift+F%1").arg(i));
632 connect(quickSave, &QAction::triggered, [this, i]() { m_controller->saveState(i); });
633 m_gameActions.append(quickSave);
634 addControlledAction(quickSaveMenu, quickSave, QString("quickSave.%1").arg(i));
635 }
636
637 fileMenu->addSeparator();
638 QAction* importShark = new QAction(tr("Import GameShark Save"), fileMenu);
639 connect(importShark, SIGNAL(triggered()), this, SLOT(importSharkport()));
640 m_gameActions.append(importShark);
641 addControlledAction(fileMenu, importShark, "importShark");
642
643 QAction* exportShark = new QAction(tr("Export GameShark Save"), fileMenu);
644 connect(exportShark, SIGNAL(triggered()), this, SLOT(exportSharkport()));
645 m_gameActions.append(exportShark);
646 addControlledAction(fileMenu, exportShark, "exportShark");
647
648 fileMenu->addSeparator();
649 QAction* multiWindow = new QAction(tr("New multiplayer window"), fileMenu);
650 connect(multiWindow, &QAction::triggered, [this]() {
651 std::shared_ptr<MultiplayerController> multiplayer = m_controller->multiplayerController();
652 if (!multiplayer) {
653 multiplayer = std::make_shared<MultiplayerController>();
654 m_controller->setMultiplayerController(multiplayer);
655 }
656 Window* w2 = new Window(m_config, multiplayer->attached());
657 w2->setAttribute(Qt::WA_DeleteOnClose);
658 w2->loadConfig();
659 w2->controller()->setMultiplayerController(multiplayer);
660 w2->show();
661 });
662 addControlledAction(fileMenu, multiWindow, "multiWindow");
663
664#ifndef Q_OS_MAC
665 addControlledAction(fileMenu, fileMenu->addAction(tr("E&xit"), this, SLOT(close()), QKeySequence::Quit), "quit");
666#endif
667
668 QMenu* emulationMenu = menubar->addMenu(tr("&Emulation"));
669 m_shortcutController->addMenu(emulationMenu);
670 QAction* reset = new QAction(tr("&Reset"), emulationMenu);
671 reset->setShortcut(tr("Ctrl+R"));
672 connect(reset, SIGNAL(triggered()), m_controller, SLOT(reset()));
673 m_gameActions.append(reset);
674 addControlledAction(emulationMenu, reset, "reset");
675
676 QAction* shutdown = new QAction(tr("Sh&utdown"), emulationMenu);
677 connect(shutdown, SIGNAL(triggered()), m_controller, SLOT(closeGame()));
678 m_gameActions.append(shutdown);
679 addControlledAction(emulationMenu, shutdown, "shutdown");
680 emulationMenu->addSeparator();
681
682 QAction* pause = new QAction(tr("&Pause"), emulationMenu);
683 pause->setChecked(false);
684 pause->setCheckable(true);
685 pause->setShortcut(tr("Ctrl+P"));
686 connect(pause, SIGNAL(triggered(bool)), m_controller, SLOT(setPaused(bool)));
687 connect(m_controller, &GameController::gamePaused, [this, pause]() {
688 pause->setChecked(true);
689
690 QImage currentImage(reinterpret_cast<const uchar*>(m_controller->drawContext()), VIDEO_HORIZONTAL_PIXELS, VIDEO_VERTICAL_PIXELS, 1024, QImage::Format_RGB32);
691 QPixmap pixmap;
692 pixmap.convertFromImage(currentImage.rgbSwapped());
693 m_screenWidget->setPixmap(pixmap);
694 m_screenWidget->setLockAspectRatio(3, 2);
695 });
696 connect(m_controller, &GameController::gameUnpaused, [pause]() { pause->setChecked(false); });
697 m_gameActions.append(pause);
698 addControlledAction(emulationMenu, pause, "pause");
699
700 QAction* frameAdvance = new QAction(tr("&Next frame"), emulationMenu);
701 frameAdvance->setShortcut(tr("Ctrl+N"));
702 connect(frameAdvance, SIGNAL(triggered()), m_controller, SLOT(frameAdvance()));
703 m_gameActions.append(frameAdvance);
704 addControlledAction(emulationMenu, frameAdvance, "frameAdvance");
705
706 emulationMenu->addSeparator();
707
708 QAction* turbo = new QAction(tr("&Fast forward"), emulationMenu);
709 turbo->setCheckable(true);
710 turbo->setChecked(false);
711 turbo->setShortcut(tr("Shift+Tab"));
712 connect(turbo, SIGNAL(triggered(bool)), m_controller, SLOT(setTurbo(bool)));
713 addControlledAction(emulationMenu, turbo, "fastForward");
714
715 QAction* rewind = new QAction(tr("Re&wind"), emulationMenu);
716 rewind->setShortcut(tr("`"));
717 connect(rewind, SIGNAL(triggered()), m_controller, SLOT(rewind()));
718 m_gameActions.append(rewind);
719 addControlledAction(emulationMenu, rewind, "rewind");
720
721 QAction* frameRewind = new QAction(tr("Step backwards"), emulationMenu);
722 frameRewind->setShortcut(tr("Ctrl+B"));
723 connect(frameRewind, &QAction::triggered, [this] () {
724 m_controller->rewind(1);
725 });
726 m_gameActions.append(frameRewind);
727 addControlledAction(emulationMenu, frameRewind, "frameRewind");
728
729 ConfigOption* videoSync = m_config->addOption("videoSync");
730 videoSync->addBoolean(tr("Sync to &video"), emulationMenu);
731 videoSync->connect([this](const QVariant& value) {
732 m_controller->setVideoSync(value.toBool());
733 }, this);
734 m_config->updateOption("videoSync");
735
736 ConfigOption* audioSync = m_config->addOption("audioSync");
737 audioSync->addBoolean(tr("Sync to &audio"), emulationMenu);
738 audioSync->connect([this](const QVariant& value) {
739 m_controller->setAudioSync(value.toBool());
740 }, this);
741 m_config->updateOption("audioSync");
742
743 emulationMenu->addSeparator();
744
745 QMenu* solarMenu = emulationMenu->addMenu(tr("Solar sensor"));
746 m_shortcutController->addMenu(solarMenu);
747 QAction* solarIncrease = new QAction(tr("Increase solar level"), solarMenu);
748 connect(solarIncrease, SIGNAL(triggered()), m_controller, SLOT(increaseLuminanceLevel()));
749 addControlledAction(solarMenu, solarIncrease, "increaseLuminanceLevel");
750
751 QAction* solarDecrease = new QAction(tr("Decrease solar level"), solarMenu);
752 connect(solarDecrease, SIGNAL(triggered()), m_controller, SLOT(decreaseLuminanceLevel()));
753 addControlledAction(solarMenu, solarDecrease, "decreaseLuminanceLevel");
754
755 QAction* maxSolar = new QAction(tr("Brightest solar level"), solarMenu);
756 connect(maxSolar, &QAction::triggered, [this]() { m_controller->setLuminanceLevel(10); });
757 addControlledAction(solarMenu, maxSolar, "maxLuminanceLevel");
758
759 QAction* minSolar = new QAction(tr("Darkest solar level"), solarMenu);
760 connect(minSolar, &QAction::triggered, [this]() { m_controller->setLuminanceLevel(0); });
761 addControlledAction(solarMenu, minSolar, "minLuminanceLevel");
762
763 QMenu* avMenu = menubar->addMenu(tr("Audio/&Video"));
764 m_shortcutController->addMenu(avMenu);
765 QMenu* frameMenu = avMenu->addMenu(tr("Frame size"));
766 m_shortcutController->addMenu(frameMenu, avMenu);
767 for (int i = 1; i <= 6; ++i) {
768 QAction* setSize = new QAction(tr("%1x").arg(QString::number(i)), avMenu);
769 connect(setSize, &QAction::triggered, [this, i]() {
770 showNormal();
771 resizeFrame(VIDEO_HORIZONTAL_PIXELS * i, VIDEO_VERTICAL_PIXELS * i);
772 });
773 addControlledAction(frameMenu, setSize, QString("frame%1x").arg(QString::number(i)));
774 }
775 addControlledAction(frameMenu, frameMenu->addAction(tr("Fullscreen"), this, SLOT(toggleFullScreen()), QKeySequence("Ctrl+F")), "fullscreen");
776
777 ConfigOption* lockAspectRatio = m_config->addOption("lockAspectRatio");
778 lockAspectRatio->addBoolean(tr("Lock aspect ratio"), avMenu);
779 lockAspectRatio->connect([this](const QVariant& value) {
780 m_display->lockAspectRatio(value.toBool());
781 }, this);
782 m_config->updateOption("lockAspectRatio");
783
784 ConfigOption* resampleVideo = m_config->addOption("resampleVideo");
785 resampleVideo->addBoolean(tr("Resample video"), avMenu);
786 resampleVideo->connect([this](const QVariant& value) {
787 m_display->filter(value.toBool());
788 }, this);
789 m_config->updateOption("resampleVideo");
790
791 QMenu* skipMenu = avMenu->addMenu(tr("Frame&skip"));
792 ConfigOption* skip = m_config->addOption("frameskip");
793 skip->connect([this](const QVariant& value) {
794 m_controller->setFrameskip(value.toInt());
795 }, this);
796 for (int i = 0; i <= 10; ++i) {
797 skip->addValue(QString::number(i), i, skipMenu);
798 }
799 m_config->updateOption("frameskip");
800
801 avMenu->addSeparator();
802
803 QMenu* buffersMenu = avMenu->addMenu(tr("Audio buffer &size"));
804 ConfigOption* buffers = m_config->addOption("audioBuffers");
805 buffers->connect([this](const QVariant& value) {
806 emit audioBufferSamplesChanged(value.toInt());
807 }, this);
808 buffers->addValue(tr("512"), 512, buffersMenu);
809 buffers->addValue(tr("768"), 768, buffersMenu);
810 buffers->addValue(tr("1024"), 1024, buffersMenu);
811 buffers->addValue(tr("2048"), 2048, buffersMenu);
812 buffers->addValue(tr("4096"), 4096, buffersMenu);
813 m_config->updateOption("audioBuffers");
814
815 avMenu->addSeparator();
816
817 QMenu* target = avMenu->addMenu(tr("FPS target"));
818 ConfigOption* fpsTargetOption = m_config->addOption("fpsTarget");
819 fpsTargetOption->connect([this](const QVariant& value) {
820 emit fpsTargetChanged(value.toInt());
821 }, this);
822 fpsTargetOption->addValue(tr("15"), 15, target);
823 fpsTargetOption->addValue(tr("30"), 30, target);
824 fpsTargetOption->addValue(tr("45"), 45, target);
825 fpsTargetOption->addValue(tr("60"), 60, target);
826 fpsTargetOption->addValue(tr("90"), 90, target);
827 fpsTargetOption->addValue(tr("120"), 120, target);
828 fpsTargetOption->addValue(tr("240"), 240, target);
829 m_config->updateOption("fpsTarget");
830
831#if defined(USE_PNG) || defined(USE_FFMPEG) || defined(USE_MAGICK)
832 avMenu->addSeparator();
833#endif
834
835#ifdef USE_PNG
836 QAction* screenshot = new QAction(tr("Take &screenshot"), avMenu);
837 screenshot->setShortcut(tr("F12"));
838 connect(screenshot, SIGNAL(triggered()), m_controller, SLOT(screenshot()));
839 m_gameActions.append(screenshot);
840 addControlledAction(avMenu, screenshot, "screenshot");
841#endif
842
843#ifdef USE_FFMPEG
844 QAction* recordOutput = new QAction(tr("Record output..."), avMenu);
845 recordOutput->setShortcut(tr("F11"));
846 connect(recordOutput, SIGNAL(triggered()), this, SLOT(openVideoWindow()));
847 addControlledAction(avMenu, recordOutput, "recordOutput");
848#endif
849
850#ifdef USE_MAGICK
851 QAction* recordGIF = new QAction(tr("Record GIF..."), avMenu);
852 recordGIF->setShortcut(tr("Shift+F11"));
853 connect(recordGIF, SIGNAL(triggered()), this, SLOT(openGIFWindow()));
854 addControlledAction(avMenu, recordGIF, "recordGIF");
855#endif
856
857 avMenu->addSeparator();
858 QMenu* videoLayers = avMenu->addMenu(tr("Video layers"));
859
860 for (int i = 0; i < 4; ++i) {
861 QAction* enableBg = new QAction(tr("Background %0").arg(i), videoLayers);
862 enableBg->setCheckable(true);
863 enableBg->setChecked(true);
864 connect(enableBg, &QAction::triggered, [this, i](bool enable) { m_controller->thread()->gba->video.renderer->disableBG[i] = !enable; });
865 m_gameActions.append(enableBg);
866 addControlledAction(videoLayers, enableBg, QString("enableBG%0").arg(i));
867 }
868
869 QAction* enableObj = new QAction(tr("OBJ (sprites)"), videoLayers);
870 enableObj->setCheckable(true);
871 enableObj->setChecked(true);
872 connect(enableObj, &QAction::triggered, [this](bool enable) { m_controller->thread()->gba->video.renderer->disableOBJ = !enable; });
873 m_gameActions.append(enableObj);
874 addControlledAction(videoLayers, enableObj, "enableOBJ");
875
876 QMenu* audioChannels = avMenu->addMenu(tr("Audio channels"));
877
878 for (int i = 0; i < 4; ++i) {
879 QAction* enableCh = new QAction(tr("Channel %0").arg(i + 1), audioChannels);
880 enableCh->setCheckable(true);
881 enableCh->setChecked(true);
882 connect(enableCh, &QAction::triggered, [this, i](bool enable) { m_controller->thread()->gba->audio.forceDisableCh[i] = !enable; });
883 m_gameActions.append(enableCh);
884 addControlledAction(audioChannels, enableCh, QString("enableCh%0").arg(i + 1));
885 }
886
887 QAction* enableChA = new QAction(tr("Channel A"), audioChannels);
888 enableChA->setCheckable(true);
889 enableChA->setChecked(true);
890 connect(enableChA, &QAction::triggered, [this, i](bool enable) { m_controller->thread()->gba->audio.forceDisableChA = !enable; });
891 m_gameActions.append(enableChA);
892 addControlledAction(audioChannels, enableChA, QString("enableChA"));
893
894 QAction* enableChB = new QAction(tr("Channel B"), audioChannels);
895 enableChB->setCheckable(true);
896 enableChB->setChecked(true);
897 connect(enableChB, &QAction::triggered, [this, i](bool enable) { m_controller->thread()->gba->audio.forceDisableChB = !enable; });
898 m_gameActions.append(enableChB);
899 addControlledAction(audioChannels, enableChB, QString("enableChB"));
900
901 QMenu* toolsMenu = menubar->addMenu(tr("&Tools"));
902 m_shortcutController->addMenu(toolsMenu);
903 QAction* viewLogs = new QAction(tr("View &logs..."), toolsMenu);
904 connect(viewLogs, SIGNAL(triggered()), m_logView, SLOT(show()));
905 addControlledAction(toolsMenu, viewLogs, "viewLogs");
906
907 QAction* overrides = new QAction(tr("Game &overrides..."), toolsMenu);
908 connect(overrides, SIGNAL(triggered()), this, SLOT(openOverrideWindow()));
909 addControlledAction(toolsMenu, overrides, "overrideWindow");
910
911 QAction* sensors = new QAction(tr("Game &Pak sensors..."), toolsMenu);
912 connect(sensors, SIGNAL(triggered()), this, SLOT(openSensorWindow()));
913 addControlledAction(toolsMenu, sensors, "sensorWindow");
914
915 QAction* cheats = new QAction(tr("&Cheats..."), toolsMenu);
916 connect(cheats, SIGNAL(triggered()), this, SLOT(openCheatsWindow()));
917 addControlledAction(toolsMenu, cheats, "cheatsWindow");
918
919#ifdef USE_GDB_STUB
920 QAction* gdbWindow = new QAction(tr("Start &GDB server..."), toolsMenu);
921 connect(gdbWindow, SIGNAL(triggered()), this, SLOT(gdbOpen()));
922 addControlledAction(toolsMenu, gdbWindow, "gdbWindow");
923#endif
924
925 toolsMenu->addSeparator();
926 addControlledAction(toolsMenu, toolsMenu->addAction(tr("Settings..."), this, SLOT(openSettingsWindow())), "settings");
927 addControlledAction(toolsMenu, toolsMenu->addAction(tr("Edit shortcuts..."), this, SLOT(openShortcutWindow())), "shortcuts");
928
929 QAction* keymap = new QAction(tr("Remap keyboard..."), toolsMenu);
930 connect(keymap, SIGNAL(triggered()), this, SLOT(openKeymapWindow()));
931 addControlledAction(toolsMenu, keymap, "remapKeyboard");
932
933#ifdef BUILD_SDL
934 QAction* gamepad = new QAction(tr("Remap gamepad..."), toolsMenu);
935 connect(gamepad, SIGNAL(triggered()), this, SLOT(openGamepadWindow()));
936 addControlledAction(toolsMenu, gamepad, "remapGamepad");
937#endif
938
939 toolsMenu->addSeparator();
940
941 QAction* paletteView = new QAction(tr("View &palette..."), toolsMenu);
942 connect(paletteView, SIGNAL(triggered()), this, SLOT(openPaletteWindow()));
943 m_gameActions.append(paletteView);
944 addControlledAction(toolsMenu, paletteView, "paletteWindow");
945
946 ConfigOption* skipBios = m_config->addOption("skipBios");
947 skipBios->connect([this](const QVariant& value) {
948 m_controller->setSkipBIOS(value.toBool());
949 }, this);
950
951 ConfigOption* volume = m_config->addOption("volume");
952 volume->connect([this](const QVariant& value) {
953 m_controller->setVolume(value.toInt());
954 }, this);
955
956 ConfigOption* mute = m_config->addOption("mute");
957 mute->connect([this](const QVariant& value) {
958 m_controller->setMute(value.toBool());
959 }, this);
960
961 ConfigOption* rewindEnable = m_config->addOption("rewindEnable");
962 rewindEnable->connect([this](const QVariant& value) {
963 m_controller->setRewind(value.toBool(), m_config->getOption("rewindBufferCapacity").toInt(), m_config->getOption("rewindBufferInterval").toInt());
964 }, this);
965
966 ConfigOption* rewindBufferCapacity = m_config->addOption("rewindBufferCapacity");
967 rewindBufferCapacity->connect([this](const QVariant& value) {
968 m_controller->setRewind(m_config->getOption("rewindEnable").toInt(), value.toInt(), m_config->getOption("rewindBufferInterval").toInt());
969 }, this);
970
971 ConfigOption* rewindBufferInterval = m_config->addOption("rewindBufferInterval");
972 rewindBufferInterval->connect([this](const QVariant& value) {
973 m_controller->setRewind(m_config->getOption("rewindEnable").toInt(), m_config->getOption("rewindBufferCapacity").toInt(), value.toInt());
974 }, this);
975
976 ConfigOption* allowOpposingDirections = m_config->addOption("allowOpposingDirections");
977 allowOpposingDirections->connect([this](const QVariant& value) {
978 m_inputController.setAllowOpposing(value.toBool());
979 }, this);
980
981 QMenu* other = new QMenu(tr("Other"), this);
982 m_shortcutController->addMenu(other);
983 m_shortcutController->addFunctions(other, [this]() {
984 m_controller->setTurbo(true, false);
985 }, [this]() {
986 m_controller->setTurbo(false, false);
987 }, QKeySequence(Qt::Key_Tab), tr("Fast Forward (held)"), "holdFastForward");
988
989 addControlledAction(other, other->addAction(tr("Exit fullscreen"), this, SLOT(exitFullScreen()), QKeySequence("Esc")), "exitFullScreen");
990
991 foreach (QAction* action, m_gameActions) {
992 action->setDisabled(true);
993 }
994}
995
996void Window::attachWidget(QWidget* widget) {
997 m_screenWidget->layout()->addWidget(widget);
998 static_cast<QStackedLayout*>(m_screenWidget->layout())->setCurrentWidget(widget);
999}
1000
1001void Window::detachWidget(QWidget* widget) {
1002 m_screenWidget->layout()->removeWidget(widget);
1003}
1004
1005void Window::appendMRU(const QString& fname) {
1006 int index = m_mruFiles.indexOf(fname);
1007 if (index >= 0) {
1008 m_mruFiles.removeAt(index);
1009 }
1010 m_mruFiles.prepend(fname);
1011 while (m_mruFiles.size() > ConfigController::MRU_LIST_SIZE) {
1012 m_mruFiles.removeLast();
1013 }
1014 updateMRU();
1015}
1016
1017void Window::updateMRU() {
1018 if (!m_mruMenu) {
1019 return;
1020 }
1021 m_mruMenu->clear();
1022 int i = 0;
1023 for (const QString& file : m_mruFiles) {
1024 QAction* item = new QAction(file, m_mruMenu);
1025 item->setShortcut(QString("Ctrl+%1").arg(i));
1026 connect(item, &QAction::triggered, [this, file]() { m_controller->loadGame(file); });
1027 m_mruMenu->addAction(item);
1028 ++i;
1029 }
1030 m_config->setMRU(m_mruFiles);
1031 m_config->write();
1032 m_mruMenu->setEnabled(i > 0);
1033}
1034
1035QAction* Window::addControlledAction(QMenu* menu, QAction* action, const QString& name) {
1036 m_shortcutController->addAction(menu, action, name);
1037 menu->addAction(action);
1038 action->setShortcutContext(Qt::WidgetShortcut);
1039 addAction(action);
1040 return action;
1041}
1042
1043WindowBackground::WindowBackground(QWidget* parent)
1044 : QLabel(parent)
1045{
1046 setLayout(new QStackedLayout());
1047 layout()->setContentsMargins(0, 0, 0, 0);
1048 setAlignment(Qt::AlignCenter);
1049}
1050
1051void WindowBackground::setSizeHint(const QSize& hint) {
1052 m_sizeHint = hint;
1053}
1054
1055QSize WindowBackground::sizeHint() const {
1056 return m_sizeHint;
1057}
1058
1059void WindowBackground::setLockAspectRatio(int width, int height) {
1060 m_aspectWidth = width;
1061 m_aspectHeight = height;
1062}
1063
1064void WindowBackground::paintEvent(QPaintEvent*) {
1065 const QPixmap* logo = pixmap();
1066 if (!logo) {
1067 return;
1068 }
1069 QPainter painter(this);
1070 painter.setRenderHint(QPainter::SmoothPixmapTransform);
1071 painter.fillRect(QRect(QPoint(), size()), Qt::black);
1072 QSize s = size();
1073 QSize ds = s;
1074 if (s.width() * m_aspectHeight > s.height() * m_aspectWidth) {
1075 ds.setWidth(s.height() * m_aspectWidth / m_aspectHeight);
1076 } else if (s.width() * m_aspectHeight < s.height() * m_aspectWidth) {
1077 ds.setHeight(s.width() * m_aspectHeight / m_aspectWidth);
1078 }
1079 QPoint origin = QPoint((s.width() - ds.width()) / 2, (s.height() - ds.height()) / 2);
1080 QRect full(origin, ds);
1081 painter.drawPixmap(full, *logo);
1082}