all repos — mgba @ cb0f95b07053e63e817bd05df0a36bf917667d09

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