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