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 ConfigOption* videoSync = m_config->addOption("videoSync");
722 videoSync->addBoolean(tr("Sync to &video"), emulationMenu);
723 videoSync->connect([this](const QVariant& value) {
724 m_controller->setVideoSync(value.toBool());
725 }, this);
726 m_config->updateOption("videoSync");
727
728 ConfigOption* audioSync = m_config->addOption("audioSync");
729 audioSync->addBoolean(tr("Sync to &audio"), emulationMenu);
730 audioSync->connect([this](const QVariant& value) {
731 m_controller->setAudioSync(value.toBool());
732 }, this);
733 m_config->updateOption("audioSync");
734
735 emulationMenu->addSeparator();
736
737 QMenu* solarMenu = emulationMenu->addMenu(tr("Solar sensor"));
738 m_shortcutController->addMenu(solarMenu);
739 QAction* solarIncrease = new QAction(tr("Increase solar level"), solarMenu);
740 connect(solarIncrease, SIGNAL(triggered()), m_controller, SLOT(increaseLuminanceLevel()));
741 addControlledAction(solarMenu, solarIncrease, "increaseLuminanceLevel");
742
743 QAction* solarDecrease = new QAction(tr("Decrease solar level"), solarMenu);
744 connect(solarDecrease, SIGNAL(triggered()), m_controller, SLOT(decreaseLuminanceLevel()));
745 addControlledAction(solarMenu, solarDecrease, "decreaseLuminanceLevel");
746
747 QAction* maxSolar = new QAction(tr("Brightest solar level"), solarMenu);
748 connect(maxSolar, &QAction::triggered, [this]() { m_controller->setLuminanceLevel(10); });
749 addControlledAction(solarMenu, maxSolar, "maxLuminanceLevel");
750
751 QAction* minSolar = new QAction(tr("Darkest solar level"), solarMenu);
752 connect(minSolar, &QAction::triggered, [this]() { m_controller->setLuminanceLevel(0); });
753 addControlledAction(solarMenu, minSolar, "minLuminanceLevel");
754
755 QMenu* avMenu = menubar->addMenu(tr("Audio/&Video"));
756 m_shortcutController->addMenu(avMenu);
757 QMenu* frameMenu = avMenu->addMenu(tr("Frame size"));
758 m_shortcutController->addMenu(frameMenu, avMenu);
759 for (int i = 1; i <= 6; ++i) {
760 QAction* setSize = new QAction(tr("%1x").arg(QString::number(i)), avMenu);
761 connect(setSize, &QAction::triggered, [this, i]() {
762 showNormal();
763 resizeFrame(VIDEO_HORIZONTAL_PIXELS * i, VIDEO_VERTICAL_PIXELS * i);
764 });
765 addControlledAction(frameMenu, setSize, QString("frame%1x").arg(QString::number(i)));
766 }
767 addControlledAction(frameMenu, frameMenu->addAction(tr("Fullscreen"), this, SLOT(toggleFullScreen()), QKeySequence("Ctrl+F")), "fullscreen");
768
769 ConfigOption* lockAspectRatio = m_config->addOption("lockAspectRatio");
770 lockAspectRatio->addBoolean(tr("Lock aspect ratio"), avMenu);
771 lockAspectRatio->connect([this](const QVariant& value) {
772 m_display->lockAspectRatio(value.toBool());
773 }, this);
774 m_config->updateOption("lockAspectRatio");
775
776 ConfigOption* resampleVideo = m_config->addOption("resampleVideo");
777 resampleVideo->addBoolean(tr("Resample video"), avMenu);
778 resampleVideo->connect([this](const QVariant& value) {
779 m_display->filter(value.toBool());
780 }, this);
781 m_config->updateOption("resampleVideo");
782
783 QMenu* skipMenu = avMenu->addMenu(tr("Frame&skip"));
784 ConfigOption* skip = m_config->addOption("frameskip");
785 skip->connect([this](const QVariant& value) {
786 m_controller->setFrameskip(value.toInt());
787 }, this);
788 for (int i = 0; i <= 10; ++i) {
789 skip->addValue(QString::number(i), i, skipMenu);
790 }
791 m_config->updateOption("frameskip");
792
793 avMenu->addSeparator();
794
795 QMenu* buffersMenu = avMenu->addMenu(tr("Audio buffer &size"));
796 ConfigOption* buffers = m_config->addOption("audioBuffers");
797 buffers->connect([this](const QVariant& value) {
798 emit audioBufferSamplesChanged(value.toInt());
799 }, this);
800 buffers->addValue(tr("512"), 512, buffersMenu);
801 buffers->addValue(tr("768"), 768, buffersMenu);
802 buffers->addValue(tr("1024"), 1024, buffersMenu);
803 buffers->addValue(tr("2048"), 2048, buffersMenu);
804 buffers->addValue(tr("4096"), 4096, buffersMenu);
805 m_config->updateOption("audioBuffers");
806
807 avMenu->addSeparator();
808
809 QMenu* target = avMenu->addMenu(tr("FPS target"));
810 ConfigOption* fpsTargetOption = m_config->addOption("fpsTarget");
811 fpsTargetOption->connect([this](const QVariant& value) {
812 emit fpsTargetChanged(value.toInt());
813 }, this);
814 fpsTargetOption->addValue(tr("15"), 15, target);
815 fpsTargetOption->addValue(tr("30"), 30, target);
816 fpsTargetOption->addValue(tr("45"), 45, target);
817 fpsTargetOption->addValue(tr("60"), 60, target);
818 fpsTargetOption->addValue(tr("90"), 90, target);
819 fpsTargetOption->addValue(tr("120"), 120, target);
820 fpsTargetOption->addValue(tr("240"), 240, target);
821 m_config->updateOption("fpsTarget");
822
823#if defined(USE_PNG) || defined(USE_FFMPEG) || defined(USE_MAGICK)
824 avMenu->addSeparator();
825#endif
826
827#ifdef USE_PNG
828 QAction* screenshot = new QAction(tr("Take &screenshot"), avMenu);
829 screenshot->setShortcut(tr("F12"));
830 connect(screenshot, SIGNAL(triggered()), m_controller, SLOT(screenshot()));
831 m_gameActions.append(screenshot);
832 addControlledAction(avMenu, screenshot, "screenshot");
833#endif
834
835#ifdef USE_FFMPEG
836 QAction* recordOutput = new QAction(tr("Record output..."), avMenu);
837 recordOutput->setShortcut(tr("F11"));
838 connect(recordOutput, SIGNAL(triggered()), this, SLOT(openVideoWindow()));
839 addControlledAction(avMenu, recordOutput, "recordOutput");
840#endif
841
842#ifdef USE_MAGICK
843 QAction* recordGIF = new QAction(tr("Record GIF..."), avMenu);
844 recordGIF->setShortcut(tr("Shift+F11"));
845 connect(recordGIF, SIGNAL(triggered()), this, SLOT(openGIFWindow()));
846 addControlledAction(avMenu, recordGIF, "recordGIF");
847#endif
848
849 avMenu->addSeparator();
850 QMenu* videoLayers = avMenu->addMenu(tr("Video layers"));
851
852 for (int i = 0; i < 4; ++i) {
853 QAction* enableBg = new QAction(tr("Background %0").arg(i), videoLayers);
854 enableBg->setCheckable(true);
855 enableBg->setChecked(true);
856 connect(enableBg, &QAction::triggered, [this, i](bool enable) { m_controller->thread()->gba->video.renderer->disableBG[i] = !enable; });
857 m_gameActions.append(enableBg);
858 addControlledAction(videoLayers, enableBg, QString("enableBG%0").arg(i));
859 }
860
861 QAction* enableObj = new QAction(tr("OBJ (sprites)"), videoLayers);
862 enableObj->setCheckable(true);
863 enableObj->setChecked(true);
864 connect(enableObj, &QAction::triggered, [this](bool enable) { m_controller->thread()->gba->video.renderer->disableOBJ = !enable; });
865 m_gameActions.append(enableObj);
866 addControlledAction(videoLayers, enableObj, "enableOBJ");
867
868 QMenu* audioChannels = avMenu->addMenu(tr("Audio channels"));
869
870 for (int i = 0; i < 4; ++i) {
871 QAction* enableCh = new QAction(tr("Channel %0").arg(i + 1), audioChannels);
872 enableCh->setCheckable(true);
873 enableCh->setChecked(true);
874 connect(enableCh, &QAction::triggered, [this, i](bool enable) { m_controller->thread()->gba->audio.forceDisableCh[i] = !enable; });
875 m_gameActions.append(enableCh);
876 addControlledAction(audioChannels, enableCh, QString("enableCh%0").arg(i + 1));
877 }
878
879 QAction* enableChA = new QAction(tr("Channel A"), audioChannels);
880 enableChA->setCheckable(true);
881 enableChA->setChecked(true);
882 connect(enableChA, &QAction::triggered, [this, i](bool enable) { m_controller->thread()->gba->audio.forceDisableChA = !enable; });
883 m_gameActions.append(enableChA);
884 addControlledAction(audioChannels, enableChA, QString("enableChA"));
885
886 QAction* enableChB = new QAction(tr("Channel B"), audioChannels);
887 enableChB->setCheckable(true);
888 enableChB->setChecked(true);
889 connect(enableChB, &QAction::triggered, [this, i](bool enable) { m_controller->thread()->gba->audio.forceDisableChB = !enable; });
890 m_gameActions.append(enableChB);
891 addControlledAction(audioChannels, enableChB, QString("enableChB"));
892
893 QMenu* toolsMenu = menubar->addMenu(tr("&Tools"));
894 m_shortcutController->addMenu(toolsMenu);
895 QAction* viewLogs = new QAction(tr("View &logs..."), toolsMenu);
896 connect(viewLogs, SIGNAL(triggered()), m_logView, SLOT(show()));
897 addControlledAction(toolsMenu, viewLogs, "viewLogs");
898
899 QAction* overrides = new QAction(tr("Game &overrides..."), toolsMenu);
900 connect(overrides, SIGNAL(triggered()), this, SLOT(openOverrideWindow()));
901 addControlledAction(toolsMenu, overrides, "overrideWindow");
902
903 QAction* sensors = new QAction(tr("Game &Pak sensors..."), toolsMenu);
904 connect(sensors, SIGNAL(triggered()), this, SLOT(openSensorWindow()));
905 addControlledAction(toolsMenu, sensors, "sensorWindow");
906
907 QAction* cheats = new QAction(tr("&Cheats..."), toolsMenu);
908 connect(cheats, SIGNAL(triggered()), this, SLOT(openCheatsWindow()));
909 addControlledAction(toolsMenu, cheats, "cheatsWindow");
910
911#ifdef USE_GDB_STUB
912 QAction* gdbWindow = new QAction(tr("Start &GDB server..."), toolsMenu);
913 connect(gdbWindow, SIGNAL(triggered()), this, SLOT(gdbOpen()));
914 addControlledAction(toolsMenu, gdbWindow, "gdbWindow");
915#endif
916
917 toolsMenu->addSeparator();
918 addControlledAction(toolsMenu, toolsMenu->addAction(tr("Settings..."), this, SLOT(openSettingsWindow())), "settings");
919 addControlledAction(toolsMenu, toolsMenu->addAction(tr("Edit shortcuts..."), this, SLOT(openShortcutWindow())), "shortcuts");
920
921 QAction* keymap = new QAction(tr("Remap keyboard..."), toolsMenu);
922 connect(keymap, SIGNAL(triggered()), this, SLOT(openKeymapWindow()));
923 addControlledAction(toolsMenu, keymap, "remapKeyboard");
924
925#ifdef BUILD_SDL
926 QAction* gamepad = new QAction(tr("Remap gamepad..."), toolsMenu);
927 connect(gamepad, SIGNAL(triggered()), this, SLOT(openGamepadWindow()));
928 addControlledAction(toolsMenu, gamepad, "remapGamepad");
929#endif
930
931 toolsMenu->addSeparator();
932
933 QAction* paletteView = new QAction(tr("View &palette..."), toolsMenu);
934 connect(paletteView, SIGNAL(triggered()), this, SLOT(openPaletteWindow()));
935 m_gameActions.append(paletteView);
936 addControlledAction(toolsMenu, paletteView, "paletteWindow");
937
938 ConfigOption* skipBios = m_config->addOption("skipBios");
939 skipBios->connect([this](const QVariant& value) {
940 m_controller->setSkipBIOS(value.toBool());
941 }, this);
942
943 ConfigOption* volume = m_config->addOption("volume");
944 volume->connect([this](const QVariant& value) {
945 m_controller->setVolume(value.toInt());
946 }, this);
947
948 ConfigOption* mute = m_config->addOption("mute");
949 mute->connect([this](const QVariant& value) {
950 m_controller->setMute(value.toBool());
951 }, this);
952
953 ConfigOption* rewindEnable = m_config->addOption("rewindEnable");
954 rewindEnable->connect([this](const QVariant& value) {
955 m_controller->setRewind(value.toBool(), m_config->getOption("rewindBufferCapacity").toInt(), m_config->getOption("rewindBufferInterval").toInt());
956 }, this);
957
958 ConfigOption* rewindBufferCapacity = m_config->addOption("rewindBufferCapacity");
959 rewindBufferCapacity->connect([this](const QVariant& value) {
960 m_controller->setRewind(m_config->getOption("rewindEnable").toInt(), value.toInt(), m_config->getOption("rewindBufferInterval").toInt());
961 }, this);
962
963 ConfigOption* rewindBufferInterval = m_config->addOption("rewindBufferInterval");
964 rewindBufferInterval->connect([this](const QVariant& value) {
965 m_controller->setRewind(m_config->getOption("rewindEnable").toInt(), m_config->getOption("rewindBufferCapacity").toInt(), value.toInt());
966 }, this);
967
968 ConfigOption* allowOpposingDirections = m_config->addOption("allowOpposingDirections");
969 allowOpposingDirections->connect([this](const QVariant& value) {
970 m_inputController.setAllowOpposing(value.toBool());
971 }, this);
972
973 QMenu* other = new QMenu(tr("Other"), this);
974 m_shortcutController->addMenu(other);
975 m_shortcutController->addFunctions(other, [this]() {
976 m_controller->setTurbo(true, false);
977 }, [this]() {
978 m_controller->setTurbo(false, false);
979 }, QKeySequence(Qt::Key_Tab), tr("Fast Forward (held)"), "holdFastForward");
980
981 addControlledAction(other, other->addAction(tr("Exit fullscreen"), this, SLOT(exitFullScreen()), QKeySequence("Esc")), "exitFullScreen");
982
983 foreach (QAction* action, m_gameActions) {
984 action->setDisabled(true);
985 }
986}
987
988void Window::attachWidget(QWidget* widget) {
989 m_screenWidget->layout()->addWidget(widget);
990 static_cast<QStackedLayout*>(m_screenWidget->layout())->setCurrentWidget(widget);
991}
992
993void Window::detachWidget(QWidget* widget) {
994 m_screenWidget->layout()->removeWidget(widget);
995}
996
997void Window::appendMRU(const QString& fname) {
998 int index = m_mruFiles.indexOf(fname);
999 if (index >= 0) {
1000 m_mruFiles.removeAt(index);
1001 }
1002 m_mruFiles.prepend(fname);
1003 while (m_mruFiles.size() > ConfigController::MRU_LIST_SIZE) {
1004 m_mruFiles.removeLast();
1005 }
1006 updateMRU();
1007}
1008
1009void Window::updateMRU() {
1010 if (!m_mruMenu) {
1011 return;
1012 }
1013 m_mruMenu->clear();
1014 int i = 0;
1015 for (const QString& file : m_mruFiles) {
1016 QAction* item = new QAction(file, m_mruMenu);
1017 item->setShortcut(QString("Ctrl+%1").arg(i));
1018 connect(item, &QAction::triggered, [this, file]() { m_controller->loadGame(file); });
1019 m_mruMenu->addAction(item);
1020 ++i;
1021 }
1022 m_config->setMRU(m_mruFiles);
1023 m_config->write();
1024 m_mruMenu->setEnabled(i > 0);
1025}
1026
1027QAction* Window::addControlledAction(QMenu* menu, QAction* action, const QString& name) {
1028 m_shortcutController->addAction(menu, action, name);
1029 menu->addAction(action);
1030 action->setShortcutContext(Qt::WidgetShortcut);
1031 addAction(action);
1032 return action;
1033}
1034
1035WindowBackground::WindowBackground(QWidget* parent)
1036 : QLabel(parent)
1037{
1038 setLayout(new QStackedLayout());
1039 layout()->setContentsMargins(0, 0, 0, 0);
1040 setAlignment(Qt::AlignCenter);
1041}
1042
1043void WindowBackground::setSizeHint(const QSize& hint) {
1044 m_sizeHint = hint;
1045}
1046
1047QSize WindowBackground::sizeHint() const {
1048 return m_sizeHint;
1049}
1050
1051void WindowBackground::setLockAspectRatio(int width, int height) {
1052 m_aspectWidth = width;
1053 m_aspectHeight = height;
1054}
1055
1056void WindowBackground::paintEvent(QPaintEvent*) {
1057 const QPixmap* logo = pixmap();
1058 if (!logo) {
1059 return;
1060 }
1061 QPainter painter(this);
1062 painter.setRenderHint(QPainter::SmoothPixmapTransform);
1063 painter.fillRect(QRect(QPoint(), size()), Qt::black);
1064 QSize s = size();
1065 QSize ds = s;
1066 if (s.width() * m_aspectHeight > s.height() * m_aspectWidth) {
1067 ds.setWidth(s.height() * m_aspectWidth / m_aspectHeight);
1068 } else if (s.width() * m_aspectHeight < s.height() * m_aspectWidth) {
1069 ds.setHeight(s.width() * m_aspectHeight / m_aspectWidth);
1070 }
1071 QPoint origin = QPoint((s.width() - ds.width()) / 2, (s.height() - ds.height()) / 2);
1072 QRect full(origin, ds);
1073 painter.drawPixmap(full, *logo);
1074}