all repos — mgba @ 5665ac0316df4800bec0e942e4d18ba3fec59310

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#ifdef M_CORE_GBA
  53#include <mgba/internal/gba/gba.h>
  54#include <mgba/internal/gba/video.h>
  55#endif
  56#include "feature/commandline.h"
  57#include "feature/sqlite3/no-intro.h"
  58#include <mgba-util/vfs.h>
  59
  60using namespace QGBA;
  61
  62Window::Window(ConfigController* config, int playerId, QWidget* parent)
  63	: QMainWindow(parent)
  64	, m_log(0)
  65	, m_logView(new LogView(&m_log))
  66	, m_stateWindow(nullptr)
  67	, m_screenWidget(new WindowBackground())
  68	, m_logo(":/res/mgba-1024.png")
  69	, m_config(config)
  70	, m_inputController(playerId, this)
  71#ifdef USE_FFMPEG
  72	, m_videoView(nullptr)
  73#endif
  74#ifdef USE_MAGICK
  75	, m_gifView(nullptr)
  76#endif
  77#ifdef USE_GDB_STUB
  78	, m_gdbController(nullptr)
  79#endif
  80#ifdef USE_DEBUGGERS
  81	, m_console(nullptr)
  82#endif
  83	, m_mruMenu(nullptr)
  84	, m_shortcutController(new ShortcutController(this))
  85	, m_fullscreenOnStart(false)
  86	, m_autoresume(false)
  87	, m_wasOpened(false)
  88{
  89	setFocusPolicy(Qt::StrongFocus);
  90	setAcceptDrops(true);
  91	setAttribute(Qt::WA_DeleteOnClose);
  92	m_controller = new GameController(this);
  93	m_controller->setInputController(&m_inputController);
  94	updateTitle();
  95
  96	m_display = Display::create(this);
  97	m_shaderView = new ShaderSelector(m_display, m_config);
  98
  99	m_logo.setDevicePixelRatio(m_screenWidget->devicePixelRatio());
 100	m_logo = m_logo; // Free memory left over in old pixmap
 101
 102	m_screenWidget->setMinimumSize(m_display->minimumSize());
 103	m_screenWidget->setSizePolicy(m_display->sizePolicy());
 104	int i = 2;
 105	QVariant multiplier = m_config->getOption("scaleMultiplier");
 106	if (!multiplier.isNull()) {
 107		m_savedScale = multiplier.toInt();
 108		i = m_savedScale;
 109	}
 110#ifdef USE_SQLITE3
 111	m_libraryView = new LibraryView();
 112	ConfigOption* showLibrary = m_config->addOption("showLibrary");
 113	showLibrary->connect([this](const QVariant& value) {
 114		if (value.toBool()) {
 115			if (m_controller->isLoaded()) {
 116				m_screenWidget->layout()->addWidget(m_libraryView);
 117			} else {
 118				attachWidget(m_libraryView);
 119			}
 120		} else {
 121			detachWidget(m_libraryView);
 122		}
 123	}, this);
 124	m_config->updateOption("showLibrary");
 125
 126	connect(m_libraryView, &LibraryView::accepted, [this]() {
 127		VFile* output = m_libraryView->selectedVFile();
 128		QPair<QString, QString> path = m_libraryView->selectedPath();
 129		if (output) {
 130			m_controller->loadGame(output, path.first, path.second);
 131		}
 132	});
 133#elif defined(M_CORE_GBA)
 134	m_screenWidget->setSizeHint(QSize(VIDEO_HORIZONTAL_PIXELS * i, VIDEO_VERTICAL_PIXELS * i));
 135#endif
 136	m_screenWidget->setPixmap(m_logo);
 137	m_screenWidget->setLockAspectRatio(m_logo.width(), m_logo.height());
 138	m_screenWidget->setLockIntegerScaling(false);
 139	setCentralWidget(m_screenWidget);
 140
 141	connect(m_controller, SIGNAL(gameStarted(mCoreThread*, const QString&)), this, SLOT(gameStarted(mCoreThread*, const QString&)));
 142	connect(m_controller, SIGNAL(gameStarted(mCoreThread*, const QString&)), &m_inputController, SLOT(suspendScreensaver()));
 143	connect(m_controller, SIGNAL(gameStopped(mCoreThread*)), m_display, SLOT(stopDrawing()));
 144	connect(m_controller, SIGNAL(gameStopped(mCoreThread*)), this, SLOT(gameStopped()));
 145	connect(m_controller, SIGNAL(gameStopped(mCoreThread*)), &m_inputController, SLOT(resumeScreensaver()));
 146	connect(m_controller, SIGNAL(stateLoaded(mCoreThread*)), m_display, SLOT(forceDraw()));
 147	connect(m_controller, SIGNAL(rewound(mCoreThread*)), m_display, SLOT(forceDraw()));
 148	connect(m_controller, &GameController::gamePaused, [this](mCoreThread* context) {
 149		unsigned width, height;
 150		context->core->desiredVideoDimensions(context->core, &width, &height);
 151		QImage currentImage(reinterpret_cast<const uchar*>(m_controller->drawContext()), width, height,
 152		                    width * BYTES_PER_PIXEL, QImage::Format_RGBX8888);
 153		QPixmap pixmap;
 154		pixmap.convertFromImage(currentImage);
 155		m_screenWidget->setPixmap(pixmap);
 156		m_screenWidget->setLockAspectRatio(width, height);
 157	});
 158	connect(m_controller, SIGNAL(gamePaused(mCoreThread*)), m_display, SLOT(pauseDrawing()));
 159#ifndef Q_OS_MAC
 160	connect(m_controller, SIGNAL(gamePaused(mCoreThread*)), menuBar(), SLOT(show()));
 161	connect(m_controller, &GameController::gameUnpaused, [this]() {
 162		if(isFullScreen()) {
 163			menuBar()->hide();
 164		}
 165	});
 166#endif
 167	connect(m_controller, SIGNAL(gamePaused(mCoreThread*)), &m_inputController, SLOT(resumeScreensaver()));
 168	connect(m_controller, SIGNAL(gameUnpaused(mCoreThread*)), m_display, SLOT(unpauseDrawing()));
 169	connect(m_controller, SIGNAL(gameUnpaused(mCoreThread*)), &m_inputController, SLOT(suspendScreensaver()));
 170	connect(m_controller, SIGNAL(postLog(int, int, const QString&)), &m_log, SLOT(postLog(int, int, const QString&)));
 171	connect(m_controller, SIGNAL(frameAvailable(const uint32_t*)), this, SLOT(recordFrame()));
 172	connect(m_controller, SIGNAL(frameAvailable(const uint32_t*)), m_display, SLOT(framePosted(const uint32_t*)));
 173	connect(m_controller, SIGNAL(gameCrashed(const QString&)), this, SLOT(gameCrashed(const QString&)));
 174	connect(m_controller, SIGNAL(gameFailed()), this, SLOT(gameFailed()));
 175	connect(m_controller, SIGNAL(unimplementedBiosCall(int)), this, SLOT(unimplementedBiosCall(int)));
 176	connect(m_controller, SIGNAL(statusPosted(const QString&)), m_display, SLOT(showMessage(const QString&)));
 177	connect(&m_log, SIGNAL(levelsSet(int)), m_controller, SLOT(setLogLevel(int)));
 178	connect(&m_log, SIGNAL(levelsEnabled(int)), m_controller, SLOT(enableLogLevel(int)));
 179	connect(&m_log, SIGNAL(levelsDisabled(int)), m_controller, SLOT(disableLogLevel(int)));
 180	connect(this, SIGNAL(startDrawing(mCoreThread*)), m_display, SLOT(startDrawing(mCoreThread*)), Qt::QueuedConnection);
 181	connect(this, SIGNAL(shutdown()), m_display, SLOT(stopDrawing()));
 182	connect(this, SIGNAL(shutdown()), m_controller, SLOT(closeGame()));
 183	connect(this, SIGNAL(shutdown()), m_logView, SLOT(hide()));
 184	connect(this, SIGNAL(shutdown()), m_shaderView, SLOT(hide()));
 185	connect(this, SIGNAL(audioBufferSamplesChanged(int)), m_controller, SLOT(setAudioBufferSamples(int)));
 186	connect(this, SIGNAL(sampleRateChanged(unsigned)), m_controller, SLOT(setAudioSampleRate(unsigned)));
 187	connect(this, SIGNAL(fpsTargetChanged(float)), m_controller, SLOT(setFPSTarget(float)));
 188	connect(&m_fpsTimer, SIGNAL(timeout()), this, SLOT(showFPS()));
 189	connect(&m_focusCheck, SIGNAL(timeout()), this, SLOT(focusCheck()));
 190	connect(m_display, &Display::hideCursor, [this]() {
 191		if (static_cast<QStackedLayout*>(m_screenWidget->layout())->currentWidget() == m_display) {
 192			m_screenWidget->setCursor(Qt::BlankCursor);
 193		}
 194	});
 195	connect(m_display, &Display::showCursor, [this]() {
 196		m_screenWidget->unsetCursor();
 197	});
 198	connect(&m_inputController, SIGNAL(profileLoaded(const QString&)), m_shortcutController, SLOT(loadProfile(const QString&)));
 199
 200	m_log.setLevels(mLOG_WARN | mLOG_ERROR | mLOG_FATAL);
 201	m_fpsTimer.setInterval(FPS_TIMER_INTERVAL);
 202	m_focusCheck.setInterval(200);
 203
 204	m_shortcutController->setConfigController(m_config);
 205	setupMenu(menuBar());
 206}
 207
 208Window::~Window() {
 209	delete m_logView;
 210
 211#ifdef USE_FFMPEG
 212	delete m_videoView;
 213#endif
 214
 215#ifdef USE_MAGICK
 216	delete m_gifView;
 217#endif
 218
 219#ifdef USE_SQLITE3
 220	delete m_libraryView;
 221#endif
 222}
 223
 224void Window::argumentsPassed(mArguments* args) {
 225	loadConfig();
 226
 227	if (args->patch) {
 228		m_controller->loadPatch(args->patch);
 229	}
 230
 231	if (args->fname) {
 232		m_controller->loadGame(args->fname);
 233	}
 234
 235#ifdef USE_GDB_STUB
 236	if (args->debuggerType == DEBUGGER_GDB) {
 237		if (!m_gdbController) {
 238			m_gdbController = new GDBController(m_controller, this);
 239			m_gdbController->listen();
 240		}
 241	}
 242#endif
 243}
 244
 245void Window::resizeFrame(const QSize& size) {
 246	QSize newSize(size);
 247#if (QT_VERSION >= QT_VERSION_CHECK(5, 6, 0))
 248	newSize /= m_screenWidget->devicePixelRatioF();
 249#endif
 250	m_screenWidget->setSizeHint(newSize);
 251	newSize -= m_screenWidget->size();
 252	newSize += this->size();
 253	resize(newSize);
 254}
 255
 256void Window::setConfig(ConfigController* config) {
 257	m_config = config;
 258}
 259
 260void Window::loadConfig() {
 261	const mCoreOptions* opts = m_config->options();
 262	reloadConfig();
 263
 264	// TODO: Move these to ConfigController
 265	if (opts->fpsTarget) {
 266		emit fpsTargetChanged(opts->fpsTarget);
 267	}
 268
 269	if (opts->audioBuffers) {
 270		emit audioBufferSamplesChanged(opts->audioBuffers);
 271	}
 272
 273	if (opts->sampleRate) {
 274		emit sampleRateChanged(opts->sampleRate);
 275	}
 276
 277	if (opts->width && opts->height) {
 278		resizeFrame(QSize(opts->width, opts->height));
 279	}
 280
 281	if (opts->fullscreen) {
 282		enterFullScreen();
 283	}
 284
 285	if (opts->shader) {
 286		struct VDir* shader = VDirOpen(opts->shader);
 287		if (shader) {
 288			m_display->setShaders(shader);
 289			m_shaderView->refreshShaders();
 290			shader->close(shader);
 291		}
 292	}
 293
 294	m_mruFiles = m_config->getMRU();
 295	updateMRU();
 296
 297	m_inputController.setConfiguration(m_config);
 298	m_controller->setUseBIOS(opts->useBios);
 299}
 300
 301void Window::reloadConfig() {
 302	const mCoreOptions* opts = m_config->options();
 303
 304	m_log.setLevels(opts->logLevel);
 305
 306	m_controller->setConfig(m_config->config());
 307	m_display->lockAspectRatio(opts->lockAspectRatio);
 308	m_display->filter(opts->resampleVideo);
 309
 310	m_inputController.setScreensaverSuspendable(opts->suspendScreensaver);
 311}
 312
 313void Window::saveConfig() {
 314	m_inputController.saveConfiguration();
 315	m_config->write();
 316}
 317
 318QString Window::getFilters() const {
 319	QStringList filters;
 320	QStringList formats;
 321
 322#ifdef M_CORE_GBA
 323	QStringList gbaFormats{
 324		"*.gba",
 325#if defined(USE_LIBZIP) || defined(USE_ZLIB)
 326		"*.zip",
 327#endif
 328#ifdef USE_LZMA
 329		"*.7z",
 330#endif
 331		"*.agb",
 332		"*.mb",
 333		"*.rom",
 334		"*.bin"};
 335	formats.append(gbaFormats);
 336	filters.append(tr("Game Boy Advance ROMs (%1)").arg(gbaFormats.join(QChar(' '))));
 337#endif
 338
 339#ifdef M_CORE_GB
 340	QStringList gbFormats{
 341		"*.gb",
 342		"*.gbc",
 343#if defined(USE_LIBZIP) || defined(USE_ZLIB)
 344		"*.zip",
 345#endif
 346#ifdef USE_LZMA
 347		"*.7z",
 348#endif
 349		"*.rom",
 350		"*.bin"};
 351	formats.append(gbFormats);
 352	filters.append(tr("Game Boy ROMs (%1)").arg(gbFormats.join(QChar(' '))));
 353#endif
 354
 355	formats.removeDuplicates();
 356	filters.prepend(tr("All ROMs (%1)").arg(formats.join(QChar(' '))));
 357	filters.append(tr("%1 Video Logs (*.mvl)").arg(projectName));
 358	return filters.join(";;");
 359}
 360
 361QString Window::getFiltersArchive() const {
 362	QStringList filters;
 363
 364	QStringList formats{
 365#if defined(USE_LIBZIP) || defined(USE_ZLIB)
 366		"*.zip",
 367#endif
 368#ifdef USE_LZMA
 369		"*.7z",
 370#endif
 371	};
 372	filters.append(tr("Archives (%1)").arg(formats.join(QChar(' '))));
 373	return filters.join(";;");
 374}
 375
 376void Window::selectROM() {
 377	QString filename = GBAApp::app()->getOpenFileName(this, tr("Select ROM"), getFilters());
 378	if (!filename.isEmpty()) {
 379		m_controller->loadGame(filename);
 380	}
 381}
 382
 383#ifdef USE_SQLITE3
 384void Window::selectROMInArchive() {
 385	QString filename = GBAApp::app()->getOpenFileName(this, tr("Select ROM"), getFiltersArchive());
 386	if (filename.isEmpty()) {
 387		return;
 388	}
 389	ArchiveInspector* archiveInspector = new ArchiveInspector(filename);
 390	connect(archiveInspector, &QDialog::accepted, [this,  archiveInspector]() {
 391		VFile* output = archiveInspector->selectedVFile();
 392		QPair<QString, QString> path = archiveInspector->selectedPath();
 393		if (output) {
 394			m_controller->loadGame(output, path.second, path.first);
 395		}
 396		archiveInspector->close();
 397	});
 398	archiveInspector->setAttribute(Qt::WA_DeleteOnClose);
 399	archiveInspector->show();
 400}
 401
 402void Window::addDirToLibrary() {
 403	QString filename = GBAApp::app()->getOpenDirectoryName(this, tr("Select folder"));
 404	if (filename.isEmpty()) {
 405		return;
 406	}
 407	m_libraryView->addDirectory(filename);
 408}
 409#endif
 410
 411void Window::replaceROM() {
 412	QString filename = GBAApp::app()->getOpenFileName(this, tr("Select ROM"), getFilters());
 413	if (!filename.isEmpty()) {
 414		m_controller->replaceGame(filename);
 415	}
 416}
 417
 418void Window::selectSave(bool temporary) {
 419	QStringList formats{"*.sav"};
 420	QString filter = tr("Game Boy Advance save files (%1)").arg(formats.join(QChar(' ')));
 421	QString filename = GBAApp::app()->getOpenFileName(this, tr("Select save"), filter);
 422	if (!filename.isEmpty()) {
 423		m_controller->loadSave(filename, temporary);
 424	}
 425}
 426
 427void Window::multiplayerChanged() {
 428	int attached = 1;
 429	MultiplayerController* multiplayer = m_controller->multiplayerController();
 430	if (multiplayer) {
 431		attached = multiplayer->attached();
 432	}
 433	if (m_controller->isLoaded()) {
 434		for (QAction* action : m_nonMpActions) {
 435			action->setDisabled(attached > 1);
 436		}
 437	}
 438}
 439
 440void Window::selectPatch() {
 441	QString filename = GBAApp::app()->getOpenFileName(this, tr("Select patch"), tr("Patches (*.ips *.ups *.bps)"));
 442	if (!filename.isEmpty()) {
 443		m_controller->loadPatch(filename);
 444	}
 445}
 446
 447void Window::openView(QWidget* widget) {
 448	connect(this, SIGNAL(shutdown()), widget, SLOT(close()));
 449	connect(m_controller, SIGNAL(gameStopped(mCoreThread*)), widget, SLOT(close()));
 450	widget->setAttribute(Qt::WA_DeleteOnClose);
 451	widget->show();
 452}
 453
 454void Window::importSharkport() {
 455	QString filename = GBAApp::app()->getOpenFileName(this, tr("Select save"), tr("GameShark saves (*.sps *.xps)"));
 456	if (!filename.isEmpty()) {
 457		m_controller->importSharkport(filename);
 458	}
 459}
 460
 461void Window::exportSharkport() {
 462	QString filename = GBAApp::app()->getSaveFileName(this, tr("Select save"), tr("GameShark saves (*.sps *.xps)"));
 463	if (!filename.isEmpty()) {
 464		m_controller->exportSharkport(filename);
 465	}
 466}
 467
 468void Window::openSettingsWindow() {
 469	SettingsView* settingsWindow = new SettingsView(m_config, &m_inputController, m_shortcutController);
 470	connect(settingsWindow, SIGNAL(biosLoaded(int, const QString&)), m_controller, SLOT(loadBIOS(int, const QString&)));
 471	connect(settingsWindow, SIGNAL(audioDriverChanged()), m_controller, SLOT(reloadAudioDriver()));
 472	connect(settingsWindow, SIGNAL(displayDriverChanged()), this, SLOT(mustRestart()));
 473	connect(settingsWindow, SIGNAL(pathsChanged()), this, SLOT(reloadConfig()));
 474	openView(settingsWindow);
 475}
 476
 477void Window::openAboutScreen() {
 478	AboutScreen* about = new AboutScreen();
 479	openView(about);
 480}
 481
 482void Window::startVideoLog() {
 483	QString filename = GBAApp::app()->getSaveFileName(this, tr("Select video log"), tr("Video logs (*.mvl)"));
 484	if (!filename.isEmpty()) {
 485		m_controller->startVideoLog(filename);
 486	}
 487}
 488
 489template <typename T, typename A>
 490std::function<void()> Window::openTView(A arg) {
 491	return [=]() {
 492		T* view = new T(m_controller, arg);
 493		openView(view);
 494	};
 495}
 496
 497template <typename T>
 498std::function<void()> Window::openTView() {
 499	return [=]() {
 500		T* view = new T(m_controller);
 501		openView(view);
 502	};
 503}
 504
 505#ifdef USE_FFMPEG
 506void Window::openVideoWindow() {
 507	if (!m_videoView) {
 508		m_videoView = new VideoView();
 509		connect(m_videoView, SIGNAL(recordingStarted(mAVStream*)), m_controller, SLOT(setAVStream(mAVStream*)));
 510		connect(m_videoView, SIGNAL(recordingStopped()), m_controller, SLOT(clearAVStream()), Qt::DirectConnection);
 511		connect(m_controller, SIGNAL(gameStopped(mCoreThread*)), m_videoView, SLOT(stopRecording()));
 512		connect(m_controller, SIGNAL(gameStopped(mCoreThread*)), m_videoView, SLOT(close()));
 513		connect(m_controller, &GameController::gameStarted, [this]() {
 514			m_videoView->setNativeResolution(m_controller->screenDimensions());
 515		});
 516		if (m_controller->isLoaded()) {
 517			m_videoView->setNativeResolution(m_controller->screenDimensions());
 518		}
 519		connect(this, SIGNAL(shutdown()), m_videoView, SLOT(close()));
 520	}
 521	m_videoView->show();
 522}
 523#endif
 524
 525#ifdef USE_MAGICK
 526void Window::openGIFWindow() {
 527	if (!m_gifView) {
 528		m_gifView = new GIFView();
 529		connect(m_gifView, SIGNAL(recordingStarted(mAVStream*)), m_controller, SLOT(setAVStream(mAVStream*)));
 530		connect(m_gifView, SIGNAL(recordingStopped()), m_controller, SLOT(clearAVStream()), Qt::DirectConnection);
 531		connect(m_controller, SIGNAL(gameStopped(mCoreThread*)), m_gifView, SLOT(stopRecording()));
 532		connect(m_controller, SIGNAL(gameStopped(mCoreThread*)), m_gifView, SLOT(close()));
 533		connect(this, SIGNAL(shutdown()), m_gifView, SLOT(close()));
 534	}
 535	m_gifView->show();
 536}
 537#endif
 538
 539#ifdef USE_GDB_STUB
 540void Window::gdbOpen() {
 541	if (!m_gdbController) {
 542		m_gdbController = new GDBController(m_controller, this);
 543	}
 544	GDBWindow* window = new GDBWindow(m_gdbController);
 545	openView(window);
 546}
 547#endif
 548
 549#ifdef USE_DEBUGGERS
 550void Window::consoleOpen() {
 551	if (!m_console) {
 552		m_console = new DebuggerConsoleController(m_controller, this);
 553	}
 554	DebuggerConsole* window = new DebuggerConsole(m_console);
 555	openView(window);
 556}
 557#endif
 558
 559void Window::keyPressEvent(QKeyEvent* event) {
 560	if (event->isAutoRepeat()) {
 561		QWidget::keyPressEvent(event);
 562		return;
 563	}
 564	GBAKey key = m_inputController.mapKeyboard(event->key());
 565	if (key == GBA_KEY_NONE) {
 566		QWidget::keyPressEvent(event);
 567		return;
 568	}
 569	m_controller->keyPressed(key);
 570	event->accept();
 571}
 572
 573void Window::keyReleaseEvent(QKeyEvent* event) {
 574	if (event->isAutoRepeat()) {
 575		QWidget::keyReleaseEvent(event);
 576		return;
 577	}
 578	GBAKey key = m_inputController.mapKeyboard(event->key());
 579	if (key == GBA_KEY_NONE) {
 580		QWidget::keyPressEvent(event);
 581		return;
 582	}
 583	m_controller->keyReleased(key);
 584	event->accept();
 585}
 586
 587void Window::resizeEvent(QResizeEvent* event) {
 588	if (!isFullScreen()) {
 589		m_config->setOption("height", m_screenWidget->height());
 590		m_config->setOption("width", m_screenWidget->width());
 591	}
 592
 593	int factor = 0;
 594	QSize size(VIDEO_HORIZONTAL_PIXELS, VIDEO_VERTICAL_PIXELS);
 595	if (m_controller->isLoaded()) {
 596		size = m_controller->screenDimensions();
 597	}
 598	if (m_screenWidget->width() % size.width() == 0 && m_screenWidget->height() % size.height() == 0 &&
 599	    m_screenWidget->width() / size.width() == m_screenWidget->height() / size.height()) {
 600		factor = m_screenWidget->width() / size.width();
 601	} else {
 602		m_savedScale = 0;
 603	}
 604	for (QMap<int, QAction*>::iterator iter = m_frameSizes.begin(); iter != m_frameSizes.end(); ++iter) {
 605		bool enableSignals = iter.value()->blockSignals(true);
 606		iter.value()->setChecked(iter.key() == factor);
 607		iter.value()->blockSignals(enableSignals);
 608	}
 609
 610	m_config->setOption("fullscreen", isFullScreen());
 611}
 612
 613void Window::showEvent(QShowEvent* event) {
 614	if (m_wasOpened) {
 615		return;
 616	}
 617	m_wasOpened = true;
 618	resizeFrame(m_screenWidget->sizeHint());
 619	QVariant windowPos = m_config->getQtOption("windowPos");
 620	if (!windowPos.isNull()) {
 621		move(windowPos.toPoint());
 622	} else {
 623		QRect rect = frameGeometry();
 624		rect.moveCenter(QApplication::desktop()->availableGeometry().center());
 625		move(rect.topLeft());
 626	}
 627	if (m_fullscreenOnStart) {
 628		enterFullScreen();
 629		m_fullscreenOnStart = false;
 630	}
 631}
 632
 633void Window::closeEvent(QCloseEvent* event) {
 634	emit shutdown();
 635	m_config->setQtOption("windowPos", pos());
 636
 637	if (m_savedScale > 0) {
 638		m_config->setOption("height", VIDEO_VERTICAL_PIXELS * m_savedScale);
 639		m_config->setOption("width", VIDEO_HORIZONTAL_PIXELS * m_savedScale);
 640	}
 641	saveConfig();
 642	QMainWindow::closeEvent(event);
 643}
 644
 645void Window::focusInEvent(QFocusEvent*) {
 646	m_display->forceDraw();
 647}
 648
 649void Window::focusOutEvent(QFocusEvent*) {
 650	m_controller->setTurbo(false, false);
 651	m_controller->stopRewinding();
 652	m_controller->clearKeys();
 653}
 654
 655void Window::dragEnterEvent(QDragEnterEvent* event) {
 656	if (event->mimeData()->hasFormat("text/uri-list")) {
 657		event->acceptProposedAction();
 658	}
 659}
 660
 661void Window::dropEvent(QDropEvent* event) {
 662	QString uris = event->mimeData()->data("text/uri-list");
 663	uris = uris.trimmed();
 664	if (uris.contains("\n")) {
 665		// Only one file please
 666		return;
 667	}
 668	QUrl url(uris);
 669	if (!url.isLocalFile()) {
 670		// No remote loading
 671		return;
 672	}
 673	event->accept();
 674	m_controller->loadGame(url.toLocalFile());
 675}
 676
 677void Window::mouseDoubleClickEvent(QMouseEvent* event) {
 678	if (event->button() != Qt::LeftButton) {
 679		return;
 680	}
 681	toggleFullScreen();
 682}
 683
 684void Window::enterFullScreen() {
 685	if (!isVisible()) {
 686		m_fullscreenOnStart = true;
 687		return;
 688	}
 689	if (isFullScreen()) {
 690		return;
 691	}
 692	showFullScreen();
 693#ifndef Q_OS_MAC
 694	if (m_controller->isLoaded() && !m_controller->isPaused()) {
 695		menuBar()->hide();
 696	}
 697#endif
 698}
 699
 700void Window::exitFullScreen() {
 701	if (!isFullScreen()) {
 702		return;
 703	}
 704	m_screenWidget->unsetCursor();
 705	menuBar()->show();
 706	showNormal();
 707}
 708
 709void Window::toggleFullScreen() {
 710	if (isFullScreen()) {
 711		exitFullScreen();
 712	} else {
 713		enterFullScreen();
 714	}
 715}
 716
 717void Window::gameStarted(mCoreThread* context, const QString& fname) {
 718	MutexLock(&context->stateMutex);
 719	if (context->state < THREAD_EXITING) {
 720		emit startDrawing(context);
 721	} else {
 722		MutexUnlock(&context->stateMutex);
 723		return;
 724	}
 725	MutexUnlock(&context->stateMutex);
 726	foreach (QAction* action, m_gameActions) {
 727		action->setDisabled(false);
 728	}
 729#ifdef M_CORE_GBA
 730	foreach (QAction* action, m_gbaActions) {
 731		action->setDisabled(context->core->platform(context->core) != PLATFORM_GBA);
 732	}
 733#endif
 734	multiplayerChanged();
 735	if (!fname.isEmpty()) {
 736		setWindowFilePath(fname);
 737		appendMRU(fname);
 738	}
 739	updateTitle();
 740	unsigned width, height;
 741	context->core->desiredVideoDimensions(context->core, &width, &height);
 742	m_display->setMinimumSize(width, height);
 743	m_screenWidget->setMinimumSize(m_display->minimumSize());
 744	m_config->updateOption("lockIntegerScaling");
 745	if (m_savedScale > 0) {
 746		resizeFrame(QSize(width, height) * m_savedScale);
 747	}
 748	attachWidget(m_display);
 749
 750#ifndef Q_OS_MAC
 751	if (isFullScreen()) {
 752		menuBar()->hide();
 753	}
 754#endif
 755
 756	m_hitUnimplementedBiosCall = false;
 757	m_fpsTimer.start();
 758	m_focusCheck.start();
 759
 760	m_controller->threadInterrupt();
 761	if (m_controller->isLoaded()) {
 762		mCore* core = m_controller->thread()->core;
 763		const mCoreChannelInfo* videoLayers;
 764		const mCoreChannelInfo* audioChannels;
 765		size_t nVideo = core->listVideoLayers(core, &videoLayers);
 766		size_t nAudio = core->listAudioChannels(core, &audioChannels);
 767
 768		if (nVideo) {
 769			for (size_t i = 0; i < nVideo; ++i) {
 770				QAction* action = new QAction(videoLayers[i].visibleName, m_videoLayers);
 771				action->setCheckable(true);
 772				action->setChecked(true);
 773				connect(action, &QAction::triggered, [this, videoLayers, i](bool enable) {
 774					m_controller->setVideoLayerEnabled(videoLayers[i].id, enable);
 775				});
 776				m_videoLayers->addAction(action);
 777			}
 778		}
 779		if (nAudio) {
 780			for (size_t i = 0; i < nAudio; ++i) {
 781				QAction* action = new QAction(audioChannels[i].visibleName, m_audioChannels);
 782				action->setCheckable(true);
 783				action->setChecked(true);
 784				connect(action, &QAction::triggered, [this, audioChannels, i](bool enable) {
 785					m_controller->setAudioChannelEnabled(audioChannels[i].id, enable);
 786				});
 787				m_audioChannels->addAction(action);
 788			}
 789		}
 790	}
 791	m_controller->threadContinue();
 792}
 793
 794void Window::gameStopped() {
 795#ifdef M_CORE_GBA
 796	foreach (QAction* action, m_gbaActions) {
 797		action->setDisabled(false);
 798	}
 799#endif
 800	foreach (QAction* action, m_gameActions) {
 801		action->setDisabled(true);
 802	}
 803	setWindowFilePath(QString());
 804	updateTitle();
 805	detachWidget(m_display);
 806	m_screenWidget->setLockAspectRatio(m_logo.width(), m_logo.height());
 807	m_screenWidget->setLockIntegerScaling(false);
 808	m_screenWidget->setPixmap(m_logo);
 809	m_screenWidget->unsetCursor();
 810#ifdef M_CORE_GB
 811	m_display->setMinimumSize(GB_VIDEO_HORIZONTAL_PIXELS, GB_VIDEO_VERTICAL_PIXELS);
 812#elif defined(M_CORE_GBA)
 813	m_display->setMinimumSize(VIDEO_HORIZONTAL_PIXELS, VIDEO_VERTICAL_PIXELS);
 814#endif
 815	m_screenWidget->setMinimumSize(m_display->minimumSize());
 816
 817	m_videoLayers->clear();
 818	m_audioChannels->clear();
 819
 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		m_controller->setVideoSync(value.toBool());
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		m_controller->setAudioSync(value.toBool());
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* lockIntegerScaling = m_config->addOption("lockIntegerScaling");
1278	lockIntegerScaling->addBoolean(tr("Force integer scaling"), avMenu);
1279	lockIntegerScaling->connect([this](const QVariant& value) {
1280		m_display->lockIntegerScaling(value.toBool());
1281		if (m_controller->isLoaded()) {
1282			m_screenWidget->setLockIntegerScaling(value.toBool());
1283		}
1284	}, this);
1285	m_config->updateOption("lockIntegerScaling");
1286
1287	ConfigOption* resampleVideo = m_config->addOption("resampleVideo");
1288	resampleVideo->addBoolean(tr("Bilinear filtering"), avMenu);
1289	resampleVideo->connect([this](const QVariant& value) {
1290		m_display->filter(value.toBool());
1291	}, this);
1292	m_config->updateOption("resampleVideo");
1293
1294	QMenu* skipMenu = avMenu->addMenu(tr("Frame&skip"));
1295	ConfigOption* skip = m_config->addOption("frameskip");
1296	skip->connect([this](const QVariant& value) {
1297		reloadConfig();
1298	}, this);
1299	for (int i = 0; i <= 10; ++i) {
1300		skip->addValue(QString::number(i), i, skipMenu);
1301	}
1302	m_config->updateOption("frameskip");
1303
1304	QAction* shaderView = new QAction(tr("Shader options..."), avMenu);
1305	connect(shaderView, SIGNAL(triggered()), m_shaderView, SLOT(show()));
1306	if (!m_display->supportsShaders()) {
1307		shaderView->setEnabled(false);
1308	}
1309	addControlledAction(avMenu, shaderView, "shaderSelector");
1310
1311	avMenu->addSeparator();
1312
1313	ConfigOption* mute = m_config->addOption("mute");
1314	QAction* muteAction = mute->addBoolean(tr("Mute"), avMenu);
1315	mute->connect([this](const QVariant& value) {
1316		reloadConfig();
1317	}, this);
1318	m_config->updateOption("mute");
1319	addControlledAction(avMenu, muteAction, "mute");
1320
1321	QMenu* target = avMenu->addMenu(tr("FPS target"));
1322	ConfigOption* fpsTargetOption = m_config->addOption("fpsTarget");
1323	fpsTargetOption->connect([this](const QVariant& value) {
1324		emit fpsTargetChanged(value.toFloat());
1325	}, this);
1326	fpsTargetOption->addValue(tr("15"), 15, target);
1327	fpsTargetOption->addValue(tr("30"), 30, target);
1328	fpsTargetOption->addValue(tr("45"), 45, target);
1329	fpsTargetOption->addValue(tr("Native (59.7)"), float(GBA_ARM7TDMI_FREQUENCY) / float(VIDEO_TOTAL_LENGTH), target);
1330	fpsTargetOption->addValue(tr("60"), 60, target);
1331	fpsTargetOption->addValue(tr("90"), 90, target);
1332	fpsTargetOption->addValue(tr("120"), 120, target);
1333	fpsTargetOption->addValue(tr("240"), 240, target);
1334	m_config->updateOption("fpsTarget");
1335
1336#if defined(USE_PNG) || defined(USE_FFMPEG) || defined(USE_MAGICK)
1337	avMenu->addSeparator();
1338#endif
1339
1340#ifdef USE_PNG
1341	QAction* screenshot = new QAction(tr("Take &screenshot"), avMenu);
1342	screenshot->setShortcut(tr("F12"));
1343	connect(screenshot, SIGNAL(triggered()), m_controller, SLOT(screenshot()));
1344	m_gameActions.append(screenshot);
1345	addControlledAction(avMenu, screenshot, "screenshot");
1346#endif
1347
1348#ifdef USE_FFMPEG
1349	QAction* recordOutput = new QAction(tr("Record output..."), avMenu);
1350	connect(recordOutput, SIGNAL(triggered()), this, SLOT(openVideoWindow()));
1351	addControlledAction(avMenu, recordOutput, "recordOutput");
1352	m_gameActions.append(recordOutput);
1353#endif
1354
1355#ifdef USE_MAGICK
1356	QAction* recordGIF = new QAction(tr("Record GIF..."), avMenu);
1357	connect(recordGIF, SIGNAL(triggered()), this, SLOT(openGIFWindow()));
1358	addControlledAction(avMenu, recordGIF, "recordGIF");
1359#endif
1360
1361	QAction* recordVL = new QAction(tr("Record video log..."), avMenu);
1362	connect(recordVL, SIGNAL(triggered()), this, SLOT(startVideoLog()));
1363	addControlledAction(avMenu, recordVL, "recordVL");
1364	m_gameActions.append(recordVL);
1365
1366	QAction* stopVL = new QAction(tr("Stop video log"), avMenu);
1367	connect(stopVL, SIGNAL(triggered()), m_controller, SLOT(endVideoLog()));
1368	addControlledAction(avMenu, stopVL, "stopVL");
1369	m_gameActions.append(stopVL);
1370
1371	avMenu->addSeparator();
1372	m_videoLayers = avMenu->addMenu(tr("Video layers"));
1373	m_shortcutController->addMenu(m_videoLayers, avMenu);
1374
1375	m_audioChannels = avMenu->addMenu(tr("Audio channels"));
1376	m_shortcutController->addMenu(m_audioChannels, avMenu);
1377
1378	QMenu* toolsMenu = menubar->addMenu(tr("&Tools"));
1379	m_shortcutController->addMenu(toolsMenu);
1380	QAction* viewLogs = new QAction(tr("View &logs..."), toolsMenu);
1381	connect(viewLogs, SIGNAL(triggered()), m_logView, SLOT(show()));
1382	addControlledAction(toolsMenu, viewLogs, "viewLogs");
1383
1384	QAction* overrides = new QAction(tr("Game &overrides..."), toolsMenu);
1385	connect(overrides, &QAction::triggered, openTView<OverrideView, ConfigController*>(m_config));
1386	addControlledAction(toolsMenu, overrides, "overrideWindow");
1387
1388	QAction* sensors = new QAction(tr("Game &Pak sensors..."), toolsMenu);
1389	connect(sensors, &QAction::triggered, openTView<SensorView, InputController*>(&m_inputController));
1390	addControlledAction(toolsMenu, sensors, "sensorWindow");
1391
1392	QAction* cheats = new QAction(tr("&Cheats..."), toolsMenu);
1393	connect(cheats, &QAction::triggered, openTView<CheatsView>());
1394	m_gameActions.append(cheats);
1395	addControlledAction(toolsMenu, cheats, "cheatsWindow");
1396
1397	toolsMenu->addSeparator();
1398	addControlledAction(toolsMenu, toolsMenu->addAction(tr("Settings..."), this, SLOT(openSettingsWindow())),
1399	                    "settings");
1400
1401	toolsMenu->addSeparator();
1402
1403#ifdef USE_DEBUGGERS
1404	QAction* consoleWindow = new QAction(tr("Open debugger console..."), toolsMenu);
1405	connect(consoleWindow, SIGNAL(triggered()), this, SLOT(consoleOpen()));
1406	addControlledAction(toolsMenu, consoleWindow, "debuggerWindow");
1407#endif
1408
1409#ifdef USE_GDB_STUB
1410	QAction* gdbWindow = new QAction(tr("Start &GDB server..."), toolsMenu);
1411	connect(gdbWindow, SIGNAL(triggered()), this, SLOT(gdbOpen()));
1412	m_gbaActions.append(gdbWindow);
1413	addControlledAction(toolsMenu, gdbWindow, "gdbWindow");
1414#endif
1415	toolsMenu->addSeparator();
1416
1417	QAction* paletteView = new QAction(tr("View &palette..."), toolsMenu);
1418	connect(paletteView, &QAction::triggered, openTView<PaletteView>());
1419	m_gameActions.append(paletteView);
1420	addControlledAction(toolsMenu, paletteView, "paletteWindow");
1421
1422	QAction* objView = new QAction(tr("View &sprites..."), toolsMenu);
1423	connect(objView, &QAction::triggered, openTView<ObjView>());
1424	m_gameActions.append(objView);
1425	addControlledAction(toolsMenu, objView, "spriteWindow");
1426
1427	QAction* tileView = new QAction(tr("View &tiles..."), toolsMenu);
1428	connect(tileView, &QAction::triggered, openTView<TileView>());
1429	m_gameActions.append(tileView);
1430	addControlledAction(toolsMenu, tileView, "tileWindow");
1431
1432	QAction* memoryView = new QAction(tr("View memory..."), toolsMenu);
1433	connect(memoryView, &QAction::triggered, openTView<MemoryView>());
1434	m_gameActions.append(memoryView);
1435	addControlledAction(toolsMenu, memoryView, "memoryView");
1436
1437#ifdef M_CORE_GBA
1438	QAction* ioViewer = new QAction(tr("View &I/O registers..."), toolsMenu);
1439	connect(ioViewer, &QAction::triggered, openTView<IOViewer>());
1440	m_gameActions.append(ioViewer);
1441	m_gbaActions.append(ioViewer);
1442	addControlledAction(toolsMenu, ioViewer, "ioViewer");
1443#endif
1444
1445	ConfigOption* skipBios = m_config->addOption("skipBios");
1446	skipBios->connect([this](const QVariant& value) {
1447		reloadConfig();
1448	}, this);
1449
1450	ConfigOption* useBios = m_config->addOption("useBios");
1451	useBios->connect([this](const QVariant& value) {
1452		m_controller->setUseBIOS(value.toBool());
1453	}, this);
1454
1455	ConfigOption* buffers = m_config->addOption("audioBuffers");
1456	buffers->connect([this](const QVariant& value) {
1457		emit audioBufferSamplesChanged(value.toInt());
1458	}, this);
1459
1460	ConfigOption* sampleRate = m_config->addOption("sampleRate");
1461	sampleRate->connect([this](const QVariant& value) {
1462		emit sampleRateChanged(value.toUInt());
1463	}, this);
1464
1465	ConfigOption* volume = m_config->addOption("volume");
1466	volume->connect([this](const QVariant& value) {
1467		reloadConfig();
1468	}, this);
1469
1470	ConfigOption* rewindEnable = m_config->addOption("rewindEnable");
1471	rewindEnable->connect([this](const QVariant& value) {
1472		m_controller->setRewind(value.toBool(), m_config->getOption("rewindBufferCapacity").toInt(), m_config->getOption("rewindSave").toInt());
1473	}, this);
1474
1475	ConfigOption* rewindBufferCapacity = m_config->addOption("rewindBufferCapacity");
1476	rewindBufferCapacity->connect([this](const QVariant& value) {
1477		m_controller->setRewind(m_config->getOption("rewindEnable").toInt(), value.toInt(), m_config->getOption("rewindSave").toInt());
1478	}, this);
1479
1480	ConfigOption* rewindSave = m_config->addOption("rewindSave");
1481	rewindBufferCapacity->connect([this](const QVariant& value) {
1482		m_controller->setRewind(m_config->getOption("rewindEnable").toInt(), m_config->getOption("rewindBufferCapacity").toInt(), value.toBool());
1483	}, this);
1484
1485	ConfigOption* allowOpposingDirections = m_config->addOption("allowOpposingDirections");
1486	allowOpposingDirections->connect([this](const QVariant& value) {
1487		m_inputController.setAllowOpposing(value.toBool());
1488	}, this);
1489
1490	ConfigOption* saveStateExtdata = m_config->addOption("saveStateExtdata");
1491	saveStateExtdata->connect([this](const QVariant& value) {
1492		m_controller->setSaveStateExtdata(value.toInt());
1493	}, this);
1494	m_config->updateOption("saveStateExtdata");
1495
1496	ConfigOption* loadStateExtdata = m_config->addOption("loadStateExtdata");
1497	loadStateExtdata->connect([this](const QVariant& value) {
1498		m_controller->setLoadStateExtdata(value.toInt());
1499	}, this);
1500	m_config->updateOption("loadStateExtdata");
1501
1502	ConfigOption* preload = m_config->addOption("preload");
1503	preload->connect([this](const QVariant& value) {
1504		m_controller->setPreload(value.toBool());
1505	}, this);
1506	m_config->updateOption("preload");
1507
1508	QAction* exitFullScreen = new QAction(tr("Exit fullscreen"), frameMenu);
1509	connect(exitFullScreen, SIGNAL(triggered()), this, SLOT(exitFullScreen()));
1510	exitFullScreen->setShortcut(QKeySequence("Esc"));
1511	addHiddenAction(frameMenu, exitFullScreen, "exitFullScreen");
1512
1513	QMenu* autofireMenu = new QMenu(tr("Autofire"), this);
1514	m_shortcutController->addMenu(autofireMenu);
1515
1516	m_shortcutController->addFunctions(autofireMenu, [this]() {
1517		m_controller->setAutofire(GBA_KEY_A, true);
1518	}, [this]() {
1519		m_controller->setAutofire(GBA_KEY_A, false);
1520	}, QKeySequence(), tr("Autofire A"), "autofireA");
1521
1522	m_shortcutController->addFunctions(autofireMenu, [this]() {
1523		m_controller->setAutofire(GBA_KEY_B, true);
1524	}, [this]() {
1525		m_controller->setAutofire(GBA_KEY_B, false);
1526	}, QKeySequence(), tr("Autofire B"), "autofireB");
1527
1528	m_shortcutController->addFunctions(autofireMenu, [this]() {
1529		m_controller->setAutofire(GBA_KEY_L, true);
1530	}, [this]() {
1531		m_controller->setAutofire(GBA_KEY_L, false);
1532	}, QKeySequence(), tr("Autofire L"), "autofireL");
1533
1534	m_shortcutController->addFunctions(autofireMenu, [this]() {
1535		m_controller->setAutofire(GBA_KEY_R, true);
1536	}, [this]() {
1537		m_controller->setAutofire(GBA_KEY_R, false);
1538	}, QKeySequence(), tr("Autofire R"), "autofireR");
1539
1540	m_shortcutController->addFunctions(autofireMenu, [this]() {
1541		m_controller->setAutofire(GBA_KEY_START, true);
1542	}, [this]() {
1543		m_controller->setAutofire(GBA_KEY_START, false);
1544	}, QKeySequence(), tr("Autofire Start"), "autofireStart");
1545
1546	m_shortcutController->addFunctions(autofireMenu, [this]() {
1547		m_controller->setAutofire(GBA_KEY_SELECT, true);
1548	}, [this]() {
1549		m_controller->setAutofire(GBA_KEY_SELECT, false);
1550	}, QKeySequence(), tr("Autofire Select"), "autofireSelect");
1551
1552	m_shortcutController->addFunctions(autofireMenu, [this]() {
1553		m_controller->setAutofire(GBA_KEY_UP, true);
1554	}, [this]() {
1555		m_controller->setAutofire(GBA_KEY_UP, false);
1556	}, QKeySequence(), tr("Autofire Up"), "autofireUp");
1557
1558	m_shortcutController->addFunctions(autofireMenu, [this]() {
1559		m_controller->setAutofire(GBA_KEY_RIGHT, true);
1560	}, [this]() {
1561		m_controller->setAutofire(GBA_KEY_RIGHT, false);
1562	}, QKeySequence(), tr("Autofire Right"), "autofireRight");
1563
1564	m_shortcutController->addFunctions(autofireMenu, [this]() {
1565		m_controller->setAutofire(GBA_KEY_DOWN, true);
1566	}, [this]() {
1567		m_controller->setAutofire(GBA_KEY_DOWN, false);
1568	}, QKeySequence(), tr("Autofire Down"), "autofireDown");
1569
1570	m_shortcutController->addFunctions(autofireMenu, [this]() {
1571		m_controller->setAutofire(GBA_KEY_LEFT, true);
1572	}, [this]() {
1573		m_controller->setAutofire(GBA_KEY_LEFT, false);
1574	}, QKeySequence(), tr("Autofire Left"), "autofireLeft");
1575
1576	foreach (QAction* action, m_gameActions) {
1577		action->setDisabled(true);
1578	}
1579}
1580
1581void Window::attachWidget(QWidget* widget) {
1582	m_screenWidget->layout()->addWidget(widget);
1583	m_screenWidget->unsetCursor();
1584	static_cast<QStackedLayout*>(m_screenWidget->layout())->setCurrentWidget(widget);
1585}
1586
1587void Window::detachWidget(QWidget* widget) {
1588	m_screenWidget->layout()->removeWidget(widget);
1589}
1590
1591void Window::appendMRU(const QString& fname) {
1592	int index = m_mruFiles.indexOf(fname);
1593	if (index >= 0) {
1594		m_mruFiles.removeAt(index);
1595	}
1596	m_mruFiles.prepend(fname);
1597	while (m_mruFiles.size() > ConfigController::MRU_LIST_SIZE) {
1598		m_mruFiles.removeLast();
1599	}
1600	updateMRU();
1601}
1602
1603void Window::updateMRU() {
1604	if (!m_mruMenu) {
1605		return;
1606	}
1607	for (QAction* action : m_mruMenu->actions()) {
1608		delete action;
1609	}
1610	m_mruMenu->clear();
1611	int i = 0;
1612	for (const QString& file : m_mruFiles) {
1613		QAction* item = new QAction(QDir::toNativeSeparators(file).replace("&", "&&"), m_mruMenu);
1614		item->setShortcut(QString("Ctrl+%1").arg(i));
1615		connect(item, &QAction::triggered, [this, file]() { m_controller->loadGame(file); });
1616		m_mruMenu->addAction(item);
1617		++i;
1618	}
1619	m_config->setMRU(m_mruFiles);
1620	m_config->write();
1621	m_mruMenu->setEnabled(i > 0);
1622}
1623
1624QAction* Window::addControlledAction(QMenu* menu, QAction* action, const QString& name) {
1625	addHiddenAction(menu, action, name);
1626	menu->addAction(action);
1627	return action;
1628}
1629
1630QAction* Window::addHiddenAction(QMenu* menu, QAction* action, const QString& name) {
1631	m_shortcutController->addAction(menu, action, name);
1632	action->setShortcutContext(Qt::WidgetShortcut);
1633	addAction(action);
1634	return action;
1635}
1636
1637void Window::focusCheck() {
1638	if (!m_config->getOption("pauseOnFocusLost").toInt()) {
1639		return;
1640	}
1641	if (QGuiApplication::focusWindow() && m_autoresume) {
1642		m_controller->setPaused(false);
1643		m_autoresume = false;
1644	} else if (!QGuiApplication::focusWindow() && !m_controller->isPaused()) {
1645		m_autoresume = true;
1646		m_controller->setPaused(true);
1647	}
1648}
1649
1650WindowBackground::WindowBackground(QWidget* parent)
1651	: QLabel(parent)
1652{
1653	setLayout(new QStackedLayout());
1654	layout()->setContentsMargins(0, 0, 0, 0);
1655	setAlignment(Qt::AlignCenter);
1656}
1657
1658void WindowBackground::setSizeHint(const QSize& hint) {
1659	m_sizeHint = hint;
1660}
1661
1662QSize WindowBackground::sizeHint() const {
1663	return m_sizeHint;
1664}
1665
1666void WindowBackground::setLockAspectRatio(int width, int height) {
1667	m_aspectWidth = width;
1668	m_aspectHeight = height;
1669}
1670
1671void WindowBackground::setLockIntegerScaling(bool lock) {
1672	m_lockIntegerScaling = lock;
1673}
1674
1675void WindowBackground::paintEvent(QPaintEvent*) {
1676	const QPixmap* logo = pixmap();
1677	if (!logo) {
1678		return;
1679	}
1680	QPainter painter(this);
1681	painter.setRenderHint(QPainter::SmoothPixmapTransform);
1682	painter.fillRect(QRect(QPoint(), size()), Qt::black);
1683	QSize s = size();
1684	QSize ds = s;
1685	if (ds.width() * m_aspectHeight > ds.height() * m_aspectWidth) {
1686		ds.setWidth(ds.height() * m_aspectWidth / m_aspectHeight);
1687	} else if (ds.width() * m_aspectHeight < ds.height() * m_aspectWidth) {
1688		ds.setHeight(ds.width() * m_aspectHeight / m_aspectWidth);
1689	}
1690	if (m_lockIntegerScaling) {
1691		ds.setWidth(ds.width() - ds.width() % m_aspectWidth);
1692		ds.setHeight(ds.height() - ds.height() % m_aspectHeight);
1693	}
1694	QPoint origin = QPoint((s.width() - ds.width()) / 2, (s.height() - ds.height()) / 2);
1695	QRect full(origin, ds);
1696	painter.drawPixmap(full, *logo);
1697}