all repos — mgba @ 154dd2e8e7c064568b901387de5fdfb4341b0577

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