all repos — mgba @ 2a9a738bfb76d540f39d8145d014170d8b095f52

mGBA Game Boy Advance Emulator

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 gameTitle[13] = { '\0' };
 523	GBAGetGameTitle(m_controller->thread()->gba, gameTitle);
 524
 525	QString title(gameTitle);
 526	std::shared_ptr<MultiplayerController> multiplayer = m_controller->multiplayerController();
 527	if (multiplayer && multiplayer->attached() > 1) {
 528		title += tr(" -  Player %1 of %2").arg(m_playerId + 1).arg(multiplayer->attached());
 529	}
 530	if (m_frameList.isEmpty()) {
 531		setWindowTitle(tr(PROJECT_NAME " - %1").arg(title));
 532		return;
 533	}
 534	qint64 interval = m_frameList.first().msecsTo(m_frameList.last());
 535	float fps = (m_frameList.count() - 1) * 10000.f / interval;
 536	fps = round(fps) / 10.f;
 537	setWindowTitle(tr(PROJECT_NAME " - %1 (%2 fps)").arg(title).arg(fps));
 538}
 539
 540void Window::openStateWindow(LoadSave ls) {
 541	if (m_stateWindow) {
 542		return;
 543	}
 544	bool wasPaused = m_controller->isPaused();
 545	m_stateWindow = new LoadSaveState(m_controller);
 546	connect(this, SIGNAL(shutdown()), m_stateWindow, SLOT(close()));
 547	connect(m_controller, SIGNAL(gameStopped(GBAThread*)), m_stateWindow, SLOT(close()));
 548	connect(m_stateWindow, &LoadSaveState::closed, [this]() {
 549		m_screenWidget->layout()->removeWidget(m_stateWindow);
 550		m_stateWindow = nullptr;
 551		QMetaObject::invokeMethod(this, "setFocus", Qt::QueuedConnection);
 552	});
 553	if (!wasPaused) {
 554		m_controller->setPaused(true);
 555		connect(m_stateWindow, &LoadSaveState::closed, [this]() { m_controller->setPaused(false); });
 556	}
 557	m_stateWindow->setAttribute(Qt::WA_DeleteOnClose);
 558	m_stateWindow->setMode(ls);
 559	attachWidget(m_stateWindow);
 560}
 561
 562void Window::setupMenu(QMenuBar* menubar) {
 563	menubar->clear();
 564	QMenu* fileMenu = menubar->addMenu(tr("&File"));
 565	m_shortcutController->addMenu(fileMenu);
 566	installEventFilter(m_shortcutController);
 567	addControlledAction(fileMenu, fileMenu->addAction(tr("Load &ROM..."), this, SLOT(selectROM()), QKeySequence::Open), "loadROM");
 568	addControlledAction(fileMenu, fileMenu->addAction(tr("Load &BIOS..."), this, SLOT(selectBIOS())), "loadBIOS");
 569	addControlledAction(fileMenu, fileMenu->addAction(tr("Load &patch..."), this, SLOT(selectPatch())), "loadPatch");
 570
 571	m_mruMenu = fileMenu->addMenu(tr("Recent"));
 572
 573	fileMenu->addSeparator();
 574
 575	QAction* loadState = new QAction(tr("&Load state"), fileMenu);
 576	loadState->setShortcut(tr("F10"));
 577	connect(loadState, &QAction::triggered, [this]() { this->openStateWindow(LoadSave::LOAD); });
 578	m_gameActions.append(loadState);
 579	addControlledAction(fileMenu, loadState, "loadState");
 580
 581	QAction* saveState = new QAction(tr("&Save state"), fileMenu);
 582	saveState->setShortcut(tr("Shift+F10"));
 583	connect(saveState, &QAction::triggered, [this]() { this->openStateWindow(LoadSave::SAVE); });
 584	m_gameActions.append(saveState);
 585	addControlledAction(fileMenu, saveState, "saveState");
 586
 587	QMenu* quickLoadMenu = fileMenu->addMenu(tr("Quick load"));
 588	QMenu* quickSaveMenu = fileMenu->addMenu(tr("Quick save"));
 589	m_shortcutController->addMenu(quickLoadMenu);
 590	m_shortcutController->addMenu(quickSaveMenu);
 591	int i;
 592	for (i = 1; i < 10; ++i) {
 593		QAction* quickLoad = new QAction(tr("State &%1").arg(i), quickLoadMenu);
 594		quickLoad->setShortcut(tr("F%1").arg(i));
 595		connect(quickLoad, &QAction::triggered, [this, i]() { m_controller->loadState(i); });
 596		m_gameActions.append(quickLoad);
 597		addControlledAction(quickLoadMenu, quickLoad, QString("quickLoad.%1").arg(i));
 598
 599		QAction* quickSave = new QAction(tr("State &%1").arg(i), quickSaveMenu);
 600		quickSave->setShortcut(tr("Shift+F%1").arg(i));
 601		connect(quickSave, &QAction::triggered, [this, i]() { m_controller->saveState(i); });
 602		m_gameActions.append(quickSave);
 603		addControlledAction(quickSaveMenu, quickSave, QString("quickSave.%1").arg(i));
 604	}
 605
 606	fileMenu->addSeparator();
 607	QAction* multiWindow = new QAction(tr("New multiplayer window"), fileMenu);
 608	connect(multiWindow, &QAction::triggered, [this]() {
 609		std::shared_ptr<MultiplayerController> multiplayer = m_controller->multiplayerController();
 610		if (!multiplayer) {
 611			multiplayer = std::make_shared<MultiplayerController>();
 612			m_controller->setMultiplayerController(multiplayer);
 613		}
 614		Window* w2 = new Window(m_config, multiplayer->attached());
 615		w2->setAttribute(Qt::WA_DeleteOnClose);
 616		w2->loadConfig();
 617		w2->controller()->setMultiplayerController(multiplayer);
 618		w2->show();
 619	});
 620	addControlledAction(fileMenu, multiWindow, "multiWindow");
 621
 622#ifndef Q_OS_MAC
 623	addControlledAction(fileMenu, fileMenu->addAction(tr("E&xit"), this, SLOT(close()), QKeySequence::Quit), "quit");
 624#endif
 625
 626	QMenu* emulationMenu = menubar->addMenu(tr("&Emulation"));
 627	m_shortcutController->addMenu(emulationMenu);
 628	QAction* reset = new QAction(tr("&Reset"), emulationMenu);
 629	reset->setShortcut(tr("Ctrl+R"));
 630	connect(reset, SIGNAL(triggered()), m_controller, SLOT(reset()));
 631	m_gameActions.append(reset);
 632	addControlledAction(emulationMenu, reset, "reset");
 633
 634	QAction* shutdown = new QAction(tr("Sh&utdown"), emulationMenu);
 635	connect(shutdown, SIGNAL(triggered()), m_controller, SLOT(closeGame()));
 636	m_gameActions.append(shutdown);
 637	addControlledAction(emulationMenu, shutdown, "shutdown");
 638	emulationMenu->addSeparator();
 639
 640	QAction* pause = new QAction(tr("&Pause"), emulationMenu);
 641	pause->setChecked(false);
 642	pause->setCheckable(true);
 643	pause->setShortcut(tr("Ctrl+P"));
 644	connect(pause, SIGNAL(triggered(bool)), m_controller, SLOT(setPaused(bool)));
 645	connect(m_controller, &GameController::gamePaused, [this, pause]() {
 646		pause->setChecked(true);
 647
 648		QImage currentImage(reinterpret_cast<const uchar*>(m_controller->drawContext()), VIDEO_HORIZONTAL_PIXELS, VIDEO_VERTICAL_PIXELS, 1024, QImage::Format_RGB32);
 649		QPixmap pixmap;
 650		pixmap.convertFromImage(currentImage.rgbSwapped());
 651		m_screenWidget->setPixmap(pixmap);
 652		m_screenWidget->setLockAspectRatio(3, 2);
 653	});
 654	connect(m_controller, &GameController::gameUnpaused, [pause]() { pause->setChecked(false); });
 655	m_gameActions.append(pause);
 656	addControlledAction(emulationMenu, pause, "pause");
 657
 658	QAction* frameAdvance = new QAction(tr("&Next frame"), emulationMenu);
 659	frameAdvance->setShortcut(tr("Ctrl+N"));
 660	connect(frameAdvance, SIGNAL(triggered()), m_controller, SLOT(frameAdvance()));
 661	m_gameActions.append(frameAdvance);
 662	addControlledAction(emulationMenu, frameAdvance, "frameAdvance");
 663
 664	emulationMenu->addSeparator();
 665
 666	QAction* turbo = new QAction(tr("&Fast forward"), emulationMenu);
 667	turbo->setCheckable(true);
 668	turbo->setChecked(false);
 669	turbo->setShortcut(tr("Shift+Tab"));
 670	connect(turbo, SIGNAL(triggered(bool)), m_controller, SLOT(setTurbo(bool)));
 671	addControlledAction(emulationMenu, turbo, "fastForward");
 672
 673	QAction* rewind = new QAction(tr("Re&wind"), emulationMenu);
 674	rewind->setShortcut(tr("`"));
 675	connect(rewind, SIGNAL(triggered()), m_controller, SLOT(rewind()));
 676	m_gameActions.append(rewind);
 677	addControlledAction(emulationMenu, rewind, "rewind");
 678
 679	ConfigOption* videoSync = m_config->addOption("videoSync");
 680	videoSync->addBoolean(tr("Sync to &video"), emulationMenu);
 681	videoSync->connect([this](const QVariant& value) {
 682		m_controller->setVideoSync(value.toBool());
 683	}, this);
 684	m_config->updateOption("videoSync");
 685
 686	ConfigOption* audioSync = m_config->addOption("audioSync");
 687	audioSync->addBoolean(tr("Sync to &audio"), emulationMenu);
 688	audioSync->connect([this](const QVariant& value) {
 689		m_controller->setAudioSync(value.toBool());
 690	}, this);
 691	m_config->updateOption("audioSync");
 692
 693	emulationMenu->addSeparator();
 694
 695	QMenu* solarMenu = emulationMenu->addMenu(tr("Solar sensor"));
 696	m_shortcutController->addMenu(solarMenu);
 697	QAction* solarIncrease = new QAction(tr("Increase solar level"), solarMenu);
 698	connect(solarIncrease, SIGNAL(triggered()), m_controller, SLOT(increaseLuminanceLevel()));
 699	addControlledAction(solarMenu, solarIncrease, "increaseLuminanceLevel");
 700
 701	QAction* solarDecrease = new QAction(tr("Decrease solar level"), solarMenu);
 702	connect(solarDecrease, SIGNAL(triggered()), m_controller, SLOT(decreaseLuminanceLevel()));
 703	addControlledAction(solarMenu, solarDecrease, "decreaseLuminanceLevel");
 704
 705	QAction* maxSolar = new QAction(tr("Brightest solar level"), solarMenu);
 706	connect(maxSolar, &QAction::triggered, [this]() { m_controller->setLuminanceLevel(10); });
 707	addControlledAction(solarMenu, maxSolar, "maxLuminanceLevel");
 708
 709	QAction* minSolar = new QAction(tr("Darkest solar level"), solarMenu);
 710	connect(minSolar, &QAction::triggered, [this]() { m_controller->setLuminanceLevel(0); });
 711	addControlledAction(solarMenu, minSolar, "minLuminanceLevel");
 712
 713	QMenu* avMenu = menubar->addMenu(tr("Audio/&Video"));
 714	m_shortcutController->addMenu(avMenu);
 715	QMenu* frameMenu = avMenu->addMenu(tr("Frame size"));
 716	m_shortcutController->addMenu(frameMenu, avMenu);
 717	for (int i = 1; i <= 6; ++i) {
 718		QAction* setSize = new QAction(tr("%1x").arg(QString::number(i)), avMenu);
 719		connect(setSize, &QAction::triggered, [this, i]() {
 720			showNormal();
 721			resizeFrame(VIDEO_HORIZONTAL_PIXELS * i, VIDEO_VERTICAL_PIXELS * i);
 722		});
 723		addControlledAction(frameMenu, setSize, QString("frame%1x").arg(QString::number(i)));
 724	}
 725	addControlledAction(frameMenu, frameMenu->addAction(tr("Fullscreen"), this, SLOT(toggleFullScreen()), QKeySequence("Ctrl+F")), "fullscreen");
 726
 727	ConfigOption* lockAspectRatio = m_config->addOption("lockAspectRatio");
 728	lockAspectRatio->addBoolean(tr("Lock aspect ratio"), avMenu);
 729	lockAspectRatio->connect([this](const QVariant& value) {
 730		m_display->lockAspectRatio(value.toBool());
 731	}, this);
 732	m_config->updateOption("lockAspectRatio");
 733
 734	ConfigOption* resampleVideo = m_config->addOption("resampleVideo");
 735	resampleVideo->addBoolean(tr("Resample video"), avMenu);
 736	resampleVideo->connect([this](const QVariant& value) {
 737		m_display->filter(value.toBool());
 738	}, this);
 739	m_config->updateOption("resampleVideo");
 740
 741	QMenu* skipMenu = avMenu->addMenu(tr("Frame&skip"));
 742	ConfigOption* skip = m_config->addOption("frameskip");
 743	skip->connect([this](const QVariant& value) {
 744		m_controller->setFrameskip(value.toInt());
 745	}, this);
 746	for (int i = 0; i <= 10; ++i) {
 747		skip->addValue(QString::number(i), i, skipMenu);
 748	}
 749	m_config->updateOption("frameskip");
 750
 751	avMenu->addSeparator();
 752
 753	QMenu* buffersMenu = avMenu->addMenu(tr("Audio buffer &size"));
 754	ConfigOption* buffers = m_config->addOption("audioBuffers");
 755	buffers->connect([this](const QVariant& value) {
 756		emit audioBufferSamplesChanged(value.toInt());
 757	}, this);
 758	buffers->addValue(tr("512"), 512, buffersMenu);
 759	buffers->addValue(tr("768"), 768, buffersMenu);
 760	buffers->addValue(tr("1024"), 1024, buffersMenu);
 761	buffers->addValue(tr("2048"), 2048, buffersMenu);
 762	buffers->addValue(tr("4096"), 4096, buffersMenu);
 763	m_config->updateOption("audioBuffers");
 764
 765	avMenu->addSeparator();
 766
 767	QMenu* target = avMenu->addMenu(tr("FPS target"));
 768	ConfigOption* fpsTargetOption = m_config->addOption("fpsTarget");
 769	fpsTargetOption->connect([this](const QVariant& value) {
 770		emit fpsTargetChanged(value.toInt());
 771	}, this);
 772	fpsTargetOption->addValue(tr("15"), 15, target);
 773	fpsTargetOption->addValue(tr("30"), 30, target);
 774	fpsTargetOption->addValue(tr("45"), 45, target);
 775	fpsTargetOption->addValue(tr("60"), 60, target);
 776	fpsTargetOption->addValue(tr("90"), 90, target);
 777	fpsTargetOption->addValue(tr("120"), 120, target);
 778	fpsTargetOption->addValue(tr("240"), 240, target);
 779	m_config->updateOption("fpsTarget");
 780
 781#if defined(USE_PNG) || defined(USE_FFMPEG) || defined(USE_MAGICK)
 782	avMenu->addSeparator();
 783#endif
 784
 785#ifdef USE_PNG
 786	QAction* screenshot = new QAction(tr("Take &screenshot"), avMenu);
 787	screenshot->setShortcut(tr("F12"));
 788	connect(screenshot, SIGNAL(triggered()), m_controller, SLOT(screenshot()));
 789	m_gameActions.append(screenshot);
 790	addControlledAction(avMenu, screenshot, "screenshot");
 791#endif
 792
 793#ifdef USE_FFMPEG
 794	QAction* recordOutput = new QAction(tr("Record output..."), avMenu);
 795	recordOutput->setShortcut(tr("F11"));
 796	connect(recordOutput, SIGNAL(triggered()), this, SLOT(openVideoWindow()));
 797	addControlledAction(avMenu, recordOutput, "recordOutput");
 798#endif
 799
 800#ifdef USE_MAGICK
 801	QAction* recordGIF = new QAction(tr("Record GIF..."), avMenu);
 802	recordGIF->setShortcut(tr("Shift+F11"));
 803	connect(recordGIF, SIGNAL(triggered()), this, SLOT(openGIFWindow()));
 804	addControlledAction(avMenu, recordGIF, "recordGIF");
 805#endif
 806
 807	avMenu->addSeparator();
 808	QMenu* videoLayers = avMenu->addMenu(tr("Video layers"));
 809
 810	for (int i = 0; i < 4; ++i) {
 811		QAction* enableBg = new QAction(tr("Background %0").arg(i), videoLayers);
 812		enableBg->setCheckable(true);
 813		enableBg->setChecked(true);
 814		connect(enableBg, &QAction::triggered, [this, i](bool enable) { m_controller->thread()->gba->video.renderer->disableBG[i] = !enable; });
 815		m_gameActions.append(enableBg);
 816		addControlledAction(videoLayers, enableBg, QString("enableBG%0").arg(i));
 817	}
 818
 819	QAction* enableObj = new QAction(tr("OBJ (sprites)"), videoLayers);
 820	enableObj->setCheckable(true);
 821	enableObj->setChecked(true);
 822	connect(enableObj, &QAction::triggered, [this](bool enable) { m_controller->thread()->gba->video.renderer->disableOBJ = !enable; });
 823	m_gameActions.append(enableObj);
 824	addControlledAction(videoLayers, enableObj, "enableOBJ");
 825
 826	QMenu* audioChannels = avMenu->addMenu(tr("Audio channels"));
 827
 828	for (int i = 0; i < 4; ++i) {
 829		QAction* enableCh = new QAction(tr("Channel %0").arg(i + 1), audioChannels);
 830		enableCh->setCheckable(true);
 831		enableCh->setChecked(true);
 832		connect(enableCh, &QAction::triggered, [this, i](bool enable) { m_controller->thread()->gba->audio.forceDisableCh[i] = !enable; });
 833		m_gameActions.append(enableCh);
 834		addControlledAction(audioChannels, enableCh, QString("enableCh%0").arg(i + 1));
 835	}
 836
 837	QAction* enableChA = new QAction(tr("Channel A"), audioChannels);
 838	enableChA->setCheckable(true);
 839	enableChA->setChecked(true);
 840	connect(enableChA, &QAction::triggered, [this, i](bool enable) { m_controller->thread()->gba->audio.forceDisableChA = !enable; });
 841	m_gameActions.append(enableChA);
 842	addControlledAction(audioChannels, enableChA, QString("enableChA"));
 843
 844	QAction* enableChB = new QAction(tr("Channel B"), audioChannels);
 845	enableChB->setCheckable(true);
 846	enableChB->setChecked(true);
 847	connect(enableChB, &QAction::triggered, [this, i](bool enable) { m_controller->thread()->gba->audio.forceDisableChB = !enable; });
 848	m_gameActions.append(enableChB);
 849	addControlledAction(audioChannels, enableChB, QString("enableChB"));
 850
 851	QMenu* toolsMenu = menubar->addMenu(tr("&Tools"));
 852	m_shortcutController->addMenu(toolsMenu);
 853	QAction* viewLogs = new QAction(tr("View &logs..."), toolsMenu);
 854	connect(viewLogs, SIGNAL(triggered()), m_logView, SLOT(show()));
 855	addControlledAction(toolsMenu, viewLogs, "viewLogs");
 856
 857	QAction* overrides = new QAction(tr("Game &overrides..."), toolsMenu);
 858	connect(overrides, SIGNAL(triggered()), this, SLOT(openOverrideWindow()));
 859	addControlledAction(toolsMenu, overrides, "overrideWindow");
 860
 861	QAction* sensors = new QAction(tr("Game &Pak sensors..."), toolsMenu);
 862	connect(sensors, SIGNAL(triggered()), this, SLOT(openSensorWindow()));
 863	addControlledAction(toolsMenu, sensors, "sensorWindow");
 864
 865	QAction* cheats = new QAction(tr("&Cheats..."), toolsMenu);
 866	connect(cheats, SIGNAL(triggered()), this, SLOT(openCheatsWindow()));
 867	addControlledAction(toolsMenu, cheats, "cheatsWindow");
 868
 869#ifdef USE_GDB_STUB
 870	QAction* gdbWindow = new QAction(tr("Start &GDB server..."), toolsMenu);
 871	connect(gdbWindow, SIGNAL(triggered()), this, SLOT(gdbOpen()));
 872	addControlledAction(toolsMenu, gdbWindow, "gdbWindow");
 873#endif
 874
 875	toolsMenu->addSeparator();
 876	addControlledAction(toolsMenu, toolsMenu->addAction(tr("Settings..."), this, SLOT(openSettingsWindow())), "settings");
 877	addControlledAction(toolsMenu, toolsMenu->addAction(tr("Edit shortcuts..."), this, SLOT(openShortcutWindow())), "shortcuts");
 878
 879	QAction* keymap = new QAction(tr("Remap keyboard..."), toolsMenu);
 880	connect(keymap, SIGNAL(triggered()), this, SLOT(openKeymapWindow()));
 881	addControlledAction(toolsMenu, keymap, "remapKeyboard");
 882
 883#ifdef BUILD_SDL
 884	QAction* gamepad = new QAction(tr("Remap gamepad..."), toolsMenu);
 885	connect(gamepad, SIGNAL(triggered()), this, SLOT(openGamepadWindow()));
 886	addControlledAction(toolsMenu, gamepad, "remapGamepad");
 887#endif
 888
 889	toolsMenu->addSeparator();
 890
 891	QAction* paletteView = new QAction(tr("View &palette..."), toolsMenu);
 892	connect(paletteView, SIGNAL(triggered()), this, SLOT(openPaletteWindow()));
 893	m_gameActions.append(paletteView);
 894	addControlledAction(toolsMenu, paletteView, "paletteWindow");
 895
 896	ConfigOption* skipBios = m_config->addOption("skipBios");
 897	skipBios->connect([this](const QVariant& value) {
 898		m_controller->setSkipBIOS(value.toBool());
 899	}, this);
 900
 901	ConfigOption* volume = m_config->addOption("volume");
 902	volume->connect([this](const QVariant& value) {
 903		m_controller->setVolume(value.toInt());
 904	}, this);
 905
 906	ConfigOption* mute = m_config->addOption("mute");
 907	mute->connect([this](const QVariant& value) {
 908		m_controller->setMute(value.toBool());
 909	}, this);
 910
 911	ConfigOption* rewindEnable = m_config->addOption("rewindEnable");
 912	rewindEnable->connect([this](const QVariant& value) {
 913		m_controller->setRewind(value.toBool(), m_config->getOption("rewindBufferCapacity").toInt(), m_config->getOption("rewindBufferInterval").toInt());
 914	}, this);
 915
 916	ConfigOption* rewindBufferCapacity = m_config->addOption("rewindBufferCapacity");
 917	rewindBufferCapacity->connect([this](const QVariant& value) {
 918		m_controller->setRewind(m_config->getOption("rewindEnable").toInt(), value.toInt(), m_config->getOption("rewindBufferInterval").toInt());
 919	}, this);
 920
 921	ConfigOption* rewindBufferInterval = m_config->addOption("rewindBufferInterval");
 922	rewindBufferInterval->connect([this](const QVariant& value) {
 923		m_controller->setRewind(m_config->getOption("rewindEnable").toInt(), m_config->getOption("rewindBufferCapacity").toInt(), value.toInt());
 924	}, this);
 925
 926	ConfigOption* allowOpposingDirections = m_config->addOption("allowOpposingDirections");
 927	allowOpposingDirections->connect([this](const QVariant& value) {
 928		m_inputController.setAllowOpposing(value.toBool());
 929	}, this);
 930
 931	QMenu* other = new QMenu(tr("Other"), this);
 932	m_shortcutController->addMenu(other);
 933	m_shortcutController->addFunctions(other, [this]() {
 934		m_controller->setTurbo(true, false);
 935	}, [this]() {
 936		m_controller->setTurbo(false, false);
 937	}, QKeySequence(Qt::Key_Tab), tr("Fast Forward (held)"), "holdFastForward");
 938
 939	addControlledAction(other, other->addAction(tr("Exit fullscreen"), this, SLOT(exitFullScreen()), QKeySequence("Esc")), "exitFullScreen");
 940
 941	foreach (QAction* action, m_gameActions) {
 942		action->setDisabled(true);
 943	}
 944}
 945
 946void Window::attachWidget(QWidget* widget) {
 947	m_screenWidget->layout()->addWidget(widget);
 948	static_cast<QStackedLayout*>(m_screenWidget->layout())->setCurrentWidget(widget);
 949}
 950
 951void Window::detachWidget(QWidget* widget) {
 952	m_screenWidget->layout()->removeWidget(widget);
 953}
 954
 955void Window::appendMRU(const QString& fname) {
 956	int index = m_mruFiles.indexOf(fname);
 957	if (index >= 0) {
 958		m_mruFiles.removeAt(index);
 959	}
 960	m_mruFiles.prepend(fname);
 961	while (m_mruFiles.size() > ConfigController::MRU_LIST_SIZE) {
 962		m_mruFiles.removeLast();
 963	}
 964	updateMRU();
 965}
 966
 967void Window::updateMRU() {
 968	if (!m_mruMenu) {
 969		return;
 970	}
 971	m_mruMenu->clear();
 972	int i = 0;
 973	for (const QString& file : m_mruFiles) {
 974		QAction* item = new QAction(file, m_mruMenu);
 975		item->setShortcut(QString("Ctrl+%1").arg(i));
 976		connect(item, &QAction::triggered, [this, file]() { m_controller->loadGame(file); });
 977		m_mruMenu->addAction(item);
 978		++i;
 979	}
 980	m_config->setMRU(m_mruFiles);
 981	m_config->write();
 982	m_mruMenu->setEnabled(i > 0);
 983}
 984
 985QAction* Window::addControlledAction(QMenu* menu, QAction* action, const QString& name) {
 986	m_shortcutController->addAction(menu, action, name);
 987	menu->addAction(action);
 988	action->setShortcutContext(Qt::WidgetShortcut);
 989	addAction(action);
 990	return action;
 991}
 992
 993WindowBackground::WindowBackground(QWidget* parent)
 994	: QLabel(parent)
 995{
 996	setLayout(new QStackedLayout());
 997	layout()->setContentsMargins(0, 0, 0, 0);
 998	setAlignment(Qt::AlignCenter);
 999}
