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