all repos — mgba @ cec4d48c8afb49e7e81e0e3e5eeeb7588331bc32

mGBA Game Boy Advance Emulator

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

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