all repos — mgba @ 470dd7f5508866b8b54722966ff7395c5b8748d3

mGBA Game Boy Advance Emulator

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

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