1000
1001void WindowBackground::setSizeHint(const QSize& hint) {
1002	m_sizeHint = hint;
1003}
1004
1005QSize WindowBackground::sizeHint() const {
1006	return m_sizeHint;
1007}
1008
1009void WindowBackground::setLockAspectRatio(int width, int height) {
1010	m_aspectWidth = width;
1011	m_aspectHeight = height;
1012}
1013
1014void WindowBackground::paintEvent(QPaintEvent*) {
1015	const QPixmap* logo = pixmap();
1016	if (!logo) {
1017		return;
1018	}
1019	QPainter painter(this);
1020	painter.setRenderHint(QPainter::SmoothPixmapTransform);
1021	painter.fillRect(QRect(QPoint(), size()), Qt::black);
1022	QSize s = size();
1023	QSize ds = s;
1024	if (s.width() * m_aspectHeight > s.height() * m_aspectWidth) {
1025		ds.setWidth(s.height() * m_aspectWidth / m_aspectHeight);
1026	} else if (s.width() * m_aspectHeight < s.height() * m_aspectWidth) {
1027		ds.setHeight(s.width() * m_aspectHeight / m_aspectWidth);
1028	}
1029	QPoint origin = QPoint((s.width() - ds.width()) / 2, (s.height() - ds.height()) / 2);
1030	QRect full(origin, ds);
1031	painter.drawPixmap(full, *logo);
1032}