all repos — mgba @ fc2a0955f4031992f694662cbaf2f7185240417f

mGBA Game Boy Advance Emulator

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

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