all repos — mgba @ f511e937db1df9786549c3f90749352f2c3117af

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