all repos — mgba @ 0a9104113c077ad54a2a746ccb61f2c31e3db72e

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