all repos — mgba @ eafcb0f5554ee6c21c0fb1ac73219ed6a2c99e1b

mGBA Game Boy Advance Emulator

src/platform/qt/Window.cpp (view raw)

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