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