all repos — mgba @ e0863dc708d4d16d4047adb000c4ee65ab4130ed

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 <QDesktopWidget>
   9#include <QKeyEvent>
  10#include <QKeySequence>
  11#include <QMenuBar>
  12#include <QMessageBox>
  13#include <QMimeData>
  14#include <QPainter>
  15#include <QStackedLayout>
  16
  17#include "AboutScreen.h"
  18#include "CheatsView.h"
  19#include "ConfigController.h"
  20#include "Display.h"
  21#include "GameController.h"
  22#include "GBAApp.h"
  23#include "GBAKeyEditor.h"
  24#include "GDBController.h"
  25#include "GDBWindow.h"
  26#include "GIFView.h"
  27#include "IOViewer.h"
  28#include "LoadSaveState.h"
  29#include "LogView.h"
  30#include "MultiplayerController.h"
  31#include "MemoryView.h"
  32#include "OverrideView.h"
  33#include "PaletteView.h"
  34#include "SensorView.h"
  35#include "SettingsView.h"
  36#include "ShaderSelector.h"
  37#include "ShortcutController.h"
  38#include "ShortcutView.h"
  39#include "VideoView.h"
  40
  41extern "C" {
  42#include "platform/commandline.h"
  43#include "util/vfs.h"
  44}
  45
  46using namespace QGBA;
  47
  48#if defined(__WIN32) || defined(__OpenBSD__)
  49// This is a macro everywhere except MinGW and OpenBSD, it seems
  50using std::isnan;
  51#endif
  52
  53Window::Window(ConfigController* config, int playerId, QWidget* parent)
  54	: QMainWindow(parent)
  55	, m_log(0)
  56	, m_logView(new LogView(&m_log))
  57	, m_stateWindow(nullptr)
  58	, m_screenWidget(new WindowBackground())
  59	, m_logo(":/res/mgba-1024.png")
  60	, m_config(config)
  61	, m_inputController(playerId, this)
  62#ifdef USE_FFMPEG
  63	, m_videoView(nullptr)
  64#endif
  65#ifdef USE_MAGICK
  66	, m_gifView(nullptr)
  67#endif
  68#ifdef USE_GDB_STUB
  69	, m_gdbController(nullptr)
  70#endif
  71	, m_mruMenu(nullptr)
  72	, m_shortcutController(new ShortcutController(this))
  73	, m_playerId(playerId)
  74	, m_fullscreenOnStart(false)
  75{
  76	setFocusPolicy(Qt::StrongFocus);
  77	setAcceptDrops(true);
  78	setAttribute(Qt::WA_DeleteOnClose);
  79	m_controller = new GameController(this);
  80	m_controller->setInputController(&m_inputController);
  81	m_controller->setOverrides(m_config->overrides());
  82	updateTitle();
  83
  84	m_display = Display::create(this);
  85
  86	m_logo.setDevicePixelRatio(m_screenWidget->devicePixelRatio());
  87	m_logo = m_logo; // Free memory left over in old pixmap
  88
  89	m_screenWidget->setMinimumSize(m_display->minimumSize());
  90	m_screenWidget->setSizePolicy(m_display->sizePolicy());
  91	m_screenWidget->setSizeHint(m_display->minimumSize() * 2);
  92	m_screenWidget->setPixmap(m_logo);
  93	m_screenWidget->setLockAspectRatio(m_logo.width(), m_logo.height());
  94	setCentralWidget(m_screenWidget);
  95
  96	connect(m_controller, SIGNAL(gameStarted(GBAThread*)), this, SLOT(gameStarted(GBAThread*)));
  97	connect(m_controller, SIGNAL(gameStarted(GBAThread*)), &m_inputController, SLOT(suspendScreensaver()));
  98	connect(m_controller, SIGNAL(gameStopped(GBAThread*)), m_display, SLOT(stopDrawing()));
  99	connect(m_controller, SIGNAL(gameStopped(GBAThread*)), this, SLOT(gameStopped()));
 100	connect(m_controller, SIGNAL(gameStopped(GBAThread*)), &m_inputController, SLOT(resumeScreensaver()));
 101	connect(m_controller, SIGNAL(stateLoaded(GBAThread*)), m_display, SLOT(forceDraw()));
 102	connect(m_controller, SIGNAL(rewound(GBAThread*)), m_display, SLOT(forceDraw()));
 103	connect(m_controller, &GameController::gamePaused, [this]() {
 104		QImage currentImage(reinterpret_cast<const uchar*>(m_controller->drawContext()), VIDEO_HORIZONTAL_PIXELS,
 105		                    VIDEO_VERTICAL_PIXELS, 1024, QImage::Format_RGBX8888);
 106		QPixmap pixmap;
 107		pixmap.convertFromImage(currentImage);
 108		m_screenWidget->setPixmap(pixmap);
 109		m_screenWidget->setLockAspectRatio(3, 2);
 110	});
 111	connect(m_controller, SIGNAL(gamePaused(GBAThread*)), m_display, SLOT(pauseDrawing()));
 112#ifndef Q_OS_MAC
 113	connect(m_controller, SIGNAL(gamePaused(GBAThread*)), menuBar(), SLOT(show()));
 114	connect(m_controller, &GameController::gameUnpaused, [this]() {
 115		if(isFullScreen()) {
 116			menuBar()->hide();
 117		}
 118	});
 119#endif
 120	connect(m_controller, SIGNAL(gamePaused(GBAThread*)), &m_inputController, SLOT(resumeScreensaver()));
 121	connect(m_controller, SIGNAL(gameUnpaused(GBAThread*)), m_display, SLOT(unpauseDrawing()));
 122	connect(m_controller, SIGNAL(gameUnpaused(GBAThread*)), &m_inputController, SLOT(suspendScreensaver()));
 123	connect(m_controller, SIGNAL(postLog(int, const QString&)), &m_log, SLOT(postLog(int, const QString&)));
 124	connect(m_controller, SIGNAL(frameAvailable(const uint32_t*)), this, SLOT(recordFrame()));
 125	connect(m_controller, SIGNAL(frameAvailable(const uint32_t*)), m_display, SLOT(framePosted(const uint32_t*)));
 126	connect(m_controller, SIGNAL(gameCrashed(const QString&)), this, SLOT(gameCrashed(const QString&)));
 127	connect(m_controller, SIGNAL(gameFailed()), this, SLOT(gameFailed()));
 128	connect(m_controller, SIGNAL(unimplementedBiosCall(int)), this, SLOT(unimplementedBiosCall(int)));
 129	connect(m_controller, SIGNAL(statusPosted(const QString&)), m_display, SLOT(showMessage(const QString&)));
 130	connect(&m_log, SIGNAL(levelsSet(int)), m_controller, SLOT(setLogLevel(int)));
 131	connect(&m_log, SIGNAL(levelsEnabled(int)), m_controller, SLOT(enableLogLevel(int)));
 132	connect(&m_log, SIGNAL(levelsDisabled(int)), m_controller, SLOT(disableLogLevel(int)));
 133	connect(this, SIGNAL(startDrawing(GBAThread*)), m_display, SLOT(startDrawing(GBAThread*)), Qt::QueuedConnection);
 134	connect(this, SIGNAL(shutdown()), m_display, SLOT(stopDrawing()));
 135	connect(this, SIGNAL(shutdown()), m_controller, SLOT(closeGame()));
 136	connect(this, SIGNAL(shutdown()), m_logView, SLOT(hide()));
 137	connect(this, SIGNAL(audioBufferSamplesChanged(int)), m_controller, SLOT(setAudioBufferSamples(int)));
 138	connect(this, SIGNAL(sampleRateChanged(unsigned)), m_controller, SLOT(setAudioSampleRate(unsigned)));
 139	connect(this, SIGNAL(fpsTargetChanged(float)), m_controller, SLOT(setFPSTarget(float)));
 140	connect(&m_fpsTimer, SIGNAL(timeout()), this, SLOT(showFPS()));
 141	connect(m_display, &Display::hideCursor, [this]() {
 142		if (static_cast<QStackedLayout*>(m_screenWidget->layout())->currentWidget() == m_display) {
 143			m_screenWidget->setCursor(Qt::BlankCursor);
 144		}
 145	});
 146	connect(m_display, &Display::showCursor, [this]() {
 147		m_screenWidget->unsetCursor();
 148	});
 149	connect(&m_inputController, SIGNAL(profileLoaded(const QString&)), m_shortcutController, SLOT(loadProfile(const QString&)));
 150
 151	m_log.setLevels(GBA_LOG_WARN | GBA_LOG_ERROR | GBA_LOG_FATAL | GBA_LOG_STATUS);
 152	m_fpsTimer.setInterval(FPS_TIMER_INTERVAL);
 153
 154	m_shortcutController->setConfigController(m_config);
 155	setupMenu(menuBar());
 156}
 157
 158Window::~Window() {
 159	delete m_logView;
 160
 161#ifdef USE_FFMPEG
 162	delete m_videoView;
 163#endif
 164
 165#ifdef USE_MAGICK
 166	delete m_gifView;
 167#endif
 168}
 169
 170void Window::argumentsPassed(GBAArguments* args) {
 171	loadConfig();
 172
 173	if (args->patch) {
 174		m_controller->loadPatch(args->patch);
 175	}
 176
 177	if (args->fname) {
 178		m_controller->loadGame(args->fname, args->dirmode);
 179	}
 180}
 181
 182void Window::resizeFrame(int width, int height) {
 183	QSize newSize(width, height);
 184	m_screenWidget->setSizeHint(newSize);
 185	newSize -= m_screenWidget->size();
 186	newSize += size();
 187	resize(newSize);
 188}
 189
 190void Window::setConfig(ConfigController* config) {
 191	m_config = config;
 192}
 193
 194void Window::loadConfig() {
 195	const GBAOptions* opts = m_config->options();
 196
 197	m_log.setLevels(opts->logLevel);
 198
 199	m_controller->setOptions(opts);
 200	m_display->lockAspectRatio(opts->lockAspectRatio);
 201	m_display->filter(opts->resampleVideo);
 202
 203	if (opts->bios) {
 204		m_controller->loadBIOS(opts->bios);
 205	}
 206
 207	// TODO: Move these to ConfigController
 208	if (opts->fpsTarget) {
 209		emit fpsTargetChanged(opts->fpsTarget);
 210	}
 211
 212	if (opts->audioBuffers) {
 213		emit audioBufferSamplesChanged(opts->audioBuffers);
 214	}
 215
 216	if (opts->sampleRate) {
 217		emit sampleRateChanged(opts->sampleRate);
 218	}
 219
 220	if (opts->width && opts->height) {
 221		resizeFrame(opts->width, opts->height);
 222	}
 223
 224	if (opts->fullscreen) {
 225		enterFullScreen();
 226	}
 227
 228	if (opts->shader) {
 229		struct VDir* shader = VDirOpen(opts->shader);
 230		if (shader) {
 231			m_display->setShaders(shader);
 232			shader->close(shader);
 233		}
 234	}
 235
 236	m_inputController.setScreensaverSuspendable(opts->suspendScreensaver);
 237
 238	m_mruFiles = m_config->getMRU();
 239	updateMRU();
 240
 241	m_inputController.setConfiguration(m_config);
 242}
 243
 244void Window::saveConfig() {
 245	m_inputController.saveConfiguration();
 246	m_config->write();
 247}
 248
 249void Window::selectROM() {
 250	QStringList formats{
 251		"*.gba",
 252#ifdef USE_LIBZIP
 253		"*.zip",
 254#endif
 255#ifdef USE_LZMA
 256		"*.7z",
 257#endif
 258		"*.mb",
 259		"*.rom",
 260		"*.bin"};
 261	QString filter = tr("Game Boy Advance ROMs (%1)").arg(formats.join(QChar(' ')));
 262	QString filename = GBAApp::app()->getOpenFileName(this, tr("Select ROM"), filter);
 263	if (!filename.isEmpty()) {
 264		m_controller->loadGame(filename);
 265	}
 266}
 267
 268void Window::replaceROM() {
 269	QStringList formats{
 270		"*.gba",
 271#ifdef USE_LIBZIP
 272		"*.zip",
 273#endif
 274#ifdef USE_LZMA
 275		"*.7z",
 276#endif
 277		"*.rom",
 278		"*.bin"};
 279	QString filter = tr("Game Boy Advance ROMs (%1)").arg(formats.join(QChar(' ')));
 280	QString filename = GBAApp::app()->getOpenFileName(this, tr("Select ROM"), filter);
 281	if (!filename.isEmpty()) {
 282		m_controller->replaceGame(filename);
 283	}
 284}
 285
 286void Window::multiplayerChanged() {
 287	disconnect(nullptr, this, SLOT(multiplayerChanged()));
 288	int attached = 1;
 289	MultiplayerController* multiplayer = m_controller->multiplayerController();
 290	if (multiplayer) {
 291		attached = multiplayer->attached();
 292		connect(multiplayer, SIGNAL(gameAttached()), this, SLOT(multiplayerChanged()));
 293		connect(multiplayer, SIGNAL(gameDetached()), this, SLOT(multiplayerChanged()));
 294		m_playerId = multiplayer->playerId(m_controller);
 295	}
 296	if (m_controller->isLoaded()) {
 297		for (QAction* action : m_nonMpActions) {
 298			action->setDisabled(attached > 1);
 299		}
 300	}
 301}
 302
 303void Window::selectBIOS() {
 304	QString filename = GBAApp::app()->getOpenFileName(this, tr("Select BIOS"));
 305	if (!filename.isEmpty()) {
 306		m_config->setOption("bios", filename);
 307		m_config->updateOption("bios");
 308		m_config->setOption("useBios", true);
 309		m_config->updateOption("useBios");
 310		m_controller->loadBIOS(filename);
 311	}
 312}
 313
 314void Window::selectPatch() {
 315	QString filename = GBAApp::app()->getOpenFileName(this, tr("Select patch"), tr("Patches (*.ips *.ups *.bps)"));
 316	if (!filename.isEmpty()) {
 317		m_controller->loadPatch(filename);
 318	}
 319}
 320
 321void Window::openView(QWidget* widget) {
 322	connect(this, SIGNAL(shutdown()), widget, SLOT(close()));
 323	widget->setAttribute(Qt::WA_DeleteOnClose);
 324	widget->show();
 325}
 326
 327void Window::importSharkport() {
 328	QString filename = GBAApp::app()->getOpenFileName(this, tr("Select save"), tr("GameShark saves (*.sps *.xps)"));
 329	if (!filename.isEmpty()) {
 330		m_controller->importSharkport(filename);
 331	}
 332}
 333
 334void Window::exportSharkport() {
 335	QString filename = GBAApp::app()->getSaveFileName(this, tr("Select save"), tr("GameShark saves (*.sps *.xps)"));
 336	if (!filename.isEmpty()) {
 337		m_controller->exportSharkport(filename);
 338	}
 339}
 340
 341void Window::openKeymapWindow() {
 342	GBAKeyEditor* keyEditor = new GBAKeyEditor(&m_inputController, InputController::KEYBOARD);
 343	openView(keyEditor);
 344}
 345
 346void Window::openSettingsWindow() {
 347	SettingsView* settingsWindow = new SettingsView(m_config);
 348	connect(settingsWindow, SIGNAL(biosLoaded(const QString&)), m_controller, SLOT(loadBIOS(const QString&)));
 349	connect(settingsWindow, SIGNAL(audioDriverChanged()), m_controller, SLOT(reloadAudioDriver()));
 350	connect(settingsWindow, SIGNAL(displayDriverChanged()), this, SLOT(mustRestart()));
 351	openView(settingsWindow);
 352}
 353
 354void Window::openShortcutWindow() {
 355#ifdef BUILD_SDL
 356	m_inputController.recalibrateAxes();
 357#endif
 358	ShortcutView* shortcutView = new ShortcutView();
 359	shortcutView->setController(m_shortcutController);
 360	shortcutView->setInputController(&m_inputController);
 361	openView(shortcutView);
 362}
 363
 364void Window::openOverrideWindow() {
 365	OverrideView* overrideWindow = new OverrideView(m_controller, m_config);
 366	openView(overrideWindow);
 367}
 368
 369void Window::openSensorWindow() {
 370	SensorView* sensorWindow = new SensorView(m_controller, &m_inputController);
 371	openView(sensorWindow);
 372}
 373
 374void Window::openCheatsWindow() {
 375	CheatsView* cheatsWindow = new CheatsView(m_controller);
 376	openView(cheatsWindow);
 377}
 378
 379void Window::openPaletteWindow() {
 380	PaletteView* paletteWindow = new PaletteView(m_controller);
 381	openView(paletteWindow);
 382}
 383
 384void Window::openMemoryWindow() {
 385	MemoryView* memoryWindow = new MemoryView(m_controller);
 386	openView(memoryWindow);
 387}
 388
 389void Window::openIOViewer() {
 390	IOViewer* ioViewer = new IOViewer(m_controller);
 391	openView(ioViewer);
 392}
 393
 394void Window::openAboutScreen() {
 395	AboutScreen* about = new AboutScreen();
 396	openView(about);
 397}
 398
 399void Window::openShaderWindow() {
 400	ShaderSelector* shaderView = new ShaderSelector(m_display);
 401	openView(shaderView);
 402}
 403
 404#ifdef BUILD_SDL
 405void Window::openGamepadWindow() {
 406	const char* profile = m_inputController.profileForType(SDL_BINDING_BUTTON);
 407	GBAKeyEditor* keyEditor = new GBAKeyEditor(&m_inputController, SDL_BINDING_BUTTON, profile);
 408	openView(keyEditor);
 409}
 410#endif
 411
 412#ifdef USE_FFMPEG
 413void Window::openVideoWindow() {
 414	if (!m_videoView) {
 415		m_videoView = new VideoView();
 416		connect(m_videoView, SIGNAL(recordingStarted(GBAAVStream*)), m_controller, SLOT(setAVStream(GBAAVStream*)));
 417		connect(m_videoView, SIGNAL(recordingStopped()), m_controller, SLOT(clearAVStream()), Qt::DirectConnection);
 418		connect(m_controller, SIGNAL(gameStopped(GBAThread*)), m_videoView, SLOT(stopRecording()));
 419		connect(m_controller, SIGNAL(gameStopped(GBAThread*)), m_videoView, SLOT(close()));
 420		connect(this, SIGNAL(shutdown()), m_videoView, SLOT(close()));
 421	}
 422	m_videoView->show();
 423}
 424#endif
 425
 426#ifdef USE_MAGICK
 427void Window::openGIFWindow() {
 428	if (!m_gifView) {
 429		m_gifView = new GIFView();
 430		connect(m_gifView, SIGNAL(recordingStarted(GBAAVStream*)), m_controller, SLOT(setAVStream(GBAAVStream*)));
 431		connect(m_gifView, SIGNAL(recordingStopped()), m_controller, SLOT(clearAVStream()), Qt::DirectConnection);
 432		connect(m_controller, SIGNAL(gameStopped(GBAThread*)), m_gifView, SLOT(stopRecording()));
 433		connect(m_controller, SIGNAL(gameStopped(GBAThread*)), m_gifView, SLOT(close()));
 434		connect(this, SIGNAL(shutdown()), m_gifView, SLOT(close()));
 435	}
 436	m_gifView->show();
 437}
 438#endif
 439
 440#ifdef USE_GDB_STUB
 441void Window::gdbOpen() {
 442	if (!m_gdbController) {
 443		m_gdbController = new GDBController(m_controller, this);
 444	}
 445	GDBWindow* window = new GDBWindow(m_gdbController);
 446	openView(window);
 447}
 448#endif
 449
 450void Window::keyPressEvent(QKeyEvent* event) {
 451	if (event->isAutoRepeat()) {
 452		QWidget::keyPressEvent(event);
 453		return;
 454	}
 455	GBAKey key = m_inputController.mapKeyboard(event->key());
 456	if (key == GBA_KEY_NONE) {
 457		QWidget::keyPressEvent(event);
 458		return;
 459	}
 460	m_controller->keyPressed(key);
 461	event->accept();
 462}
 463
 464void Window::keyReleaseEvent(QKeyEvent* event) {
 465	if (event->isAutoRepeat()) {
 466		QWidget::keyReleaseEvent(event);
 467		return;
 468	}
 469	GBAKey key = m_inputController.mapKeyboard(event->key());
 470	if (key == GBA_KEY_NONE) {
 471		QWidget::keyPressEvent(event);
 472		return;
 473	}
 474	m_controller->keyReleased(key);
 475	event->accept();
 476}
 477
 478void Window::resizeEvent(QResizeEvent* event) {
 479	if (!isFullScreen()) {
 480		m_config->setOption("height", m_screenWidget->height());
 481		m_config->setOption("width", m_screenWidget->width());
 482	}
 483
 484	int factor = 0;
 485	if (event->size().width() % VIDEO_HORIZONTAL_PIXELS == 0 && event->size().height() % VIDEO_VERTICAL_PIXELS == 0 &&
 486	    event->size().width() / VIDEO_HORIZONTAL_PIXELS == event->size().height() / VIDEO_VERTICAL_PIXELS) {
 487		factor = event->size().width() / VIDEO_HORIZONTAL_PIXELS;
 488	}
 489	for (QMap<int, QAction*>::iterator iter = m_frameSizes.begin(); iter != m_frameSizes.end(); ++iter) {
 490		bool enableSignals = iter.value()->blockSignals(true);
 491		if (iter.key() == factor) {
 492			iter.value()->setChecked(true);
 493		} else {
 494			iter.value()->setChecked(false);
 495		}
 496		iter.value()->blockSignals(enableSignals);
 497	}
 498
 499	m_config->setOption("fullscreen", isFullScreen());
 500}
 501
 502void Window::showEvent(QShowEvent* event) {
 503	resizeFrame(m_screenWidget->sizeHint().width(), m_screenWidget->sizeHint().height());
 504	QVariant windowPos = m_config->getQtOption("windowPos");
 505	if (!windowPos.isNull()) {
 506		move(windowPos.toPoint());
 507	} else {
 508		QRect rect = frameGeometry();
 509		rect.moveCenter(QApplication::desktop()->availableGeometry().center());
 510		move(rect.topLeft());
 511	}
 512	if (m_fullscreenOnStart) {
 513		enterFullScreen();
 514		m_fullscreenOnStart = false;
 515	}
 516}
 517
 518void Window::closeEvent(QCloseEvent* event) {
 519	emit shutdown();
 520	m_config->setQtOption("windowPos", pos());
 521	saveConfig();
 522	QMainWindow::closeEvent(event);
 523}
 524
 525void Window::focusInEvent(QFocusEvent*) {
 526	m_display->forceDraw();
 527}
 528
 529void Window::focusOutEvent(QFocusEvent*) {
 530	m_controller->setTurbo(false, false);
 531	m_controller->stopRewinding();
 532	m_controller->clearKeys();
 533}
 534
 535void Window::dragEnterEvent(QDragEnterEvent* event) {
 536	if (event->mimeData()->hasFormat("text/uri-list")) {
 537		event->acceptProposedAction();
 538	}
 539}
 540
 541void Window::dropEvent(QDropEvent* event) {
 542	QString uris = event->mimeData()->data("text/uri-list");
 543	uris = uris.trimmed();
 544	if (uris.contains("\n")) {
 545		// Only one file please
 546		return;
 547	}
 548	QUrl url(uris);
 549	if (!url.isLocalFile()) {
 550		// No remote loading
 551		return;
 552	}
 553	event->accept();
 554	m_controller->loadGame(url.toLocalFile());
 555}
 556
 557void Window::mouseDoubleClickEvent(QMouseEvent* event) {
 558	if (event->button() != Qt::LeftButton) {
 559		return;
 560	}
 561	toggleFullScreen();
 562}
 563
 564void Window::enterFullScreen() {
 565	if (!isVisible()) {
 566		m_fullscreenOnStart = true;
 567		return;
 568	}
 569	if (isFullScreen()) {
 570		return;
 571	}
 572	showFullScreen();
 573#ifndef Q_OS_MAC
 574	if (m_controller->isLoaded() && !m_controller->isPaused()) {
 575		menuBar()->hide();
 576	}
 577#endif
 578}
 579
 580void Window::exitFullScreen() {
 581	if (!isFullScreen()) {
 582		return;
 583	}
 584	m_screenWidget->unsetCursor();
 585	menuBar()->show();
 586	showNormal();
 587}
 588
 589void Window::toggleFullScreen() {
 590	if (isFullScreen()) {
 591		exitFullScreen();
 592	} else {
 593		enterFullScreen();
 594	}
 595}
 596
 597void Window::gameStarted(GBAThread* context) {
 598	char title[13] = { '\0' };
 599	MutexLock(&context->stateMutex);
 600	if (context->state < THREAD_EXITING) {
 601		emit startDrawing(context);
 602		GBAGetGameTitle(context->gba, title);
 603	} else {
 604		MutexUnlock(&context->stateMutex);
 605		return;
 606	}
 607	MutexUnlock(&context->stateMutex);
 608	foreach (QAction* action, m_gameActions) {
 609		action->setDisabled(false);
 610	}
 611	multiplayerChanged();
 612	if (context->fname) {
 613		setWindowFilePath(context->fname);
 614		appendMRU(context->fname);
 615	}
 616	updateTitle();
 617	attachWidget(m_display);
 618
 619#ifndef Q_OS_MAC
 620	if (isFullScreen()) {
 621		menuBar()->hide();
 622	}
 623#endif
 624
 625	m_hitUnimplementedBiosCall = false;
 626	m_fpsTimer.start();
 627}
 628
 629void Window::gameStopped() {
 630	foreach (QAction* action, m_gameActions) {
 631		action->setDisabled(true);
 632	}
 633	setWindowFilePath(QString());
 634	updateTitle();
 635	detachWidget(m_display);
 636	m_screenWidget->setLockAspectRatio(m_logo.width(), m_logo.height());
 637	m_screenWidget->setPixmap(m_logo);
 638	m_screenWidget->unsetCursor();
 639
 640	m_fpsTimer.stop();
 641}
 642
 643void Window::gameCrashed(const QString& errorMessage) {
 644	QMessageBox* crash = new QMessageBox(QMessageBox::Critical, tr("Crash"),
 645	                                     tr("The game has crashed with the following error:\n\n%1").arg(errorMessage),
 646	                                     QMessageBox::Ok, this, Qt::Sheet);
 647	crash->setAttribute(Qt::WA_DeleteOnClose);
 648	crash->show();
 649}
 650
 651void Window::gameFailed() {
 652	QMessageBox* fail = new QMessageBox(QMessageBox::Warning, tr("Couldn't Load"),
 653	                                    tr("Could not load game. Are you sure it's in the correct format?"),
 654	                                    QMessageBox::Ok, this, Qt::Sheet);
 655	fail->setAttribute(Qt::WA_DeleteOnClose);
 656	fail->show();
 657}
 658
 659void Window::unimplementedBiosCall(int call) {
 660	if (m_hitUnimplementedBiosCall) {
 661		return;
 662	}
 663	m_hitUnimplementedBiosCall = true;
 664
 665	QMessageBox* fail = new QMessageBox(
 666	    QMessageBox::Warning, tr("Unimplemented BIOS call"),
 667	    tr("This game uses a BIOS call that is not implemented. Please use the official BIOS for best experience."),
 668	    QMessageBox::Ok, this, Qt::Sheet);
 669	fail->setAttribute(Qt::WA_DeleteOnClose);
 670	fail->show();
 671}
 672
 673void Window::tryMakePortable() {
 674	QMessageBox* confirm = new QMessageBox(QMessageBox::Question, tr("Really make portable?"),
 675	                                       tr("This will make the emulator load its configuration from the same directory as the executable. Do you want to continue?"),
 676	                                       QMessageBox::Yes | QMessageBox::Cancel, this, Qt::Sheet);
 677	confirm->setAttribute(Qt::WA_DeleteOnClose);
 678	connect(confirm->button(QMessageBox::Yes), SIGNAL(clicked()), m_config, SLOT(makePortable()));
 679	confirm->show();
 680}
 681
 682void Window::mustRestart() {
 683	QMessageBox* dialog = new QMessageBox(QMessageBox::Warning, tr("Restart needed"),
 684	                                      tr("Some changes will not take effect until the emulator is restarted."),
 685	                                      QMessageBox::Ok, this, Qt::Sheet);
 686	dialog->setAttribute(Qt::WA_DeleteOnClose);
 687	dialog->show();
 688}
 689
 690void Window::recordFrame() {
 691	m_frameList.append(QDateTime::currentDateTime());
 692	while (m_frameList.count() > FRAME_LIST_SIZE) {
 693		m_frameList.removeFirst();
 694	}
 695}
 696
 697void Window::showFPS() {
 698	if (m_frameList.isEmpty()) {
 699		updateTitle();
 700		return;
 701	}
 702	qint64 interval = m_frameList.first().msecsTo(m_frameList.last());
 703	float fps = (m_frameList.count() - 1) * 10000.f / interval;
 704	fps = round(fps) / 10.f;
 705	updateTitle(fps);
 706}
 707
 708void Window::updateTitle(float fps) {
 709	QString title;
 710
 711	m_controller->threadInterrupt();
 712	if (m_controller->isLoaded()) {
 713		char gameTitle[13] = { '\0' };
 714		GBAGetGameTitle(m_controller->thread()->gba, gameTitle);
 715
 716		title = (gameTitle);
 717	}
 718	MultiplayerController* multiplayer = m_controller->multiplayerController();
 719	if (multiplayer && multiplayer->attached() > 1) {
 720		title += tr(" -  Player %1 of %2").arg(m_playerId + 1).arg(multiplayer->attached());
 721	}
 722	m_controller->threadContinue();
 723	if (title.isNull()) {
 724		setWindowTitle(tr("%1 - %2").arg(projectName).arg(projectVersion));
 725	} else if (isnan(fps)) {
 726		setWindowTitle(tr("%1 - %2 - %3").arg(projectName).arg(title).arg(projectVersion));
 727	} else {
 728		setWindowTitle(tr("%1 - %2 (%3 fps) - %4").arg(projectName).arg(title).arg(fps).arg(projectVersion));
 729	}
 730}
 731
 732void Window::openStateWindow(LoadSave ls) {
 733	if (m_stateWindow) {
 734		return;
 735	}
 736	MultiplayerController* multiplayer = m_controller->multiplayerController();
 737	if (multiplayer && multiplayer->attached() > 1) {
 738		return;
 739	}
 740	bool wasPaused = m_controller->isPaused();
 741	m_stateWindow = new LoadSaveState(m_controller);
 742	connect(this, SIGNAL(shutdown()), m_stateWindow, SLOT(close()));
 743	connect(m_controller, SIGNAL(gameStopped(GBAThread*)), m_stateWindow, SLOT(close()));
 744	connect(m_stateWindow, &LoadSaveState::closed, [this]() {
 745		detachWidget(m_stateWindow);
 746		m_stateWindow = nullptr;
 747		QMetaObject::invokeMethod(this, "setFocus", Qt::QueuedConnection);
 748	});
 749	if (!wasPaused) {
 750		m_controller->setPaused(true);
 751		connect(m_stateWindow, &LoadSaveState::closed, [this]() { m_controller->setPaused(false); });
 752	}
 753	m_stateWindow->setAttribute(Qt::WA_DeleteOnClose);
 754	m_stateWindow->setMode(ls);
 755	attachWidget(m_stateWindow);
 756}
 757
 758void Window::setupMenu(QMenuBar* menubar) {
 759	menubar->clear();
 760	QMenu* fileMenu = menubar->addMenu(tr("&File"));
 761	m_shortcutController->addMenu(fileMenu);
 762	installEventFilter(m_shortcutController);
 763	addControlledAction(fileMenu, fileMenu->addAction(tr("Load &ROM..."), this, SLOT(selectROM()), QKeySequence::Open),
 764	                    "loadROM");
 765	addControlledAction(fileMenu, fileMenu->addAction(tr("Load &BIOS..."), this, SLOT(selectBIOS())), "loadBIOS");
 766	addControlledAction(fileMenu, fileMenu->addAction(tr("Load &patch..."), this, SLOT(selectPatch())), "loadPatch");
 767	addControlledAction(fileMenu, fileMenu->addAction(tr("Boot BIOS"), m_controller, SLOT(bootBIOS())), "bootBIOS");
 768
 769	addControlledAction(fileMenu, fileMenu->addAction(tr("Replace ROM..."), this, SLOT(replaceROM())), "replaceROM");
 770
 771	m_mruMenu = fileMenu->addMenu(tr("Recent"));
 772
 773	fileMenu->addSeparator();
 774
 775	addControlledAction(fileMenu, fileMenu->addAction(tr("Make portable"), this, SLOT(tryMakePortable())), "makePortable");
 776
 777	fileMenu->addSeparator();
 778
 779	QAction* loadState = new QAction(tr("&Load state"), fileMenu);
 780	loadState->setShortcut(tr("F10"));
 781	connect(loadState, &QAction::triggered, [this]() { this->openStateWindow(LoadSave::LOAD); });
 782	m_gameActions.append(loadState);
 783	m_nonMpActions.append(loadState);
 784	addControlledAction(fileMenu, loadState, "loadState");
 785
 786	QAction* saveState = new QAction(tr("&Save state"), fileMenu);
 787	saveState->setShortcut(tr("Shift+F10"));
 788	connect(saveState, &QAction::triggered, [this]() { this->openStateWindow(LoadSave::SAVE); });
 789	m_gameActions.append(saveState);
 790	m_nonMpActions.append(saveState);
 791	addControlledAction(fileMenu, saveState, "saveState");
 792
 793	QMenu* quickLoadMenu = fileMenu->addMenu(tr("Quick load"));
 794	QMenu* quickSaveMenu = fileMenu->addMenu(tr("Quick save"));
 795	m_shortcutController->addMenu(quickLoadMenu);
 796	m_shortcutController->addMenu(quickSaveMenu);
 797
 798	QAction* quickLoad = new QAction(tr("Load recent"), quickLoadMenu);
 799	connect(quickLoad, SIGNAL(triggered()), m_controller, SLOT(loadState()));
 800	m_gameActions.append(quickLoad);
 801	m_nonMpActions.append(quickLoad);
 802	addControlledAction(quickLoadMenu, quickLoad, "quickLoad");
 803
 804	QAction* quickSave = new QAction(tr("Save recent"), quickSaveMenu);
 805	connect(quickSave, SIGNAL(triggered()), m_controller, SLOT(saveState()));
 806	m_gameActions.append(quickSave);
 807	m_nonMpActions.append(quickSave);
 808	addControlledAction(quickSaveMenu, quickSave, "quickSave");
 809
 810	quickLoadMenu->addSeparator();
 811	quickSaveMenu->addSeparator();
 812
 813	QAction* undoLoadState = new QAction(tr("Undo load state"), quickLoadMenu);
 814	undoLoadState->setShortcut(tr("F11"));
 815	connect(undoLoadState, SIGNAL(triggered()), m_controller, SLOT(loadBackupState()));
 816	m_gameActions.append(undoLoadState);
 817	m_nonMpActions.append(undoLoadState);
 818	addControlledAction(quickLoadMenu, undoLoadState, "undoLoadState");
 819
 820	QAction* undoSaveState = new QAction(tr("Undo save state"), quickSaveMenu);
 821	undoSaveState->setShortcut(tr("Shift+F11"));
 822	connect(undoSaveState, SIGNAL(triggered()), m_controller, SLOT(saveBackupState()));
 823	m_gameActions.append(undoSaveState);
 824	m_nonMpActions.append(undoSaveState);
 825	addControlledAction(quickSaveMenu, undoSaveState, "undoSaveState");
 826
 827	quickLoadMenu->addSeparator();
 828	quickSaveMenu->addSeparator();
 829
 830	int i;
 831	for (i = 1; i < 10; ++i) {
 832		quickLoad = new QAction(tr("State &%1").arg(i), quickLoadMenu);
 833		quickLoad->setShortcut(tr("F%1").arg(i));
 834		connect(quickLoad, &QAction::triggered, [this, i]() { m_controller->loadState(i); });
 835		m_gameActions.append(quickLoad);
 836		m_nonMpActions.append(quickLoad);
 837		addControlledAction(quickLoadMenu, quickLoad, QString("quickLoad.%1").arg(i));
 838
 839		quickSave = new QAction(tr("State &%1").arg(i), quickSaveMenu);
 840		quickSave->setShortcut(tr("Shift+F%1").arg(i));
 841		connect(quickSave, &QAction::triggered, [this, i]() { m_controller->saveState(i); });
 842		m_gameActions.append(quickSave);
 843		m_nonMpActions.append(quickSave);
 844		addControlledAction(quickSaveMenu, quickSave, QString("quickSave.%1").arg(i));
 845	}
 846
 847	fileMenu->addSeparator();
 848	QAction* importShark = new QAction(tr("Import GameShark Save"), fileMenu);
 849	connect(importShark, SIGNAL(triggered()), this, SLOT(importSharkport()));
 850	m_gameActions.append(importShark);
 851	addControlledAction(fileMenu, importShark, "importShark");
 852
 853	QAction* exportShark = new QAction(tr("Export GameShark Save"), fileMenu);
 854	connect(exportShark, SIGNAL(triggered()), this, SLOT(exportSharkport()));
 855	m_gameActions.append(exportShark);
 856	addControlledAction(fileMenu, exportShark, "exportShark");
 857
 858	fileMenu->addSeparator();
 859	QAction* multiWindow = new QAction(tr("New multiplayer window"), fileMenu);
 860	connect(multiWindow, &QAction::triggered, [this]() {
 861		GBAApp::app()->newWindow();
 862	});
 863	addControlledAction(fileMenu, multiWindow, "multiWindow");
 864
 865#ifndef Q_OS_MAC
 866	fileMenu->addSeparator();
 867#endif
 868
 869	QAction* about = new QAction(tr("About"), fileMenu);
 870	connect(about, SIGNAL(triggered()), this, SLOT(openAboutScreen()));
 871	fileMenu->addAction(about);
 872
 873#ifndef Q_OS_MAC
 874	addControlledAction(fileMenu, fileMenu->addAction(tr("E&xit"), this, SLOT(close()), QKeySequence::Quit), "quit");
 875#endif
 876
 877	QMenu* emulationMenu = menubar->addMenu(tr("&Emulation"));
 878	m_shortcutController->addMenu(emulationMenu);
 879	QAction* reset = new QAction(tr("&Reset"), emulationMenu);
 880	reset->setShortcut(tr("Ctrl+R"));
 881	connect(reset, SIGNAL(triggered()), m_controller, SLOT(reset()));
 882	m_gameActions.append(reset);
 883	addControlledAction(emulationMenu, reset, "reset");
 884
 885	QAction* shutdown = new QAction(tr("Sh&utdown"), emulationMenu);
 886	connect(shutdown, SIGNAL(triggered()), m_controller, SLOT(closeGame()));
 887	m_gameActions.append(shutdown);
 888	addControlledAction(emulationMenu, shutdown, "shutdown");
 889
 890	QAction* yank = new QAction(tr("Yank game pak"), emulationMenu);
 891	connect(yank, SIGNAL(triggered()), m_controller, SLOT(yankPak()));
 892	m_gameActions.append(yank);
 893	addControlledAction(emulationMenu, yank, "yank");
 894	emulationMenu->addSeparator();
 895
 896	QAction* pause = new QAction(tr("&Pause"), emulationMenu);
 897	pause->setChecked(false);
 898	pause->setCheckable(true);
 899	pause->setShortcut(tr("Ctrl+P"));
 900	connect(pause, SIGNAL(triggered(bool)), m_controller, SLOT(setPaused(bool)));
 901	connect(m_controller, &GameController::gamePaused, [this, pause]() {
 902		pause->setChecked(true);
 903	});
 904	connect(m_controller, &GameController::gameUnpaused, [pause]() { pause->setChecked(false); });
 905	m_gameActions.append(pause);
 906	addControlledAction(emulationMenu, pause, "pause");
 907
 908	QAction* frameAdvance = new QAction(tr("&Next frame"), emulationMenu);
 909	frameAdvance->setShortcut(tr("Ctrl+N"));
 910	connect(frameAdvance, SIGNAL(triggered()), m_controller, SLOT(frameAdvance()));
 911	m_gameActions.append(frameAdvance);
 912	m_nonMpActions.append(frameAdvance);
 913	addControlledAction(emulationMenu, frameAdvance, "frameAdvance");
 914
 915	emulationMenu->addSeparator();
 916
 917	m_shortcutController->addFunctions(emulationMenu, [this]() {
 918		m_controller->setTurbo(true, false);
 919	}, [this]() {
 920		m_controller->setTurbo(false, false);
 921	}, QKeySequence(Qt::Key_Tab), tr("Fast forward (held)"), "holdFastForward");
 922
 923	QAction* turbo = new QAction(tr("&Fast forward"), emulationMenu);
 924	turbo->setCheckable(true);
 925	turbo->setChecked(false);
 926	turbo->setShortcut(tr("Shift+Tab"));
 927	connect(turbo, SIGNAL(triggered(bool)), m_controller, SLOT(setTurbo(bool)));
 928	addControlledAction(emulationMenu, turbo, "fastForward");
 929
 930	QMenu* ffspeedMenu = emulationMenu->addMenu(tr("Fast forward speed"));
 931	ConfigOption* ffspeed = m_config->addOption("fastForwardRatio");
 932	ffspeed->connect([this](const QVariant& value) {
 933		m_controller->setTurboSpeed(value.toFloat());
 934	}, this);
 935	ffspeed->addValue(tr("Unbounded"), -1.0f, ffspeedMenu);
 936	ffspeed->setValue(QVariant(-1.0f));
 937	ffspeedMenu->addSeparator();
 938	for (i = 2; i < 11; ++i) {
 939		ffspeed->addValue(tr("%0x").arg(i), i, ffspeedMenu);
 940	}
 941	m_config->updateOption("fastForwardRatio");
 942
 943	m_shortcutController->addFunctions(emulationMenu, [this]() {
 944		m_controller->startRewinding();
 945	}, [this]() {
 946		m_controller->stopRewinding();
 947	}, QKeySequence("~"), tr("Rewind (held)"), "holdRewind");
 948
 949	QAction* rewind = new QAction(tr("Re&wind"), emulationMenu);
 950	rewind->setShortcut(tr("`"));
 951	connect(rewind, SIGNAL(triggered()), m_controller, SLOT(rewind()));
 952	m_gameActions.append(rewind);
 953	m_nonMpActions.append(rewind);
 954	addControlledAction(emulationMenu, rewind, "rewind");
 955
 956	QAction* frameRewind = new QAction(tr("Step backwards"), emulationMenu);
 957	frameRewind->setShortcut(tr("Ctrl+B"));
 958	connect(frameRewind, &QAction::triggered, [this] () {
 959		m_controller->rewind(1);
 960	});
 961	m_gameActions.append(frameRewind);
 962	m_nonMpActions.append(frameRewind);
 963	addControlledAction(emulationMenu, frameRewind, "frameRewind");
 964
 965	ConfigOption* videoSync = m_config->addOption("videoSync");
 966	videoSync->addBoolean(tr("Sync to &video"), emulationMenu);
 967	videoSync->connect([this](const QVariant& value) {
 968		m_controller->setVideoSync(value.toBool());
 969	}, this);
 970	m_config->updateOption("videoSync");
 971
 972	ConfigOption* audioSync = m_config->addOption("audioSync");
 973	audioSync->addBoolean(tr("Sync to &audio"), emulationMenu);
 974	audioSync->connect([this](const QVariant& value) {
 975		m_controller->setAudioSync(value.toBool());
 976	}, this);
 977	m_config->updateOption("audioSync");
 978
 979	emulationMenu->addSeparator();
 980
 981	QMenu* solarMenu = emulationMenu->addMenu(tr("Solar sensor"));
 982	m_shortcutController->addMenu(solarMenu);
 983	QAction* solarIncrease = new QAction(tr("Increase solar level"), solarMenu);
 984	connect(solarIncrease, SIGNAL(triggered()), m_controller, SLOT(increaseLuminanceLevel()));
 985	addControlledAction(solarMenu, solarIncrease, "increaseLuminanceLevel");
 986
 987	QAction* solarDecrease = new QAction(tr("Decrease solar level"), solarMenu);
 988	connect(solarDecrease, SIGNAL(triggered()), m_controller, SLOT(decreaseLuminanceLevel()));
 989	addControlledAction(solarMenu, solarDecrease, "decreaseLuminanceLevel");
 990
 991	QAction* maxSolar = new QAction(tr("Brightest solar level"), solarMenu);
 992	connect(maxSolar, &QAction::triggered, [this]() { m_controller->setLuminanceLevel(10); });
 993	addControlledAction(solarMenu, maxSolar, "maxLuminanceLevel");
 994
 995	QAction* minSolar = new QAction(tr("Darkest solar level"), solarMenu);
 996	connect(minSolar, &QAction::triggered, [this]() { m_controller->setLuminanceLevel(0); });
 997	addControlledAction(solarMenu, minSolar, "minLuminanceLevel");
 998
 999	solarMenu->addSeparator();
1000	for (int i = 0; i <= 10; ++i) {
1001		QAction* setSolar = new QAction(tr("Brightness %1").arg(QString::number(i)), solarMenu);
1002		connect(setSolar, &QAction::triggered, [this, i]() {
1003			m_controller->setLuminanceLevel(i);
1004		});
1005		addControlledAction(solarMenu, setSolar, QString("luminanceLevel.%1").arg(QString::number(i)));
1006	}
1007
1008	QMenu* avMenu = menubar->addMenu(tr("Audio/&Video"));
1009	m_shortcutController->addMenu(avMenu);
1010	QMenu* frameMenu = avMenu->addMenu(tr("Frame size"));
1011	m_shortcutController->addMenu(frameMenu, avMenu);
1012	for (int i = 1; i <= 6; ++i) {
1013		QAction* setSize = new QAction(tr("%1x").arg(QString::number(i)), avMenu);
1014		setSize->setCheckable(true);
1015		connect(setSize, &QAction::triggered, [this, i, setSize]() {
1016			showNormal();
1017			resizeFrame(VIDEO_HORIZONTAL_PIXELS * i, VIDEO_VERTICAL_PIXELS * i);
1018			bool enableSignals = setSize->blockSignals(true);
1019			setSize->setChecked(true);
1020			setSize->blockSignals(enableSignals);
1021		});
1022		m_frameSizes[i] = setSize;
1023		addControlledAction(frameMenu, setSize, QString("frame%1x").arg(QString::number(i)));
1024	}
1025	QKeySequence fullscreenKeys;
1026#ifdef Q_OS_WIN
1027	fullscreenKeys = QKeySequence("Alt+Return");
1028#else
1029	fullscreenKeys = QKeySequence("Ctrl+F");
1030#endif
1031	addControlledAction(frameMenu, frameMenu->addAction(tr("Toggle fullscreen"), this, SLOT(toggleFullScreen()), fullscreenKeys), "fullscreen");
1032
1033	ConfigOption* lockAspectRatio = m_config->addOption("lockAspectRatio");
1034	lockAspectRatio->addBoolean(tr("Lock aspect ratio"), avMenu);
1035	lockAspectRatio->connect([this](const QVariant& value) {
1036		m_display->lockAspectRatio(value.toBool());
1037	}, this);
1038	m_config->updateOption("lockAspectRatio");
1039
1040	ConfigOption* resampleVideo = m_config->addOption("resampleVideo");
1041	resampleVideo->addBoolean(tr("Resample video"), avMenu);
1042	resampleVideo->connect([this](const QVariant& value) {
1043		m_display->filter(value.toBool());
1044	}, this);
1045	m_config->updateOption("resampleVideo");
1046
1047	QMenu* skipMenu = avMenu->addMenu(tr("Frame&skip"));
1048	ConfigOption* skip = m_config->addOption("frameskip");
1049	skip->connect([this](const QVariant& value) {
1050		m_controller->setFrameskip(value.toInt());
1051	}, this);
1052	for (int i = 0; i <= 10; ++i) {
1053		skip->addValue(QString::number(i), i, skipMenu);
1054	}
1055	m_config->updateOption("frameskip");
1056
1057	QAction* shaderView = new QAction(tr("Shader options..."), avMenu);
1058	connect(shaderView, SIGNAL(triggered()), this, SLOT(openShaderWindow()));
1059	if (!m_display->supportsShaders()) {
1060		shaderView->setEnabled(false);
1061	}
1062	addControlledAction(avMenu, shaderView, "shaderSelector");
1063
1064	avMenu->addSeparator();
1065
1066	ConfigOption* mute = m_config->addOption("mute");
1067	mute->addBoolean(tr("Mute"), avMenu);
1068	mute->connect([this](const QVariant& value) {
1069		m_controller->setMute(value.toBool());
1070	}, this);
1071	m_config->updateOption("mute");
1072
1073	QMenu* target = avMenu->addMenu(tr("FPS target"));
1074	ConfigOption* fpsTargetOption = m_config->addOption("fpsTarget");
1075	fpsTargetOption->connect([this](const QVariant& value) {
1076		emit fpsTargetChanged(value.toFloat());
1077	}, this);
1078	fpsTargetOption->addValue(tr("15"), 15, target);
1079	fpsTargetOption->addValue(tr("30"), 30, target);
1080	fpsTargetOption->addValue(tr("45"), 45, target);
1081	fpsTargetOption->addValue(tr("Native (59.7)"), float(GBA_ARM7TDMI_FREQUENCY) / float(VIDEO_TOTAL_LENGTH), target);
1082	fpsTargetOption->addValue(tr("60"), 60, target);
1083	fpsTargetOption->addValue(tr("90"), 90, target);
1084	fpsTargetOption->addValue(tr("120"), 120, target);
1085	fpsTargetOption->addValue(tr("240"), 240, target);
1086	m_config->updateOption("fpsTarget");
1087
1088#if defined(USE_PNG) || defined(USE_FFMPEG) || defined(USE_MAGICK)
1089	avMenu->addSeparator();
1090#endif
1091
1092#ifdef USE_PNG
1093	QAction* screenshot = new QAction(tr("Take &screenshot"), avMenu);
1094	screenshot->setShortcut(tr("F12"));
1095	connect(screenshot, SIGNAL(triggered()), m_controller, SLOT(screenshot()));
1096	m_gameActions.append(screenshot);
1097	addControlledAction(avMenu, screenshot, "screenshot");
1098#endif
1099
1100#ifdef USE_FFMPEG
1101	QAction* recordOutput = new QAction(tr("Record output..."), avMenu);
1102	connect(recordOutput, SIGNAL(triggered()), this, SLOT(openVideoWindow()));
1103	addControlledAction(avMenu, recordOutput, "recordOutput");
1104#endif
1105
1106#ifdef USE_MAGICK
1107	QAction* recordGIF = new QAction(tr("Record GIF..."), avMenu);
1108	connect(recordGIF, SIGNAL(triggered()), this, SLOT(openGIFWindow()));
1109	addControlledAction(avMenu, recordGIF, "recordGIF");
1110#endif
1111
1112	avMenu->addSeparator();
1113	QMenu* videoLayers = avMenu->addMenu(tr("Video layers"));
1114
1115	for (int i = 0; i < 4; ++i) {
1116		QAction* enableBg = new QAction(tr("Background %0").arg(i), videoLayers);
1117		enableBg->setCheckable(true);
1118		enableBg->setChecked(true);
1119		connect(enableBg, &QAction::triggered, [this, i](bool enable) { m_controller->setVideoLayerEnabled(i, enable); });
1120		addControlledAction(videoLayers, enableBg, QString("enableBG%0").arg(i));
1121	}
1122
1123	QAction* enableObj = new QAction(tr("OBJ (sprites)"), videoLayers);
1124	enableObj->setCheckable(true);
1125	enableObj->setChecked(true);
1126	connect(enableObj, &QAction::triggered, [this](bool enable) { m_controller->setVideoLayerEnabled(4, enable); });
1127	addControlledAction(videoLayers, enableObj, "enableOBJ");
1128
1129	QMenu* audioChannels = avMenu->addMenu(tr("Audio channels"));
1130
1131	for (int i = 0; i < 4; ++i) {
1132		QAction* enableCh = new QAction(tr("Channel %0").arg(i + 1), audioChannels);
1133		enableCh->setCheckable(true);
1134		enableCh->setChecked(true);
1135		connect(enableCh, &QAction::triggered, [this, i](bool enable) { m_controller->setAudioChannelEnabled(i, enable); });
1136		addControlledAction(audioChannels, enableCh, QString("enableCh%0").arg(i + 1));
1137	}
1138
1139	QAction* enableChA = new QAction(tr("Channel A"), audioChannels);
1140	enableChA->setCheckable(true);
1141	enableChA->setChecked(true);
1142	connect(enableChA, &QAction::triggered, [this, i](bool enable) { m_controller->setAudioChannelEnabled(4, enable); });
1143	addControlledAction(audioChannels, enableChA, QString("enableChA"));
1144
1145	QAction* enableChB = new QAction(tr("Channel B"), audioChannels);
1146	enableChB->setCheckable(true);
1147	enableChB->setChecked(true);
1148	connect(enableChB, &QAction::triggered, [this, i](bool enable) { m_controller->setAudioChannelEnabled(5, enable); });
1149	addControlledAction(audioChannels, enableChB, QString("enableChB"));
1150
1151	QMenu* toolsMenu = menubar->addMenu(tr("&Tools"));
1152	m_shortcutController->addMenu(toolsMenu);
1153	QAction* viewLogs = new QAction(tr("View &logs..."), toolsMenu);
1154	connect(viewLogs, SIGNAL(triggered()), m_logView, SLOT(show()));
1155	addControlledAction(toolsMenu, viewLogs, "viewLogs");
1156
1157	QAction* overrides = new QAction(tr("Game &overrides..."), toolsMenu);
1158	connect(overrides, SIGNAL(triggered()), this, SLOT(openOverrideWindow()));
1159	addControlledAction(toolsMenu, overrides, "overrideWindow");
1160
1161	QAction* sensors = new QAction(tr("Game &Pak sensors..."), toolsMenu);
1162	connect(sensors, SIGNAL(triggered()), this, SLOT(openSensorWindow()));
1163	addControlledAction(toolsMenu, sensors, "sensorWindow");
1164
1165	QAction* cheats = new QAction(tr("&Cheats..."), toolsMenu);
1166	connect(cheats, SIGNAL(triggered()), this, SLOT(openCheatsWindow()));
1167	addControlledAction(toolsMenu, cheats, "cheatsWindow");
1168
1169#ifdef USE_GDB_STUB
1170	QAction* gdbWindow = new QAction(tr("Start &GDB server..."), toolsMenu);
1171	connect(gdbWindow, SIGNAL(triggered()), this, SLOT(gdbOpen()));
1172	addControlledAction(toolsMenu, gdbWindow, "gdbWindow");
1173#endif
1174
1175	toolsMenu->addSeparator();
1176	addControlledAction(toolsMenu, toolsMenu->addAction(tr("Settings..."), this, SLOT(openSettingsWindow())),
1177	                    "settings");
1178	addControlledAction(toolsMenu, toolsMenu->addAction(tr("Edit shortcuts..."), this, SLOT(openShortcutWindow())),
1179	                    "shortcuts");
1180
1181	QAction* keymap = new QAction(tr("Remap keyboard..."), toolsMenu);
1182	connect(keymap, SIGNAL(triggered()), this, SLOT(openKeymapWindow()));
1183	addControlledAction(toolsMenu, keymap, "remapKeyboard");
1184
1185#ifdef BUILD_SDL
1186	QAction* gamepad = new QAction(tr("Remap gamepad..."), toolsMenu);
1187	connect(gamepad, SIGNAL(triggered()), this, SLOT(openGamepadWindow()));
1188	addControlledAction(toolsMenu, gamepad, "remapGamepad");
1189#endif
1190
1191	toolsMenu->addSeparator();
1192
1193	QAction* paletteView = new QAction(tr("View &palette..."), toolsMenu);
1194	connect(paletteView, SIGNAL(triggered()), this, SLOT(openPaletteWindow()));
1195	m_gameActions.append(paletteView);
1196	addControlledAction(toolsMenu, paletteView, "paletteWindow");
1197
1198	QAction* memoryView = new QAction(tr("View memory..."), toolsMenu);
1199	connect(memoryView, SIGNAL(triggered()), this, SLOT(openMemoryWindow()));
1200	m_gameActions.append(memoryView);
1201	addControlledAction(toolsMenu, memoryView, "memoryView");
1202
1203	QAction* ioViewer = new QAction(tr("View &I/O registers..."), toolsMenu);
1204	connect(ioViewer, SIGNAL(triggered()), this, SLOT(openIOViewer()));
1205	m_gameActions.append(ioViewer);
1206	addControlledAction(toolsMenu, ioViewer, "ioViewer");
1207
1208	ConfigOption* skipBios = m_config->addOption("skipBios");
1209	skipBios->connect([this](const QVariant& value) {
1210		m_controller->setSkipBIOS(value.toBool());
1211	}, this);
1212
1213	ConfigOption* useBios = m_config->addOption("useBios");
1214	useBios->connect([this](const QVariant& value) {
1215		m_controller->setUseBIOS(value.toBool());
1216	}, this);
1217
1218	ConfigOption* buffers = m_config->addOption("audioBuffers");
1219	buffers->connect([this](const QVariant& value) {
1220		emit audioBufferSamplesChanged(value.toInt());
1221	}, this);
1222
1223	ConfigOption* sampleRate = m_config->addOption("sampleRate");
1224	sampleRate->connect([this](const QVariant& value) {
1225		emit sampleRateChanged(value.toUInt());
1226	}, this);
1227
1228	ConfigOption* volume = m_config->addOption("volume");
1229	volume->connect([this](const QVariant& value) {
1230		m_controller->setVolume(value.toInt());
1231	}, this);
1232
1233	ConfigOption* rewindEnable = m_config->addOption("rewindEnable");
1234	rewindEnable->connect([this](const QVariant& value) {
1235		m_controller->setRewind(value.toBool(), m_config->getOption("rewindBufferCapacity").toInt(), m_config->getOption("rewindBufferInterval").toInt());
1236	}, this);
1237
1238	ConfigOption* rewindBufferCapacity = m_config->addOption("rewindBufferCapacity");
1239	rewindBufferCapacity->connect([this](const QVariant& value) {
1240		m_controller->setRewind(m_config->getOption("rewindEnable").toInt(), value.toInt(), m_config->getOption("rewindBufferInterval").toInt());
1241	}, this);
1242
1243	ConfigOption* rewindBufferInterval = m_config->addOption("rewindBufferInterval");
1244	rewindBufferInterval->connect([this](const QVariant& value) {
1245		m_controller->setRewind(m_config->getOption("rewindEnable").toInt(), m_config->getOption("rewindBufferCapacity").toInt(), value.toInt());
1246	}, this);
1247
1248	ConfigOption* allowOpposingDirections = m_config->addOption("allowOpposingDirections");
1249	allowOpposingDirections->connect([this](const QVariant& value) {
1250		m_inputController.setAllowOpposing(value.toBool());
1251	}, this);
1252
1253	QAction* exitFullScreen = new QAction(tr("Exit fullscreen"), frameMenu);
1254	connect(exitFullScreen, SIGNAL(triggered()), this, SLOT(exitFullScreen()));
1255	exitFullScreen->setShortcut(QKeySequence("Esc"));
1256	addHiddenAction(frameMenu, exitFullScreen, "exitFullScreen");
1257
1258	foreach (QAction* action, m_gameActions) {
1259		action->setDisabled(true);
1260	}
1261}
1262
1263void Window::attachWidget(QWidget* widget) {
1264	m_screenWidget->layout()->addWidget(widget);
1265	m_screenWidget->unsetCursor();
1266	static_cast<QStackedLayout*>(m_screenWidget->layout())->setCurrentWidget(widget);
1267}
1268
1269void Window::detachWidget(QWidget* widget) {
1270	m_screenWidget->layout()->removeWidget(widget);
1271}
1272
1273void Window::appendMRU(const QString& fname) {
1274	int index = m_mruFiles.indexOf(fname);
1275	if (index >= 0) {
1276		m_mruFiles.removeAt(index);
1277	}
1278	m_mruFiles.prepend(fname);
1279	while (m_mruFiles.size() > ConfigController::MRU_LIST_SIZE) {
1280		m_mruFiles.removeLast();
1281	}
1282	updateMRU();
1283}
1284
1285void Window::updateMRU() {
1286	if (!m_mruMenu) {
1287		return;
1288	}
1289	m_mruMenu->clear();
1290	int i = 0;
1291	for (const QString& file : m_mruFiles) {
1292		QAction* item = new QAction(file, m_mruMenu);
1293		item->setShortcut(QString("Ctrl+%1").arg(i));
1294		connect(item, &QAction::triggered, [this, file]() { m_controller->loadGame(file); });
1295		m_mruMenu->addAction(item);
1296		++i;
1297	}
1298	m_config->setMRU(m_mruFiles);
1299	m_config->write();
1300	m_mruMenu->setEnabled(i > 0);
1301}
1302
1303QAction* Window::addControlledAction(QMenu* menu, QAction* action, const QString& name) {
1304	addHiddenAction(menu, action, name);
1305	menu->addAction(action);
1306	return action;
1307}
1308
1309QAction* Window::addHiddenAction(QMenu* menu, QAction* action, const QString& name) {
1310	m_shortcutController->addAction(menu, action, name);
1311	action->setShortcutContext(Qt::WidgetShortcut);
1312	addAction(action);
1313	return action;
1314}
1315
1316WindowBackground::WindowBackground(QWidget* parent)
1317	: QLabel(parent)
1318{
1319	setLayout(new QStackedLayout());
1320	layout()->setContentsMargins(0, 0, 0, 0);
1321	setAlignment(Qt::AlignCenter);
1322}
1323
1324void WindowBackground::setSizeHint(const QSize& hint) {
1325	m_sizeHint = hint;
1326}
1327
1328QSize WindowBackground::sizeHint() const {
1329	return m_sizeHint;
1330}
1331
1332void WindowBackground::setLockAspectRatio(int width, int height) {
1333	m_aspectWidth = width;
1334	m_aspectHeight = height;
1335}
1336
1337void WindowBackground::paintEvent(QPaintEvent*) {
1338	const QPixmap* logo = pixmap();
1339	if (!logo) {
1340		return;
1341	}
1342	QPainter painter(this);
1343	painter.setRenderHint(QPainter::SmoothPixmapTransform);
1344	painter.fillRect(QRect(QPoint(), size()), Qt::black);
1345	QSize s = size();
1346	QSize ds = s;
1347	if (ds.width() * m_aspectHeight > ds.height() * m_aspectWidth) {
1348		ds.setWidth(ds.height() * m_aspectWidth / m_aspectHeight);
1349	} else if (ds.width() * m_aspectHeight < ds.height() * m_aspectWidth) {
1350		ds.setHeight(ds.width() * m_aspectHeight / m_aspectWidth);
1351	}
1352	QPoint origin = QPoint((s.width() - ds.width()) / 2, (s.height() - ds.height()) / 2);
1353	QRect full(origin, ds);
1354	painter.drawPixmap(full, *logo);
1355}