all repos — mgba @ faadb5d6a6357c59a5b70ecbdf4fa204a9c96f9a

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