all repos — mgba @ b909575a6cb2aa669e4086c2d4e21bcc635e85b5

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