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