all repos — mgba @ 36fb807687480a75085559889d4796e093185d1b

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