all repos — mgba @ 8c095ec885e7131993ee50ae7f1bc9b1ea570128

mGBA Game Boy Advance Emulator

src/platform/qt/Window.cpp (view raw)

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