all repos — mgba @ 7d360d6cb893f916ecdcece999303cd6a35e952c

mGBA Game Boy Advance Emulator

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

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