all repos — mgba @ 691600902c18fbee18ba8ab12cefed8403b3c7ae

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