all repos — mgba @ f91a4195b60fdd7943ace1444031ea7043fc172d

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