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(GBAThread*)), m_display, SLOT(startDrawing(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#ifdef BUILD_SDL
302 m_inputController.recalibrateAxes();
303#endif
304 ShortcutView* shortcutView = new ShortcutView();
305 shortcutView->setController(m_shortcutController);
306 openView(shortcutView);
307}
308
309void Window::openOverrideWindow() {
310 OverrideView* overrideWindow = new OverrideView(m_controller, m_config);
311 openView(overrideWindow);
312}
313
314void Window::openSensorWindow() {
315 SensorView* sensorWindow = new SensorView(m_controller);
316 openView(sensorWindow);
317}
318
319void Window::openCheatsWindow() {
320 CheatsView* cheatsWindow = new CheatsView(m_controller);
321 openView(cheatsWindow);
322}
323
324void Window::openPaletteWindow() {
325 PaletteView* paletteWindow = new PaletteView(m_controller);
326 openView(paletteWindow);
327}
328
329#ifdef BUILD_SDL
330void Window::openGamepadWindow() {
331 const char* profile = m_inputController.profileForType(SDL_BINDING_BUTTON);
332 GBAKeyEditor* keyEditor = new GBAKeyEditor(&m_inputController, SDL_BINDING_BUTTON, profile);
333 openView(keyEditor);
334}
335#endif
336
337#ifdef USE_FFMPEG
338void Window::openVideoWindow() {
339 if (!m_videoView) {
340 m_videoView = new VideoView();
341 connect(m_videoView, SIGNAL(recordingStarted(GBAAVStream*)), m_controller, SLOT(setAVStream(GBAAVStream*)));
342 connect(m_videoView, SIGNAL(recordingStopped()), m_controller, SLOT(clearAVStream()), Qt::DirectConnection);
343 connect(m_controller, SIGNAL(gameStopped(GBAThread*)), m_videoView, SLOT(stopRecording()));
344 connect(m_controller, SIGNAL(gameStopped(GBAThread*)), m_videoView, SLOT(close()));
345 connect(this, SIGNAL(shutdown()), m_videoView, SLOT(close()));
346 }
347 m_videoView->show();
348}
349#endif
350
351#ifdef USE_MAGICK
352void Window::openGIFWindow() {
353 if (!m_gifView) {
354 m_gifView = new GIFView();
355 connect(m_gifView, SIGNAL(recordingStarted(GBAAVStream*)), m_controller, SLOT(setAVStream(GBAAVStream*)));
356 connect(m_gifView, SIGNAL(recordingStopped()), m_controller, SLOT(clearAVStream()), Qt::DirectConnection);
357 connect(m_controller, SIGNAL(gameStopped(GBAThread*)), m_gifView, SLOT(stopRecording()));
358 connect(m_controller, SIGNAL(gameStopped(GBAThread*)), m_gifView, SLOT(close()));
359 connect(this, SIGNAL(shutdown()), m_gifView, SLOT(close()));
360 }
361 m_gifView->show();
362}
363#endif
364
365#ifdef USE_GDB_STUB
366void Window::gdbOpen() {
367 if (!m_gdbController) {
368 m_gdbController = new GDBController(m_controller, this);
369 }
370 GDBWindow* window = new GDBWindow(m_gdbController);
371 connect(this, SIGNAL(shutdown()), window, SLOT(close()));
372 window->setAttribute(Qt::WA_DeleteOnClose);
373 window->show();
374}
375#endif
376
377void Window::keyPressEvent(QKeyEvent* event) {
378 if (event->isAutoRepeat()) {
379 QWidget::keyPressEvent(event);
380 return;
381 }
382 GBAKey key = m_inputController.mapKeyboard(event->key());
383 if (key == GBA_KEY_NONE) {
384 QWidget::keyPressEvent(event);
385 return;
386 }
387 m_controller->keyPressed(key);
388 event->accept();
389}
390
391void Window::keyReleaseEvent(QKeyEvent* event) {
392 if (event->isAutoRepeat()) {
393 QWidget::keyReleaseEvent(event);
394 return;
395 }
396 GBAKey key = m_inputController.mapKeyboard(event->key());
397 if (key == GBA_KEY_NONE) {
398 QWidget::keyPressEvent(event);
399 return;
400 }
401 m_controller->keyReleased(key);
402 event->accept();
403}
404
405void Window::resizeEvent(QResizeEvent*) {
406 m_config->setOption("height", m_screenWidget->height());
407 m_config->setOption("width", m_screenWidget->width());
408 m_config->setOption("fullscreen", isFullScreen());
409}
410
411void Window::closeEvent(QCloseEvent* event) {
412 emit shutdown();
413 m_config->setQtOption("windowPos", pos());
414 QMainWindow::closeEvent(event);
415}
416
417void Window::focusOutEvent(QFocusEvent*) {
418 m_controller->setTurbo(false, false);
419 m_controller->clearKeys();
420}
421
422void Window::dragEnterEvent(QDragEnterEvent* event) {
423 if (event->mimeData()->hasFormat("text/uri-list")) {
424 event->acceptProposedAction();
425 }
426}
427
428void Window::dropEvent(QDropEvent* event) {
429 QString uris = event->mimeData()->data("text/uri-list");
430 uris = uris.trimmed();
431 if (uris.contains("\n")) {
432 // Only one file please
433 return;
434 }
435 QUrl url(uris);
436 if (!url.isLocalFile()) {
437 // No remote loading
438 return;
439 }
440 event->accept();
441 m_controller->loadGame(url.path());
442}
443
444void Window::mouseDoubleClickEvent(QMouseEvent* event) {
445 if (event->button() != Qt::LeftButton) {
446 return;
447 }
448 toggleFullScreen();
449}
450
451void Window::enterFullScreen() {
452 if (isFullScreen()) {
453 return;
454 }
455 showFullScreen();
456#ifndef Q_OS_MAC
457 if (m_controller->isLoaded() && !m_controller->isPaused()) {
458 menuBar()->hide();
459 }
460#endif
461}
462
463void Window::exitFullScreen() {
464 if (!isFullScreen()) {
465 return;
466 }
467 showNormal();
468 menuBar()->show();
469}
470
471void Window::toggleFullScreen() {
472 if (isFullScreen()) {
473 exitFullScreen();
474 } else {
475 enterFullScreen();
476 }
477}
478
479void Window::gameStarted(GBAThread* context) {
480 char title[13] = { '\0' };
481 MutexLock(&context->stateMutex);
482 if (context->state < THREAD_EXITING) {
483 emit startDrawing(context);
484 GBAGetGameTitle(context->gba, title);
485 } else {
486 MutexUnlock(&context->stateMutex);
487 return;
488 }
489 MutexUnlock(&context->stateMutex);
490 foreach (QAction* action, m_gameActions) {
491 action->setDisabled(false);
492 }
493 appendMRU(context->fname);
494 setWindowTitle(tr(PROJECT_NAME " - %1").arg(title));
495 attachWidget(m_display);
496
497#ifndef Q_OS_MAC
498 if(isFullScreen()) {
499 menuBar()->hide();
500 }
501#endif
502
503 m_hitUnimplementedBiosCall = false;
504 m_fpsTimer.start();
505}
506
507void Window::gameStopped() {
508 foreach (QAction* action, m_gameActions) {
509 action->setDisabled(true);
510 }
511 setWindowTitle(tr(PROJECT_NAME));
512 detachWidget(m_display);
513 m_screenWidget->setLockAspectRatio(m_logo.width(), m_logo.height());
514 m_screenWidget->setPixmap(m_logo);
515
516 m_fpsTimer.stop();
517}
518
519void Window::gameCrashed(const QString& errorMessage) {
520 QMessageBox* crash = new QMessageBox(QMessageBox::Critical, tr("Crash"),
521 tr("The game has crashed with the following error:\n\n%1").arg(errorMessage),
522 QMessageBox::Ok, this, Qt::Sheet);
523 crash->setAttribute(Qt::WA_DeleteOnClose);
524 crash->show();
525}
526
527void Window::gameFailed() {
528 QMessageBox* fail = new QMessageBox(QMessageBox::Warning, tr("Couldn't Load"),
529 tr("Could not load game. Are you sure it's in the correct format?"),
530 QMessageBox::Ok, this, Qt::Sheet);
531 fail->setAttribute(Qt::WA_DeleteOnClose);
532 fail->show();
533}
534
535void Window::unimplementedBiosCall(int call) {
536 if (m_hitUnimplementedBiosCall) {
537 return;
538 }
539 m_hitUnimplementedBiosCall = true;
540
541 QMessageBox* fail = new QMessageBox(QMessageBox::Warning, tr("Unimplemented BIOS call"),
542 tr("This game uses a BIOS call that is not implemented. Please use the official BIOS for best experience."),
543 QMessageBox::Ok, this, Qt::Sheet);
544 fail->setAttribute(Qt::WA_DeleteOnClose);
545 fail->show();
546}
547
548void Window::recordFrame() {
549 m_frameList.append(QDateTime::currentDateTime());
550 while (m_frameList.count() > FRAME_LIST_SIZE) {
551 m_frameList.removeFirst();
552 }
553}
554
555void Window::showFPS() {
556 char gameTitle[13] = { '\0' };
557 GBAGetGameTitle(m_controller->thread()->gba, gameTitle);
558
559 QString title(gameTitle);
560 std::shared_ptr<MultiplayerController> multiplayer = m_controller->multiplayerController();
561 if (multiplayer && multiplayer->attached() > 1) {
562 title += tr(" - Player %1 of %2").arg(m_playerId + 1).arg(multiplayer->attached());
563 }
564 if (m_frameList.isEmpty()) {
565 setWindowTitle(tr(PROJECT_NAME " - %1").arg(title));
566 return;
567 }
568 qint64 interval = m_frameList.first().msecsTo(m_frameList.last());
569 float fps = (m_frameList.count() - 1) * 10000.f / interval;
570 fps = round(fps) / 10.f;
571 setWindowTitle(tr(PROJECT_NAME " - %1 (%2 fps)").arg(title).arg(fps));
572}
573
574void Window::openStateWindow(LoadSave ls) {
575 if (m_stateWindow) {
576 return;
577 }
578 bool wasPaused = m_controller->isPaused();
579 m_stateWindow = new LoadSaveState(m_controller);
580 connect(this, SIGNAL(shutdown()), m_stateWindow, SLOT(close()));
581 connect(m_controller, SIGNAL(gameStopped(GBAThread*)), m_stateWindow, SLOT(close()));
582 connect(m_stateWindow, &LoadSaveState::closed, [this]() {
583 m_screenWidget->layout()->removeWidget(m_stateWindow);
584 m_stateWindow = nullptr;
585 QMetaObject::invokeMethod(this, "setFocus", Qt::QueuedConnection);
586 });
587 if (!wasPaused) {
588 m_controller->setPaused(true);
589 connect(m_stateWindow, &LoadSaveState::closed, [this]() { m_controller->setPaused(false); });
590 }
591 m_stateWindow->setAttribute(Qt::WA_DeleteOnClose);
592 m_stateWindow->setMode(ls);
593 attachWidget(m_stateWindow);
594}
595
596void Window::setupMenu(QMenuBar* menubar) {
597 menubar->clear();
598 QMenu* fileMenu = menubar->addMenu(tr("&File"));
599 m_shortcutController->addMenu(fileMenu);
600 installEventFilter(m_shortcutController);
601 addControlledAction(fileMenu, fileMenu->addAction(tr("Load &ROM..."), this, SLOT(selectROM()), QKeySequence::Open), "loadROM");
602 addControlledAction(fileMenu, fileMenu->addAction(tr("Load &BIOS..."), this, SLOT(selectBIOS())), "loadBIOS");
603 addControlledAction(fileMenu, fileMenu->addAction(tr("Load &patch..."), this, SLOT(selectPatch())), "loadPatch");
604
605 m_mruMenu = fileMenu->addMenu(tr("Recent"));
606
607 fileMenu->addSeparator();
608
609 QAction* loadState = new QAction(tr("&Load state"), fileMenu);
610 loadState->setShortcut(tr("F10"));
611 connect(loadState, &QAction::triggered, [this]() { this->openStateWindow(LoadSave::LOAD); });
612 m_gameActions.append(loadState);
613 addControlledAction(fileMenu, loadState, "loadState");
614
615 QAction* saveState = new QAction(tr("&Save state"), fileMenu);
616 saveState->setShortcut(tr("Shift+F10"));
617 connect(saveState, &QAction::triggered, [this]() { this->openStateWindow(LoadSave::SAVE); });
618 m_gameActions.append(saveState);
619 addControlledAction(fileMenu, saveState, "saveState");
620
621 QMenu* quickLoadMenu = fileMenu->addMenu(tr("Quick load"));
622 QMenu* quickSaveMenu = fileMenu->addMenu(tr("Quick save"));
623 m_shortcutController->addMenu(quickLoadMenu);
624 m_shortcutController->addMenu(quickSaveMenu);
625 int i;
626 for (i = 1; i < 10; ++i) {
627 QAction* quickLoad = new QAction(tr("State &%1").arg(i), quickLoadMenu);
628 quickLoad->setShortcut(tr("F%1").arg(i));
629 connect(quickLoad, &QAction::triggered, [this, i]() { m_controller->loadState(i); });
630 m_gameActions.append(quickLoad);
631 addControlledAction(quickLoadMenu, quickLoad, QString("quickLoad.%1").arg(i));
632
633 QAction* quickSave = new QAction(tr("State &%1").arg(i), quickSaveMenu);
634 quickSave->setShortcut(tr("Shift+F%1").arg(i));
635 connect(quickSave, &QAction::triggered, [this, i]() { m_controller->saveState(i); });
636 m_gameActions.append(quickSave);
637 addControlledAction(quickSaveMenu, quickSave, QString("quickSave.%1").arg(i));
638 }
639
640 fileMenu->addSeparator();
641 QAction* importShark = new QAction(tr("Import GameShark Save"), fileMenu);
642 connect(importShark, SIGNAL(triggered()), this, SLOT(importSharkport()));
643 m_gameActions.append(importShark);
644 addControlledAction(fileMenu, importShark, "importShark");
645
646 QAction* exportShark = new QAction(tr("Export GameShark Save"), fileMenu);
647 connect(exportShark, SIGNAL(triggered()), this, SLOT(exportSharkport()));
648 m_gameActions.append(exportShark);
649 addControlledAction(fileMenu, exportShark, "exportShark");
650
651 fileMenu->addSeparator();
652 QAction* multiWindow = new QAction(tr("New multiplayer window"), fileMenu);
653 connect(multiWindow, &QAction::triggered, [this]() {
654 std::shared_ptr<MultiplayerController> multiplayer = m_controller->multiplayerController();
655 if (!multiplayer) {
656 multiplayer = std::make_shared<MultiplayerController>();
657 m_controller->setMultiplayerController(multiplayer);
658 }
659 Window* w2 = new Window(m_config, multiplayer->attached());
660 w2->setAttribute(Qt::WA_DeleteOnClose);
661 w2->loadConfig();
662 w2->controller()->setMultiplayerController(multiplayer);
663 w2->show();
664 });
665 addControlledAction(fileMenu, multiWindow, "multiWindow");
666
667#ifndef Q_OS_MAC
668 addControlledAction(fileMenu, fileMenu->addAction(tr("E&xit"), this, SLOT(close()), QKeySequence::Quit), "quit");
669#endif
670
671 QMenu* emulationMenu = menubar->addMenu(tr("&Emulation"));
672 m_shortcutController->addMenu(emulationMenu);
673 QAction* reset = new QAction(tr("&Reset"), emulationMenu);
674 reset->setShortcut(tr("Ctrl+R"));
675 connect(reset, SIGNAL(triggered()), m_controller, SLOT(reset()));
676 m_gameActions.append(reset);
677 addControlledAction(emulationMenu, reset, "reset");
678
679 QAction* shutdown = new QAction(tr("Sh&utdown"), emulationMenu);
680 connect(shutdown, SIGNAL(triggered()), m_controller, SLOT(closeGame()));
681 m_gameActions.append(shutdown);
682 addControlledAction(emulationMenu, shutdown, "shutdown");
683 emulationMenu->addSeparator();
684
685 QAction* pause = new QAction(tr("&Pause"), emulationMenu);
686 pause->setChecked(false);
687 pause->setCheckable(true);
688 pause->setShortcut(tr("Ctrl+P"));
689 connect(pause, SIGNAL(triggered(bool)), m_controller, SLOT(setPaused(bool)));
690 connect(m_controller, &GameController::gamePaused, [this, pause]() {
691 pause->setChecked(true);
692
693 QImage currentImage(reinterpret_cast<const uchar*>(m_controller->drawContext()), VIDEO_HORIZONTAL_PIXELS, VIDEO_VERTICAL_PIXELS, 1024, QImage::Format_RGB32);
694 QPixmap pixmap;
695 pixmap.convertFromImage(currentImage.rgbSwapped());
696 m_screenWidget->setPixmap(pixmap);
697 m_screenWidget->setLockAspectRatio(3, 2);
698 });
699 connect(m_controller, &GameController::gameUnpaused, [pause]() { pause->setChecked(false); });
700 m_gameActions.append(pause);
701 addControlledAction(emulationMenu, pause, "pause");
702
703 QAction* frameAdvance = new QAction(tr("&Next frame"), emulationMenu);
704 frameAdvance->setShortcut(tr("Ctrl+N"));
705 connect(frameAdvance, SIGNAL(triggered()), m_controller, SLOT(frameAdvance()));
706 m_gameActions.append(frameAdvance);
707 addControlledAction(emulationMenu, frameAdvance, "frameAdvance");
708
709 emulationMenu->addSeparator();
710
711 QAction* turbo = new QAction(tr("&Fast forward"), emulationMenu);
712 turbo->setCheckable(true);
713 turbo->setChecked(false);
714 turbo->setShortcut(tr("Shift+Tab"));
715 connect(turbo, SIGNAL(triggered(bool)), m_controller, SLOT(setTurbo(bool)));
716 addControlledAction(emulationMenu, turbo, "fastForward");
717
718 QAction* rewind = new QAction(tr("Re&wind"), emulationMenu);
719 rewind->setShortcut(tr("`"));
720 connect(rewind, SIGNAL(triggered()), m_controller, SLOT(rewind()));
721 m_gameActions.append(rewind);
722 addControlledAction(emulationMenu, rewind, "rewind");
723
724 QAction* frameRewind = new QAction(tr("Step backwards"), emulationMenu);
725 frameRewind->setShortcut(tr("Ctrl+B"));
726 connect(frameRewind, &QAction::triggered, [this] () {
727 m_controller->rewind(1);
728 });
729 m_gameActions.append(frameRewind);
730 addControlledAction(emulationMenu, frameRewind, "frameRewind");
731
732 ConfigOption* videoSync = m_config->addOption("videoSync");
733 videoSync->addBoolean(tr("Sync to &video"), emulationMenu);
734 videoSync->connect([this](const QVariant& value) {
735 m_controller->setVideoSync(value.toBool());
736 }, this);
737 m_config->updateOption("videoSync");
738
739 ConfigOption* audioSync = m_config->addOption("audioSync");
740 audioSync->addBoolean(tr("Sync to &audio"), emulationMenu);
741 audioSync->connect([this](const QVariant& value) {
742 m_controller->setAudioSync(value.toBool());
743 }, this);
744 m_config->updateOption("audioSync");
745
746 emulationMenu->addSeparator();
747
748 QMenu* solarMenu = emulationMenu->addMenu(tr("Solar sensor"));
749 m_shortcutController->addMenu(solarMenu);
750 QAction* solarIncrease = new QAction(tr("Increase solar level"), solarMenu);
751 connect(solarIncrease, SIGNAL(triggered()), m_controller, SLOT(increaseLuminanceLevel()));
752 addControlledAction(solarMenu, solarIncrease, "increaseLuminanceLevel");
753
754 QAction* solarDecrease = new QAction(tr("Decrease solar level"), solarMenu);
755 connect(solarDecrease, SIGNAL(triggered()), m_controller, SLOT(decreaseLuminanceLevel()));
756 addControlledAction(solarMenu, solarDecrease, "decreaseLuminanceLevel");
757
758 QAction* maxSolar = new QAction(tr("Brightest solar level"), solarMenu);
759 connect(maxSolar, &QAction::triggered, [this]() { m_controller->setLuminanceLevel(10); });
760 addControlledAction(solarMenu, maxSolar, "maxLuminanceLevel");
761
762 QAction* minSolar = new QAction(tr("Darkest solar level"), solarMenu);
763 connect(minSolar, &QAction::triggered, [this]() { m_controller->setLuminanceLevel(0); });
764 addControlledAction(solarMenu, minSolar, "minLuminanceLevel");
765
766 solarMenu->addSeparator();
767 for (int i = 0; i <= 10; ++i) {
768 QAction* setSolar = new QAction(tr("Brightness %1").arg(QString::number(i)), solarMenu);
769 connect(setSolar, &QAction::triggered, [this, i]() {
770 m_controller->setLuminanceLevel(i);
771 });
772 addControlledAction(solarMenu, setSolar, QString("luminanceLevel.%1").arg(QString::number(i)));
773 }
774
775 QMenu* avMenu = menubar->addMenu(tr("Audio/&Video"));
776 m_shortcutController->addMenu(avMenu);
777 QMenu* frameMenu = avMenu->addMenu(tr("Frame size"));
778 m_shortcutController->addMenu(frameMenu, avMenu);
779 for (int i = 1; i <= 6; ++i) {
780 QAction* setSize = new QAction(tr("%1x").arg(QString::number(i)), avMenu);
781 connect(setSize, &QAction::triggered, [this, i]() {
782 showNormal();
783 resizeFrame(VIDEO_HORIZONTAL_PIXELS * i, VIDEO_VERTICAL_PIXELS * i);
784 });
785 addControlledAction(frameMenu, setSize, QString("frame%1x").arg(QString::number(i)));
786 }
787 addControlledAction(frameMenu, frameMenu->addAction(tr("Fullscreen"), this, SLOT(toggleFullScreen()), QKeySequence("Ctrl+F")), "fullscreen");
788
789 ConfigOption* lockAspectRatio = m_config->addOption("lockAspectRatio");
790 lockAspectRatio->addBoolean(tr("Lock aspect ratio"), avMenu);
791 lockAspectRatio->connect([this](const QVariant& value) {
792 m_display->lockAspectRatio(value.toBool());
793 }, this);
794 m_config->updateOption("lockAspectRatio");
795
796 ConfigOption* resampleVideo = m_config->addOption("resampleVideo");
797 resampleVideo->addBoolean(tr("Resample video"), avMenu);
798 resampleVideo->connect([this](const QVariant& value) {
799 m_display->filter(value.toBool());
800 }, this);
801 m_config->updateOption("resampleVideo");
802
803 QMenu* skipMenu = avMenu->addMenu(tr("Frame&skip"));
804 ConfigOption* skip = m_config->addOption("frameskip");
805 skip->connect([this](const QVariant& value) {
806 m_controller->setFrameskip(value.toInt());
807 }, this);
808 for (int i = 0; i <= 10; ++i) {
809 skip->addValue(QString::number(i), i, skipMenu);
810 }
811 m_config->updateOption("frameskip");
812
813 avMenu->addSeparator();
814
815 QMenu* buffersMenu = avMenu->addMenu(tr("Audio buffer &size"));
816 ConfigOption* buffers = m_config->addOption("audioBuffers");
817 buffers->connect([this](const QVariant& value) {
818 emit audioBufferSamplesChanged(value.toInt());
819 }, this);
820 buffers->addValue(tr("512"), 512, buffersMenu);
821 buffers->addValue(tr("768"), 768, buffersMenu);
822 buffers->addValue(tr("1024"), 1024, buffersMenu);
823 buffers->addValue(tr("2048"), 2048, buffersMenu);
824 buffers->addValue(tr("4096"), 4096, buffersMenu);
825 m_config->updateOption("audioBuffers");
826
827 avMenu->addSeparator();
828
829 QMenu* target = avMenu->addMenu(tr("FPS target"));
830 ConfigOption* fpsTargetOption = m_config->addOption("fpsTarget");
831 fpsTargetOption->connect([this](const QVariant& value) {
832 emit fpsTargetChanged(value.toFloat());
833 }, this);
834 fpsTargetOption->addValue(tr("15"), 15, target);
835 fpsTargetOption->addValue(tr("30"), 30, target);
836 fpsTargetOption->addValue(tr("45"), 45, target);
837 fpsTargetOption->addValue(tr("Native (59.7)"), float(GBA_ARM7TDMI_FREQUENCY) / float(VIDEO_TOTAL_LENGTH), target);
838 fpsTargetOption->addValue(tr("60"), 60, target);
839 fpsTargetOption->addValue(tr("90"), 90, target);
840 fpsTargetOption->addValue(tr("120"), 120, target);
841 fpsTargetOption->addValue(tr("240"), 240, target);
842 m_config->updateOption("fpsTarget");
843
844#if defined(USE_PNG) || defined(USE_FFMPEG) || defined(USE_MAGICK)
845 avMenu->addSeparator();
846#endif
847
848#ifdef USE_PNG
849 QAction* screenshot = new QAction(tr("Take &screenshot"), avMenu);
850 screenshot->setShortcut(tr("F12"));
851 connect(screenshot, SIGNAL(triggered()), m_controller, SLOT(screenshot()));
852 m_gameActions.append(screenshot);
853 addControlledAction(avMenu, screenshot, "screenshot");
854#endif
855
856#ifdef USE_FFMPEG
857 QAction* recordOutput = new QAction(tr("Record output..."), avMenu);
858 recordOutput->setShortcut(tr("F11"));
859 connect(recordOutput, SIGNAL(triggered()), this, SLOT(openVideoWindow()));
860 addControlledAction(avMenu, recordOutput, "recordOutput");
861#endif
862
863#ifdef USE_MAGICK
864 QAction* recordGIF = new QAction(tr("Record GIF..."), avMenu);
865 recordGIF->setShortcut(tr("Shift+F11"));
866 connect(recordGIF, SIGNAL(triggered()), this, SLOT(openGIFWindow()));
867 addControlledAction(avMenu, recordGIF, "recordGIF");
868#endif
869
870 avMenu->addSeparator();
871 QMenu* videoLayers = avMenu->addMenu(tr("Video layers"));
872
873 for (int i = 0; i < 4; ++i) {
874 QAction* enableBg = new QAction(tr("Background %0").arg(i), videoLayers);
875 enableBg->setCheckable(true);
876 enableBg->setChecked(true);
877 connect(enableBg, &QAction::triggered, [this, i](bool enable) { m_controller->thread()->gba->video.renderer->disableBG[i] = !enable; });
878 m_gameActions.append(enableBg);
879 addControlledAction(videoLayers, enableBg, QString("enableBG%0").arg(i));
880 }
881
882 QAction* enableObj = new QAction(tr("OBJ (sprites)"), videoLayers);
883 enableObj->setCheckable(true);
884 enableObj->setChecked(true);
885 connect(enableObj, &QAction::triggered, [this](bool enable) { m_controller->thread()->gba->video.renderer->disableOBJ = !enable; });
886 m_gameActions.append(enableObj);
887 addControlledAction(videoLayers, enableObj, "enableOBJ");
888
889 QMenu* audioChannels = avMenu->addMenu(tr("Audio channels"));
890
891 for (int i = 0; i < 4; ++i) {
892 QAction* enableCh = new QAction(tr("Channel %0").arg(i + 1), audioChannels);
893 enableCh->setCheckable(true);
894 enableCh->setChecked(true);
895 connect(enableCh, &QAction::triggered, [this, i](bool enable) { m_controller->thread()->gba->audio.forceDisableCh[i] = !enable; });
896 m_gameActions.append(enableCh);
897 addControlledAction(audioChannels, enableCh, QString("enableCh%0").arg(i + 1));
898 }
899
900 QAction* enableChA = new QAction(tr("Channel A"), audioChannels);
901 enableChA->setCheckable(true);
902 enableChA->setChecked(true);
903 connect(enableChA, &QAction::triggered, [this, i](bool enable) { m_controller->thread()->gba->audio.forceDisableChA = !enable; });
904 m_gameActions.append(enableChA);
905 addControlledAction(audioChannels, enableChA, QString("enableChA"));
906
907 QAction* enableChB = new QAction(tr("Channel B"), audioChannels);
908 enableChB->setCheckable(true);
909 enableChB->setChecked(true);
910 connect(enableChB, &QAction::triggered, [this, i](bool enable) { m_controller->thread()->gba->audio.forceDisableChB = !enable; });
911 m_gameActions.append(enableChB);
912 addControlledAction(audioChannels, enableChB, QString("enableChB"));
913
914 QMenu* toolsMenu = menubar->addMenu(tr("&Tools"));
915 m_shortcutController->addMenu(toolsMenu);
916 QAction* viewLogs = new QAction(tr("View &logs..."), toolsMenu);
917 connect(viewLogs, SIGNAL(triggered()), m_logView, SLOT(show()));
918 addControlledAction(toolsMenu, viewLogs, "viewLogs");
919
920 QAction* overrides = new QAction(tr("Game &overrides..."), toolsMenu);
921 connect(overrides, SIGNAL(triggered()), this, SLOT(openOverrideWindow()));
922 addControlledAction(toolsMenu, overrides, "overrideWindow");
923
924 QAction* sensors = new QAction(tr("Game &Pak sensors..."), toolsMenu);
925 connect(sensors, SIGNAL(triggered()), this, SLOT(openSensorWindow()));
926 addControlledAction(toolsMenu, sensors, "sensorWindow");
927
928 QAction* cheats = new QAction(tr("&Cheats..."), toolsMenu);
929 connect(cheats, SIGNAL(triggered()), this, SLOT(openCheatsWindow()));
930 addControlledAction(toolsMenu, cheats, "cheatsWindow");
931
932#ifdef USE_GDB_STUB
933 QAction* gdbWindow = new QAction(tr("Start &GDB server..."), toolsMenu);
934 connect(gdbWindow, SIGNAL(triggered()), this, SLOT(gdbOpen()));
935 addControlledAction(toolsMenu, gdbWindow, "gdbWindow");
936#endif
937
938 toolsMenu->addSeparator();
939 addControlledAction(toolsMenu, toolsMenu->addAction(tr("Settings..."), this, SLOT(openSettingsWindow())), "settings");
940 addControlledAction(toolsMenu, toolsMenu->addAction(tr("Edit shortcuts..."), this, SLOT(openShortcutWindow())), "shortcuts");
941
942 QAction* keymap = new QAction(tr("Remap keyboard..."), toolsMenu);
943 connect(keymap, SIGNAL(triggered()), this, SLOT(openKeymapWindow()));
944 addControlledAction(toolsMenu, keymap, "remapKeyboard");
945
946#ifdef BUILD_SDL
947 QAction* gamepad = new QAction(tr("Remap gamepad..."), toolsMenu);
948 connect(gamepad, SIGNAL(triggered()), this, SLOT(openGamepadWindow()));
949 addControlledAction(toolsMenu, gamepad, "remapGamepad");
950#endif
951
952 toolsMenu->addSeparator();
953
954 QAction* paletteView = new QAction(tr("View &palette..."), toolsMenu);
955 connect(paletteView, SIGNAL(triggered()), this, SLOT(openPaletteWindow()));
956 m_gameActions.append(paletteView);
957 addControlledAction(toolsMenu, paletteView, "paletteWindow");
958
959 ConfigOption* skipBios = m_config->addOption("skipBios");
960 skipBios->connect([this](const QVariant& value) {
961 m_controller->setSkipBIOS(value.toBool());
962 }, this);
963
964 ConfigOption* volume = m_config->addOption("volume");
965 volume->connect([this](const QVariant& value) {
966 m_controller->setVolume(value.toInt());
967 }, this);
968
969 ConfigOption* mute = m_config->addOption("mute");
970 mute->connect([this](const QVariant& value) {
971 m_controller->setMute(value.toBool());
972 }, this);
973
974 ConfigOption* rewindEnable = m_config->addOption("rewindEnable");
975 rewindEnable->connect([this](const QVariant& value) {
976 m_controller->setRewind(value.toBool(), m_config->getOption("rewindBufferCapacity").toInt(), m_config->getOption("rewindBufferInterval").toInt());
977 }, this);
978
979 ConfigOption* rewindBufferCapacity = m_config->addOption("rewindBufferCapacity");
980 rewindBufferCapacity->connect([this](const QVariant& value) {
981 m_controller->setRewind(m_config->getOption("rewindEnable").toInt(), value.toInt(), m_config->getOption("rewindBufferInterval").toInt());
982 }, this);
983
984 ConfigOption* rewindBufferInterval = m_config->addOption("rewindBufferInterval");
985 rewindBufferInterval->connect([this](const QVariant& value) {
986 m_controller->setRewind(m_config->getOption("rewindEnable").toInt(), m_config->getOption("rewindBufferCapacity").toInt(), value.toInt());
987 }, this);
988
989 ConfigOption* allowOpposingDirections = m_config->addOption("allowOpposingDirections");
990 allowOpposingDirections->connect([this](const QVariant& value) {
991 m_inputController.setAllowOpposing(value.toBool());
992 }, this);
993
994 QMenu* other = new QMenu(tr("Other"), this);
995 m_shortcutController->addMenu(other);
996 m_shortcutController->addFunctions(other, [this]() {
997 m_controller->setTurbo(true, false);
998 }, [this]() {
999 m_controller->setTurbo(false, false);
1000 }, QKeySequence(Qt::Key_Tab), tr("Fast Forward (held)"), "holdFastForward");
1001
1002 addControlledAction(other, other->addAction(tr("Exit fullscreen"), this, SLOT(exitFullScreen()), QKeySequence("Esc")), "exitFullScreen");
1003
1004 foreach (QAction* action, m_gameActions) {
1005 action->setDisabled(true);
1006 }
1007}
1008
1009void Window::attachWidget(QWidget* widget) {
1010 m_screenWidget->layout()->addWidget(widget);
1011 static_cast<QStackedLayout*>(m_screenWidget->layout())->setCurrentWidget(widget);
1012}
1013
1014void Window::detachWidget(QWidget* widget) {
1015 m_screenWidget->layout()->removeWidget(widget);
1016}
1017
1018void Window::appendMRU(const QString& fname) {
1019 int index = m_mruFiles.indexOf(fname);
1020 if (index >= 0) {
1021 m_mruFiles.removeAt(index);
1022 }
1023 m_mruFiles.prepend(fname);
1024 while (m_mruFiles.size() > ConfigController::MRU_LIST_SIZE) {
1025 m_mruFiles.removeLast();
1026 }
1027 updateMRU();
1028}
1029
1030void Window::updateMRU() {
1031 if (!m_mruMenu) {
1032 return;
1033 }
1034 m_mruMenu->clear();
1035 int i = 0;
1036 for (const QString& file : m_mruFiles) {
1037 QAction* item = new QAction(file, m_mruMenu);
1038 item->setShortcut(QString("Ctrl+%1").arg(i));
1039 connect(item, &QAction::triggered, [this, file]() { m_controller->loadGame(file); });
1040 m_mruMenu->addAction(item);
1041 ++i;
1042 }
1043 m_config->setMRU(m_mruFiles);
1044 m_config->write();
1045 m_mruMenu->setEnabled(i > 0);
1046}
1047
1048QAction* Window::addControlledAction(QMenu* menu, QAction* action, const QString& name) {
1049 m_shortcutController->addAction(menu, action, name);
1050 menu->addAction(action);
1051 action->setShortcutContext(Qt::WidgetShortcut);
1052 addAction(action);
1053 return action;
1054}
1055
1056WindowBackground::WindowBackground(QWidget* parent)
1057 : QLabel(parent)
1058{
1059 setLayout(new QStackedLayout());
1060 layout()->setContentsMargins(0, 0, 0, 0);
1061 setAlignment(Qt::AlignCenter);
1062}
1063
1064void WindowBackground::setSizeHint(const QSize& hint) {
1065 m_sizeHint = hint;
1066}
1067
1068QSize WindowBackground::sizeHint() const {
1069 return m_sizeHint;
1070}
1071
1072void WindowBackground::setLockAspectRatio(int width, int height) {
1073 m_aspectWidth = width;
1074 m_aspectHeight = height;
1075}
1076
1077void WindowBackground::paintEvent(QPaintEvent*) {
1078 const QPixmap* logo = pixmap();
1079 if (!logo) {
1080 return;
1081 }
1082 QPainter painter(this);
1083 painter.setRenderHint(QPainter::SmoothPixmapTransform);
1084 painter.fillRect(QRect(QPoint(), size()), Qt::black);
1085 QSize s = size();
1086 QSize ds = s;
1087 if (s.width() * m_aspectHeight > s.height() * m_aspectWidth) {
1088 ds.setWidth(s.height() * m_aspectWidth / m_aspectHeight);
1089 } else if (s.width() * m_aspectHeight < s.height() * m_aspectWidth) {
1090 ds.setHeight(s.width() * m_aspectHeight / m_aspectWidth);
1091 }
1092 QPoint origin = QPoint((s.width() - ds.width()) / 2, (s.height() - ds.height()) / 2);
1093 QRect full(origin, ds);
1094 painter.drawPixmap(full, *logo);
1095}