all repos — mgba @ 938c2f84b814337997363a9be6b171d1f38d23e0

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