all repos — mgba @ 74af12317c18d20781a83886ecc33238f37238f9

mGBA Game Boy Advance Emulator

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

   1/* Copyright (c) 2013-2014 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 <QFileDialog>
   9#include <QFileInfo>
  10#include <QKeyEvent>
  11#include <QKeySequence>
  12#include <QMenuBar>
  13#include <QMessageBox>
  14#include <QMimeData>
  15#include <QPainter>
  16#include <QStackedLayout>
  17
  18#include "CheatsView.h"
  19#include "ConfigController.h"
  20#include "DisplayGL.h"
  21#include "GameController.h"
  22#include "GBAKeyEditor.h"
  23#include "GDBController.h"
  24#include "GDBWindow.h"
  25#include "GIFView.h"
  26#include "LoadSaveState.h"
  27#include "LogView.h"
  28#include "MultiplayerController.h"
  29#include "MemoryView.h"
  30#include "OverrideView.h"
  31#include "PaletteView.h"
  32#include "SensorView.h"
  33#include "SettingsView.h"
  34#include "ShortcutController.h"
  35#include "ShortcutView.h"
  36#include "VideoView.h"
  37
  38extern "C" {
  39#include "platform/commandline.h"
  40}
  41
  42using namespace QGBA;
  43
  44Window::Window(ConfigController* config, int playerId, QWidget* parent)
  45	: QMainWindow(parent)
  46	, m_logView(new LogView())
  47	, m_stateWindow(nullptr)
  48	, m_screenWidget(new WindowBackground())
  49	, m_logo(":/res/mgba-1024.png")
  50	, m_config(config)
  51	, m_inputController(playerId)
  52#ifdef USE_FFMPEG
  53	, m_videoView(nullptr)
  54#endif
  55#ifdef USE_MAGICK
  56	, m_gifView(nullptr)
  57#endif
  58#ifdef USE_GDB_STUB
  59	, m_gdbController(nullptr)
  60#endif
  61	, m_mruMenu(nullptr)
  62	, m_shortcutController(new ShortcutController(this))
  63	, m_playerId(playerId)
  64{
  65	setWindowTitle(PROJECT_NAME);
  66	setFocusPolicy(Qt::StrongFocus);
  67	setAcceptDrops(true);
  68	m_controller = new GameController(this);
  69	m_controller->setInputController(&m_inputController);
  70	m_controller->setOverrides(m_config->overrides());
  71
  72	QGLFormat format(QGLFormat(QGL::Rgba | QGL::DoubleBuffer));
  73	format.setSwapInterval(1);
  74	m_display = new DisplayGL(format, this);
  75
  76	m_logo.setDevicePixelRatio(m_screenWidget->devicePixelRatio());
  77	m_logo = m_logo; // Free memory left over in old pixmap
  78
  79	m_screenWidget->setMinimumSize(m_display->minimumSize());
  80	m_screenWidget->setSizePolicy(m_display->sizePolicy());
  81	m_screenWidget->setSizeHint(m_display->minimumSize() * 2);
  82	m_screenWidget->setPixmap(m_logo);
  83	m_screenWidget->setLockAspectRatio(m_logo.width(), m_logo.height());
  84	setCentralWidget(m_screenWidget);
  85
  86	QVariant windowPos = m_config->getQtOption("windowPos");
  87	if (!windowPos.isNull()) {
  88		move(windowPos.toPoint());
  89	}
  90
  91	connect(m_controller, SIGNAL(gameStarted(GBAThread*)), this, SLOT(gameStarted(GBAThread*)));
  92	connect(m_controller, SIGNAL(gameStopped(GBAThread*)), m_display, SLOT(stopDrawing()));
  93	connect(m_controller, SIGNAL(gameStopped(GBAThread*)), this, SLOT(gameStopped()));
  94	connect(m_controller, SIGNAL(stateLoaded(GBAThread*)), m_display, SLOT(forceDraw()));
  95	connect(m_controller, SIGNAL(rewound(GBAThread*)), m_display, SLOT(forceDraw()));
  96	connect(m_controller, SIGNAL(gamePaused(GBAThread*)), m_display, SLOT(pauseDrawing()));
  97#ifndef Q_OS_MAC
  98	connect(m_controller, SIGNAL(gamePaused(GBAThread*)), menuBar(), SLOT(show()));
  99	connect(m_controller, &GameController::gameUnpaused, [this]() {
 100		if(isFullScreen()) {
 101			menuBar()->hide();
 102		}
 103	});
 104#endif
 105	connect(m_controller, SIGNAL(gameUnpaused(GBAThread*)), m_display, SLOT(unpauseDrawing()));
 106	connect(m_controller, SIGNAL(postLog(int, const QString&)), m_logView, SLOT(postLog(int, const QString&)));
 107	connect(m_controller, SIGNAL(frameAvailable(const uint32_t*)), this, SLOT(recordFrame()));
 108	connect(m_controller, SIGNAL(frameAvailable(const uint32_t*)), m_display, SLOT(framePosted(const uint32_t*)));
 109	connect(m_controller, SIGNAL(gameCrashed(const QString&)), this, SLOT(gameCrashed(const QString&)));
 110	connect(m_controller, SIGNAL(gameFailed()), this, SLOT(gameFailed()));
 111	connect(m_controller, SIGNAL(unimplementedBiosCall(int)), this, SLOT(unimplementedBiosCall(int)));
 112	connect(m_controller, SIGNAL(statusPosted(const QString&)), m_display, SLOT(showMessage(const QString&)));
 113	connect(m_logView, SIGNAL(levelsSet(int)), m_controller, SLOT(setLogLevel(int)));
 114	connect(m_logView, SIGNAL(levelsEnabled(int)), m_controller, SLOT(enableLogLevel(int)));
 115	connect(m_logView, SIGNAL(levelsDisabled(int)), m_controller, SLOT(disableLogLevel(int)));
 116	connect(this, SIGNAL(startDrawing(GBAThread*)), m_display, SLOT(startDrawing(GBAThread*)), Qt::QueuedConnection);
 117	connect(this, SIGNAL(shutdown()), m_display, SLOT(stopDrawing()));
 118	connect(this, SIGNAL(shutdown()), m_controller, SLOT(closeGame()));
 119	connect(this, SIGNAL(shutdown()), m_logView, SLOT(hide()));
 120	connect(this, SIGNAL(audioBufferSamplesChanged(int)), m_controller, SLOT(setAudioBufferSamples(int)));
 121	connect(this, SIGNAL(fpsTargetChanged(float)), m_controller, SLOT(setFPSTarget(float)));
 122	connect(&m_fpsTimer, SIGNAL(timeout()), this, SLOT(showFPS()));
 123
 124	m_logView->setLevels(GBA_LOG_WARN | GBA_LOG_ERROR | GBA_LOG_FATAL | GBA_LOG_STATUS);
 125	m_fpsTimer.setInterval(FPS_TIMER_INTERVAL);
 126
 127	m_shortcutController->setConfigController(m_config);
 128	setupMenu(menuBar());
 129}
 130
 131Window::~Window() {
 132	delete m_logView;
 133
 134#ifdef USE_FFMPEG
 135	delete m_videoView;
 136#endif
 137
 138#ifdef USE_MAGICK
 139	delete m_gifView;
 140#endif
 141}
 142
 143void Window::argumentsPassed(GBAArguments* args) {
 144	loadConfig();
 145
 146	if (args->patch) {
 147		m_controller->loadPatch(args->patch);
 148	}
 149
 150	if (args->fname) {
 151		m_controller->loadGame(args->fname, args->dirmode);
 152	}
 153}
 154
 155void Window::resizeFrame(int width, int height) {
 156	QSize newSize(width, height);
 157	newSize -= m_screenWidget->size();
 158	newSize += size();
 159	resize(newSize);
 160}
 161
 162void Window::setConfig(ConfigController* config) {
 163	m_config = config;
 164}
 165
 166void Window::loadConfig() {
 167	const GBAOptions* opts = m_config->options();
 168
 169	m_logView->setLevels(opts->logLevel);
 170
 171	m_controller->setOptions(opts);
 172	m_display->lockAspectRatio(opts->lockAspectRatio);
 173	m_display->filter(opts->resampleVideo);
 174
 175	if (opts->bios) {
 176		m_controller->loadBIOS(opts->bios);
 177	}
 178
 179	if (opts->fpsTarget) {
 180		emit fpsTargetChanged(opts->fpsTarget);
 181	}
 182
 183	if (opts->audioBuffers) {
 184		emit audioBufferSamplesChanged(opts->audioBuffers);
 185	}
 186
 187	if (opts->width && opts->height) {
 188		resizeFrame(opts->width, opts->height);
 189	}
 190
 191	if (opts->fullscreen) {
 192		enterFullScreen();
 193	}
 194
 195	m_mruFiles = m_config->getMRU();
 196	updateMRU();
 197
 198	m_inputController.setConfiguration(m_config);
 199}
 200
 201void Window::saveConfig() {
 202	m_inputController.saveConfiguration();
 203	m_config->write();
 204}
 205
 206void Window::selectROM() {
 207	bool doPause = m_controller->isLoaded() && !m_controller->isPaused();
 208	if (doPause) {
 209		m_controller->setPaused(true);
 210	}
 211	QString filename = QFileDialog::getOpenFileName(this, tr("Select ROM"), m_config->getQtOption("lastDirectory").toString(), tr("Game Boy Advance ROMs (*.gba *.zip *.rom *.bin)"));
 212	if (doPause) {
 213		m_controller->setPaused(false);
 214	}
 215	if (!filename.isEmpty()) {
 216		m_config->setQtOption("lastDirectory", QFileInfo(filename).dir().path());
 217		m_controller->loadGame(filename);
 218	}
 219}
 220
 221void Window::selectBIOS() {
 222	bool doPause = m_controller->isLoaded() && !m_controller->isPaused();
 223	if (doPause) {
 224		m_controller->setPaused(true);
 225	}
 226	QString filename = QFileDialog::getOpenFileName(this, tr("Select BIOS"), m_config->getQtOption("lastDirectory").toString());
 227	if (doPause) {
 228		m_controller->setPaused(false);
 229	}
 230	if (!filename.isEmpty()) {
 231		m_config->setQtOption("lastDirectory", QFileInfo(filename).dir().path());
 232		m_config->setOption("bios", filename);
 233		m_config->updateOption("bios");
 234		m_config->setOption("useBios", true);
 235		m_config->updateOption("useBios");
 236		m_controller->loadBIOS(filename);
 237	}
 238}
 239
 240void Window::selectPatch() {
 241	bool doPause = m_controller->isLoaded() && !m_controller->isPaused();
 242	if (doPause) {
 243		m_controller->setPaused(true);
 244	}
 245	QString filename = QFileDialog::getOpenFileName(this, tr("Select patch"), m_config->getQtOption("lastDirectory").toString(), tr("Patches (*.ips *.ups *.bps)"));
 246	if (doPause) {
 247		m_controller->setPaused(false);
 248	}
 249	if (!filename.isEmpty()) {
 250		m_config->setQtOption("lastDirectory", QFileInfo(filename).dir().path());
 251		m_controller->loadPatch(filename);
 252	}
 253}
 254
 255void Window::openView(QWidget* widget) {
 256	connect(this, SIGNAL(shutdown()), widget, SLOT(close()));
 257	widget->setAttribute(Qt::WA_DeleteOnClose);
 258	widget->show();
 259}
 260
 261void Window::importSharkport() {
 262	bool doPause = m_controller->isLoaded() && !m_controller->isPaused();
 263	if (doPause) {
 264		m_controller->setPaused(true);
 265	}
 266	QString filename = QFileDialog::getOpenFileName(this, tr("Select save"), m_config->getQtOption("lastDirectory").toString(), tr("GameShark saves (*.sps *.xps)"));
 267	if (doPause) {
 268		m_controller->setPaused(false);
 269	}
 270	if (!filename.isEmpty()) {
 271		m_config->setQtOption("lastDirectory", QFileInfo(filename).dir().path());
 272		m_controller->importSharkport(filename);
 273	}
 274}
 275
 276void Window::exportSharkport() {
 277	bool doPause = m_controller->isLoaded() && !m_controller->isPaused();
 278	if (doPause) {
 279		m_controller->setPaused(true);
 280	}
 281	QString filename = QFileDialog::getSaveFileName(this, tr("Select save"), m_config->getQtOption("lastDirectory").toString(), tr("GameShark saves (*.sps *.xps)"));
 282	if (doPause) {
 283		m_controller->setPaused(false);
 284	}
 285	if (!filename.isEmpty()) {
 286		m_config->setQtOption("lastDirectory", QFileInfo(filename).dir().path());
 287		m_controller->exportSharkport(filename);
 288	}
 289}
 290
 291void Window::openKeymapWindow() {
 292	GBAKeyEditor* keyEditor = new GBAKeyEditor(&m_inputController, InputController::KEYBOARD);
 293	openView(keyEditor);
 294}
 295
 296void Window::openSettingsWindow() {
 297	SettingsView* settingsWindow = new SettingsView(m_config);
 298	connect(settingsWindow, SIGNAL(biosLoaded(const QString&)), m_controller, SLOT(loadBIOS(const QString&)));
 299	connect(settingsWindow, SIGNAL(audioDriverChanged()), m_controller, SLOT(reloadAudioDriver()));
 300	openView(settingsWindow);
 301}
 302
 303void Window::openShortcutWindow() {
 304#ifdef BUILD_SDL
 305	m_inputController.recalibrateAxes();
 306#endif
 307	ShortcutView* shortcutView = new ShortcutView();
 308	shortcutView->setController(m_shortcutController);
 309	openView(shortcutView);
 310}
 311
 312void Window::openOverrideWindow() {
 313	OverrideView* overrideWindow = new OverrideView(m_controller, m_config);
 314	openView(overrideWindow);
 315}
 316
 317void Window::openSensorWindow() {
 318	SensorView* sensorWindow = new SensorView(m_controller, &m_inputController);
 319	openView(sensorWindow);
 320}
 321
 322void Window::openCheatsWindow() {
 323	CheatsView* cheatsWindow = new CheatsView(m_controller);
 324	openView(cheatsWindow);
 325}
 326
 327void Window::openPaletteWindow() {
 328	PaletteView* paletteWindow = new PaletteView(m_controller);
 329	openView(paletteWindow);
 330}
 331
 332void Window::openMemoryWindow() {
 333	MemoryView* memoryWindow = new MemoryView(m_controller);
 334	openView(memoryWindow);
 335}
 336
 337#ifdef BUILD_SDL
 338void Window::openGamepadWindow() {
 339	const char* profile = m_inputController.profileForType(SDL_BINDING_BUTTON);
 340	GBAKeyEditor* keyEditor = new GBAKeyEditor(&m_inputController, SDL_BINDING_BUTTON, profile);
 341	openView(keyEditor);
 342}
 343#endif
 344
 345#ifdef USE_FFMPEG
 346void Window::openVideoWindow() {
 347	if (!m_videoView) {
 348		m_videoView = new VideoView();
 349		connect(m_videoView, SIGNAL(recordingStarted(GBAAVStream*)), m_controller, SLOT(setAVStream(GBAAVStream*)));
 350		connect(m_videoView, SIGNAL(recordingStopped()), m_controller, SLOT(clearAVStream()), Qt::DirectConnection);
 351		connect(m_controller, SIGNAL(gameStopped(GBAThread*)), m_videoView, SLOT(stopRecording()));
 352		connect(m_controller, SIGNAL(gameStopped(GBAThread*)), m_videoView, SLOT(close()));
 353		connect(this, SIGNAL(shutdown()), m_videoView, SLOT(close()));
 354	}
 355	m_videoView->show();
 356}
 357#endif
 358
 359#ifdef USE_MAGICK
 360void Window::openGIFWindow() {
 361	if (!m_gifView) {
 362		m_gifView = new GIFView();
 363		connect(m_gifView, SIGNAL(recordingStarted(GBAAVStream*)), m_controller, SLOT(setAVStream(GBAAVStream*)));
 364		connect(m_gifView, SIGNAL(recordingStopped()), m_controller, SLOT(clearAVStream()), Qt::DirectConnection);
 365		connect(m_controller, SIGNAL(gameStopped(GBAThread*)), m_gifView, SLOT(stopRecording()));
 366		connect(m_controller, SIGNAL(gameStopped(GBAThread*)), m_gifView, SLOT(close()));
 367		connect(this, SIGNAL(shutdown()), m_gifView, SLOT(close()));
 368	}
 369	m_gifView->show();
 370}
 371#endif
 372
 373#ifdef USE_GDB_STUB
 374void Window::gdbOpen() {
 375	if (!m_gdbController) {
 376		m_gdbController = new GDBController(m_controller, this);
 377	}
 378	GDBWindow* window = new GDBWindow(m_gdbController);
 379	connect(this, SIGNAL(shutdown()), window, SLOT(close()));
 380	window->setAttribute(Qt::WA_DeleteOnClose);
 381	window->show();
 382}
 383#endif
 384
 385void Window::keyPressEvent(QKeyEvent* event) {
 386	if (event->isAutoRepeat()) {
 387		QWidget::keyPressEvent(event);
 388		return;
 389	}
 390	GBAKey key = m_inputController.mapKeyboard(event->key());
 391	if (key == GBA_KEY_NONE) {
 392		QWidget::keyPressEvent(event);
 393		return;
 394	}
 395	m_controller->keyPressed(key);
 396	event->accept();
 397}
 398
 399void Window::keyReleaseEvent(QKeyEvent* event) {
 400	if (event->isAutoRepeat()) {
 401		QWidget::keyReleaseEvent(event);
 402		return;
 403	}
 404	GBAKey key = m_inputController.mapKeyboard(event->key());
 405	if (key == GBA_KEY_NONE) {
 406		QWidget::keyPressEvent(event);
 407		return;
 408	}
 409	m_controller->keyReleased(key);
 410	event->accept();
 411}
 412
 413void Window::resizeEvent(QResizeEvent*) {
 414	m_config->setOption("height", m_screenWidget->height());
 415	m_config->setOption("width", m_screenWidget->width());
 416	m_config->setOption("fullscreen", isFullScreen());
 417}
 418
 419void Window::closeEvent(QCloseEvent* event) {
 420	emit shutdown();
 421	m_config->setQtOption("windowPos", pos());
 422	saveConfig();
 423	QMainWindow::closeEvent(event);
 424}
 425
 426void Window::focusOutEvent(QFocusEvent*) {
 427	m_controller->setTurbo(false, false);
 428	m_controller->clearKeys();
 429}
 430
 431void Window::dragEnterEvent(QDragEnterEvent* event) {
 432	if (event->mimeData()->hasFormat("text/uri-list")) {
 433		event->acceptProposedAction();
 434	}
 435}
 436
 437void Window::dropEvent(QDropEvent* event) {
 438	QString uris = event->mimeData()->data("text/uri-list");
 439	uris = uris.trimmed();
 440	if (uris.contains("\n")) {
 441		// Only one file please
 442		return;
 443	}
 444	QUrl url(uris);
 445	if (!url.isLocalFile()) {
 446		// No remote loading
 447		return;
 448	}
 449	event->accept();
 450	m_controller->loadGame(url.path());
 451}
 452
 453void Window::mouseDoubleClickEvent(QMouseEvent* event) {
 454	if (event->button() != Qt::LeftButton) {
 455		return;
 456	}
 457	toggleFullScreen();
 458}
 459
 460void Window::enterFullScreen() {
 461	if (isFullScreen()) {
 462		return;
 463	}
 464	showFullScreen();
 465#ifndef Q_OS_MAC
 466	if (m_controller->isLoaded() && !m_controller->isPaused()) {
 467		menuBar()->hide();
 468	}
 469#endif
 470}
 471
 472void Window::exitFullScreen() {
 473	if (!isFullScreen()) {
 474		return;
 475	}
 476	showNormal();
 477	menuBar()->show();
 478}
 479
 480void Window::toggleFullScreen() {
 481	if (isFullScreen()) {
 482		exitFullScreen();
 483	} else {
 484		enterFullScreen();
 485	}
 486}
 487
 488void Window::gameStarted(GBAThread* context) {
 489	char title[13] = { '\0' };
 490	MutexLock(&context->stateMutex);
 491	if (context->state < THREAD_EXITING) {
 492		emit startDrawing(context);
 493		GBAGetGameTitle(context->gba, title);
 494	} else {
 495		MutexUnlock(&context->stateMutex);
 496		return;
 497	}
 498	MutexUnlock(&context->stateMutex);
 499	foreach (QAction* action, m_gameActions) {
 500		action->setDisabled(false);
 501	}
 502	appendMRU(context->fname);
 503	setWindowTitle(tr(PROJECT_NAME " - %1").arg(title));
 504	attachWidget(m_display);
 505
 506#ifndef Q_OS_MAC
 507	if(isFullScreen()) {
 508		menuBar()->hide();
 509	}
 510#endif
 511
 512	m_hitUnimplementedBiosCall = false;
 513	m_fpsTimer.start();
 514}
 515
 516void Window::gameStopped() {
 517	foreach (QAction* action, m_gameActions) {
 518		action->setDisabled(true);
 519	}
 520	setWindowTitle(tr(PROJECT_NAME));
 521	detachWidget(m_display);
 522	m_screenWidget->setLockAspectRatio(m_logo.width(), m_logo.height());
 523	m_screenWidget->setPixmap(m_logo);
 524
 525	m_fpsTimer.stop();
 526}
 527
 528void Window::gameCrashed(const QString& errorMessage) {
 529	QMessageBox* crash = new QMessageBox(QMessageBox::Critical, tr("Crash"),
 530		tr("The game has crashed with the following error:\n\n%1").arg(errorMessage),
 531		QMessageBox::Ok, this,  Qt::Sheet);
 532	crash->setAttribute(Qt::WA_DeleteOnClose);
 533	crash->show();
 534}
 535
 536void Window::gameFailed() {
 537	QMessageBox* fail = new QMessageBox(QMessageBox::Warning, tr("Couldn't Load"),
 538		tr("Could not load game. Are you sure it's in the correct format?"),
 539		QMessageBox::Ok, this,  Qt::Sheet);
 540	fail->setAttribute(Qt::WA_DeleteOnClose);
 541	fail->show();
 542}
 543
 544void Window::unimplementedBiosCall(int call) {
 545	if (m_hitUnimplementedBiosCall) {
 546		return;
 547	}
 548	m_hitUnimplementedBiosCall = true;
 549
 550	QMessageBox* fail = new QMessageBox(QMessageBox::Warning, tr("Unimplemented BIOS call"),
 551		tr("This game uses a BIOS call that is not implemented. Please use the official BIOS for best experience."),
 552		QMessageBox::Ok, this,  Qt::Sheet);
 553	fail->setAttribute(Qt::WA_DeleteOnClose);
 554	fail->show();
 555}
 556
 557void Window::recordFrame() {
 558	m_frameList.append(QDateTime::currentDateTime());
 559	while (m_frameList.count() > FRAME_LIST_SIZE) {
 560		m_frameList.removeFirst();
 561	}
 562}
 563
 564void Window::showFPS() {
 565	char gameTitle[13] = { '\0' };
 566	GBAGetGameTitle(m_controller->thread()->gba, gameTitle);
 567
 568	QString title(gameTitle);
 569	std::shared_ptr<MultiplayerController> multiplayer = m_controller->multiplayerController();
 570	if (multiplayer && multiplayer->attached() > 1) {
 571		title += tr(" -  Player %1 of %2").arg(m_playerId + 1).arg(multiplayer->attached());
 572	}
 573	if (m_frameList.isEmpty()) {
 574		setWindowTitle(tr(PROJECT_NAME " - %1").arg(title));
 575		return;
 576	}
 577	qint64 interval = m_frameList.first().msecsTo(m_frameList.last());
 578	float fps = (m_frameList.count() - 1) * 10000.f / interval;
 579	fps = round(fps) / 10.f;
 580	setWindowTitle(tr(PROJECT_NAME " - %1 (%2 fps)").arg(title).arg(fps));
 581}
 582
 583void Window::openStateWindow(LoadSave ls) {
 584	if (m_stateWindow) {
 585		return;
 586	}
 587	bool wasPaused = m_controller->isPaused();
 588	m_stateWindow = new LoadSaveState(m_controller);
 589	connect(this, SIGNAL(shutdown()), m_stateWindow, SLOT(close()));
 590	connect(m_controller, SIGNAL(gameStopped(GBAThread*)), m_stateWindow, SLOT(close()));
 591	connect(m_stateWindow, &LoadSaveState::closed, [this]() {
 592		m_screenWidget->layout()->removeWidget(m_stateWindow);
 593		m_stateWindow = nullptr;
 594		QMetaObject::invokeMethod(this, "setFocus", Qt::QueuedConnection);
 595	});
 596	if (!wasPaused) {
 597		m_controller->setPaused(true);
 598		connect(m_stateWindow, &LoadSaveState::closed, [this]() { m_controller->setPaused(false); });
 599	}
 600	m_stateWindow->setAttribute(Qt::WA_DeleteOnClose);
 601	m_stateWindow->setMode(ls);
 602	attachWidget(m_stateWindow);
 603}
 604
 605void Window::setupMenu(QMenuBar* menubar) {
 606	menubar->clear();
 607	QMenu* fileMenu = menubar->addMenu(tr("&File"));
 608	m_shortcutController->addMenu(fileMenu);
 609	installEventFilter(m_shortcutController);
 610	addControlledAction(fileMenu, fileMenu->addAction(tr("Load &ROM..."), this, SLOT(selectROM()), QKeySequence::Open), "loadROM");
 611	addControlledAction(fileMenu, fileMenu->addAction(tr("Load &BIOS..."), this, SLOT(selectBIOS())), "loadBIOS");
 612	addControlledAction(fileMenu, fileMenu->addAction(tr("Load &patch..."), this, SLOT(selectPatch())), "loadPatch");
 613
 614	m_mruMenu = fileMenu->addMenu(tr("Recent"));
 615
 616	fileMenu->addSeparator();
 617
 618	QAction* loadState = new QAction(tr("&Load state"), fileMenu);
 619	loadState->setShortcut(tr("F10"));
 620	connect(loadState, &QAction::triggered, [this]() { this->openStateWindow(LoadSave::LOAD); });
 621	m_gameActions.append(loadState);
 622	addControlledAction(fileMenu, loadState, "loadState");
 623
 624	QAction* saveState = new QAction(tr("&Save state"), fileMenu);
 625	saveState->setShortcut(tr("Shift+F10"));
 626	connect(saveState, &QAction::triggered, [this]() { this->openStateWindow(LoadSave::SAVE); });
 627	m_gameActions.append(saveState);
 628	addControlledAction(fileMenu, saveState, "saveState");
 629
 630	QMenu* quickLoadMenu = fileMenu->addMenu(tr("Quick load"));
 631	QMenu* quickSaveMenu = fileMenu->addMenu(tr("Quick save"));
 632	m_shortcutController->addMenu(quickLoadMenu);
 633	m_shortcutController->addMenu(quickSaveMenu);
 634	int i;
 635	for (i = 1; i < 10; ++i) {
 636		QAction* quickLoad = new QAction(tr("State &%1").arg(i), quickLoadMenu);
 637		quickLoad->setShortcut(tr("F%1").arg(i));
 638		connect(quickLoad, &QAction::triggered, [this, i]() { m_controller->loadState(i); });
 639		m_gameActions.append(quickLoad);
 640		addControlledAction(quickLoadMenu, quickLoad, QString("quickLoad.%1").arg(i));
 641
 642		QAction* quickSave = new QAction(tr("State &%1").arg(i), quickSaveMenu);
 643		quickSave->setShortcut(tr("Shift+F%1").arg(i));
 644		connect(quickSave, &QAction::triggered, [this, i]() { m_controller->saveState(i); });
 645		m_gameActions.append(quickSave);
 646		addControlledAction(quickSaveMenu, quickSave, QString("quickSave.%1").arg(i));
 647	}
 648
 649	fileMenu->addSeparator();
 650	QAction* importShark = new QAction(tr("Import GameShark Save"), fileMenu);
 651	connect(importShark, SIGNAL(triggered()), this, SLOT(importSharkport()));
 652	m_gameActions.append(importShark);
 653	addControlledAction(fileMenu, importShark, "importShark");
 654
 655	QAction* exportShark = new QAction(tr("Export GameShark Save"), fileMenu);
 656	connect(exportShark, SIGNAL(triggered()), this, SLOT(exportSharkport()));
 657	m_gameActions.append(exportShark);
 658	addControlledAction(fileMenu, exportShark, "exportShark");
 659
 660	fileMenu->addSeparator();
 661	QAction* multiWindow = new QAction(tr("New multiplayer window"), fileMenu);
 662	connect(multiWindow, &QAction::triggered, [this]() {
 663		std::shared_ptr<MultiplayerController> multiplayer = m_controller->multiplayerController();
 664		if (!multiplayer) {
 665			multiplayer = std::make_shared<MultiplayerController>();
 666			m_controller->setMultiplayerController(multiplayer);
 667		}
 668		Window* w2 = new Window(m_config, multiplayer->attached());
 669		w2->setAttribute(Qt::WA_DeleteOnClose);
 670#ifndef Q_OS_MAC
 671		w2->show();
 672#endif
 673		w2->loadConfig();
 674		w2->controller()->setMultiplayerController(multiplayer);
 675#ifdef Q_OS_MAC
 676		w2->show();
 677#endif
 678	});
 679	addControlledAction(fileMenu, multiWindow, "multiWindow");
 680
 681#ifndef Q_OS_MAC
 682	addControlledAction(fileMenu, fileMenu->addAction(tr("E&xit"), this, SLOT(close()), QKeySequence::Quit), "quit");
 683#endif
 684
 685	QMenu* emulationMenu = menubar->addMenu(tr("&Emulation"));
 686	m_shortcutController->addMenu(emulationMenu);
 687	QAction* reset = new QAction(tr("&Reset"), emulationMenu);
 688	reset->setShortcut(tr("Ctrl+R"));
 689	connect(reset, SIGNAL(triggered()), m_controller, SLOT(reset()));
 690	m_gameActions.append(reset);
 691	addControlledAction(emulationMenu, reset, "reset");
 692
 693	QAction* shutdown = new QAction(tr("Sh&utdown"), emulationMenu);
 694	connect(shutdown, SIGNAL(triggered()), m_controller, SLOT(closeGame()));
 695	m_gameActions.append(shutdown);
 696	addControlledAction(emulationMenu, shutdown, "shutdown");
 697	emulationMenu->addSeparator();
 698
 699	QAction* pause = new QAction(tr("&Pause"), emulationMenu);
 700	pause->setChecked(false);
 701	pause->setCheckable(true);
 702	pause->setShortcut(tr("Ctrl+P"));
 703	connect(pause, SIGNAL(triggered(bool)), m_controller, SLOT(setPaused(bool)));
 704	connect(m_controller, &GameController::gamePaused, [this, pause]() {
 705		pause->setChecked(true);
 706
 707		QImage currentImage(reinterpret_cast<const uchar*>(m_controller->drawContext()), VIDEO_HORIZONTAL_PIXELS, VIDEO_VERTICAL_PIXELS, 1024, QImage::Format_RGB32);
 708		QPixmap pixmap;
 709		pixmap.convertFromImage(currentImage.rgbSwapped());
 710		m_screenWidget->setPixmap(pixmap);
 711		m_screenWidget->setLockAspectRatio(3, 2);
 712	});
 713	connect(m_controller, &GameController::gameUnpaused, [pause]() { pause->setChecked(false); });
 714	m_gameActions.append(pause);
 715	addControlledAction(emulationMenu, pause, "pause");
 716
 717	QAction* frameAdvance = new QAction(tr("&Next frame"), emulationMenu);
 718	frameAdvance->setShortcut(tr("Ctrl+N"));
 719	connect(frameAdvance, SIGNAL(triggered()), m_controller, SLOT(frameAdvance()));
 720	m_gameActions.append(frameAdvance);
 721	addControlledAction(emulationMenu, frameAdvance, "frameAdvance");
 722
 723	emulationMenu->addSeparator();
 724
 725	m_shortcutController->addFunctions(emulationMenu, [this]() {
 726		m_controller->setTurbo(true, false);
 727	}, [this]() {
 728		m_controller->setTurbo(false, false);
 729	}, QKeySequence(Qt::Key_Tab), tr("Fast forward (held)"), "holdFastForward");
 730
 731	QAction* turbo = new QAction(tr("&Fast forward"), emulationMenu);
 732	turbo->setCheckable(true);
 733	turbo->setChecked(false);
 734	turbo->setShortcut(tr("Shift+Tab"));
 735	connect(turbo, SIGNAL(triggered(bool)), m_controller, SLOT(setTurbo(bool)));
 736	addControlledAction(emulationMenu, turbo, "fastForward");
 737
 738	QAction* rewind = new QAction(tr("Re&wind"), emulationMenu);
 739	rewind->setShortcut(tr("`"));
 740	connect(rewind, SIGNAL(triggered()), m_controller, SLOT(rewind()));
 741	m_gameActions.append(rewind);
 742	addControlledAction(emulationMenu, rewind, "rewind");
 743
 744	QAction* frameRewind = new QAction(tr("Step backwards"), emulationMenu);
 745	frameRewind->setShortcut(tr("Ctrl+B"));
 746	connect(frameRewind, &QAction::triggered, [this] () {
 747		m_controller->rewind(1);
 748	});
 749	m_gameActions.append(frameRewind);
 750	addControlledAction(emulationMenu, frameRewind, "frameRewind");
 751
 752	ConfigOption* videoSync = m_config->addOption("videoSync");
 753	videoSync->addBoolean(tr("Sync to &video"), emulationMenu);
 754	videoSync->connect([this](const QVariant& value) {
 755		m_controller->setVideoSync(value.toBool());
 756	}, this);
 757	m_config->updateOption("videoSync");
 758
 759	ConfigOption* audioSync = m_config->addOption("audioSync");
 760	audioSync->addBoolean(tr("Sync to &audio"), emulationMenu);
 761	audioSync->connect([this](const QVariant& value) {
 762		m_controller->setAudioSync(value.toBool());
 763	}, this);
 764	m_config->updateOption("audioSync");
 765
 766	emulationMenu->addSeparator();
 767
 768	QMenu* solarMenu = emulationMenu->addMenu(tr("Solar sensor"));
 769	m_shortcutController->addMenu(solarMenu);
 770	QAction* solarIncrease = new QAction(tr("Increase solar level"), solarMenu);
 771	connect(solarIncrease, SIGNAL(triggered()), m_controller, SLOT(increaseLuminanceLevel()));
 772	addControlledAction(solarMenu, solarIncrease, "increaseLuminanceLevel");
 773
 774	QAction* solarDecrease = new QAction(tr("Decrease solar level"), solarMenu);
 775	connect(solarDecrease, SIGNAL(triggered()), m_controller, SLOT(decreaseLuminanceLevel()));
 776	addControlledAction(solarMenu, solarDecrease, "decreaseLuminanceLevel");
 777
 778	QAction* maxSolar = new QAction(tr("Brightest solar level"), solarMenu);
 779	connect(maxSolar, &QAction::triggered, [this]() { m_controller->setLuminanceLevel(10); });
 780	addControlledAction(solarMenu, maxSolar, "maxLuminanceLevel");
 781
 782	QAction* minSolar = new QAction(tr("Darkest solar level"), solarMenu);
 783	connect(minSolar, &QAction::triggered, [this]() { m_controller->setLuminanceLevel(0); });
 784	addControlledAction(solarMenu, minSolar, "minLuminanceLevel");
 785
 786	solarMenu->addSeparator();
 787	for (int i = 0; i <= 10; ++i) {
 788		QAction* setSolar = new QAction(tr("Brightness %1").arg(QString::number(i)), solarMenu);
 789		connect(setSolar, &QAction::triggered, [this, i]() {
 790			m_controller->setLuminanceLevel(i);
 791		});
 792		addControlledAction(solarMenu, setSolar, QString("luminanceLevel.%1").arg(QString::number(i)));
 793	}
 794
 795	QMenu* avMenu = menubar->addMenu(tr("Audio/&Video"));
 796	m_shortcutController->addMenu(avMenu);
 797	QMenu* frameMenu = avMenu->addMenu(tr("Frame size"));
 798	m_shortcutController->addMenu(frameMenu, avMenu);
 799	for (int i = 1; i <= 6; ++i) {
 800		QAction* setSize = new QAction(tr("%1x").arg(QString::number(i)), avMenu);
 801		connect(setSize, &QAction::triggered, [this, i]() {
 802			showNormal();
 803			resizeFrame(VIDEO_HORIZONTAL_PIXELS * i, VIDEO_VERTICAL_PIXELS * i);
 804		});
 805		addControlledAction(frameMenu, setSize, QString("frame%1x").arg(QString::number(i)));
 806	}
 807	addControlledAction(frameMenu, frameMenu->addAction(tr("Fullscreen"), this, SLOT(toggleFullScreen()), QKeySequence("Ctrl+F")), "fullscreen");
 808
 809	ConfigOption* lockAspectRatio = m_config->addOption("lockAspectRatio");
 810	lockAspectRatio->addBoolean(tr("Lock aspect ratio"), avMenu);
 811	lockAspectRatio->connect([this](const QVariant& value) {
 812		m_display->lockAspectRatio(value.toBool());
 813	}, this);
 814	m_config->updateOption("lockAspectRatio");
 815
 816	ConfigOption* resampleVideo = m_config->addOption("resampleVideo");
 817	resampleVideo->addBoolean(tr("Resample video"), avMenu);
 818	resampleVideo->connect([this](const QVariant& value) {
 819		m_display->filter(value.toBool());
 820	}, this);
 821	m_config->updateOption("resampleVideo");
 822
 823	QMenu* skipMenu = avMenu->addMenu(tr("Frame&skip"));
 824	ConfigOption* skip = m_config->addOption("frameskip");
 825	skip->connect([this](const QVariant& value) {
 826		m_controller->setFrameskip(value.toInt());
 827	}, this);
 828	for (int i = 0; i <= 10; ++i) {
 829		skip->addValue(QString::number(i), i, skipMenu);
 830	}
 831	m_config->updateOption("frameskip");
 832
 833	avMenu->addSeparator();
 834
 835	QMenu* buffersMenu = avMenu->addMenu(tr("Audio buffer &size"));
 836	ConfigOption* buffers = m_config->addOption("audioBuffers");
 837	buffers->connect([this](const QVariant& value) {
 838		emit audioBufferSamplesChanged(value.toInt());
 839	}, this);
 840	buffers->addValue(tr("512"), 512, buffersMenu);
 841	buffers->addValue(tr("768"), 768, buffersMenu);
 842	buffers->addValue(tr("1024"), 1024, buffersMenu);
 843	buffers->addValue(tr("2048"), 2048, buffersMenu);
 844	buffers->addValue(tr("4096"), 4096, buffersMenu);
 845	m_config->updateOption("audioBuffers");
 846
 847	avMenu->addSeparator();
 848
 849	QMenu* target = avMenu->addMenu(tr("FPS target"));
 850	ConfigOption* fpsTargetOption = m_config->addOption("fpsTarget");
 851	fpsTargetOption->connect([this](const QVariant& value) {
 852		emit fpsTargetChanged(value.toFloat());
 853	}, this);
 854	fpsTargetOption->addValue(tr("15"), 15, target);
 855	fpsTargetOption->addValue(tr("30"), 30, target);
 856	fpsTargetOption->addValue(tr("45"), 45, target);
 857	fpsTargetOption->addValue(tr("Native (59.7)"), float(GBA_ARM7TDMI_FREQUENCY) / float(VIDEO_TOTAL_LENGTH), target);
 858	fpsTargetOption->addValue(tr("60"), 60, target);
 859	fpsTargetOption->addValue(tr("90"), 90, target);
 860	fpsTargetOption->addValue(tr("120"), 120, target);
 861	fpsTargetOption->addValue(tr("240"), 240, target);
 862	m_config->updateOption("fpsTarget");
 863
 864#if defined(USE_PNG) || defined(USE_FFMPEG) || defined(USE_MAGICK)
 865	avMenu->addSeparator();
 866#endif
 867
 868#ifdef USE_PNG
 869	QAction* screenshot = new QAction(tr("Take &screenshot"), avMenu);
 870	screenshot->setShortcut(tr("F12"));
 871	connect(screenshot, SIGNAL(triggered()), m_controller, SLOT(screenshot()));
 872	m_gameActions.append(screenshot);
 873	addControlledAction(avMenu, screenshot, "screenshot");
 874#endif
 875
 876#ifdef USE_FFMPEG
 877	QAction* recordOutput = new QAction(tr("Record output..."), avMenu);
 878	recordOutput->setShortcut(tr("F11"));
 879	connect(recordOutput, SIGNAL(triggered()), this, SLOT(openVideoWindow()));
 880	addControlledAction(avMenu, recordOutput, "recordOutput");
 881#endif
 882
 883#ifdef USE_MAGICK
 884	QAction* recordGIF = new QAction(tr("Record GIF..."), avMenu);
 885	recordGIF->setShortcut(tr("Shift+F11"));
 886	connect(recordGIF, SIGNAL(triggered()), this, SLOT(openGIFWindow()));
 887	addControlledAction(avMenu, recordGIF, "recordGIF");
 888#endif
 889
 890	avMenu->addSeparator();
 891	QMenu* videoLayers = avMenu->addMenu(tr("Video layers"));
 892
 893	for (int i = 0; i < 4; ++i) {
 894		QAction* enableBg = new QAction(tr("Background %0").arg(i), videoLayers);
 895		enableBg->setCheckable(true);
 896		enableBg->setChecked(true);
 897		connect(enableBg, &QAction::triggered, [this, i](bool enable) { m_controller->thread()->gba->video.renderer->disableBG[i] = !enable; });
 898		m_gameActions.append(enableBg);
 899		addControlledAction(videoLayers, enableBg, QString("enableBG%0").arg(i));
 900	}
 901
 902	QAction* enableObj = new QAction(tr("OBJ (sprites)"), videoLayers);
 903	enableObj->setCheckable(true);
 904	enableObj->setChecked(true);
 905	connect(enableObj, &QAction::triggered, [this](bool enable) { m_controller->thread()->gba->video.renderer->disableOBJ = !enable; });
 906	m_gameActions.append(enableObj);
 907	addControlledAction(videoLayers, enableObj, "enableOBJ");
 908
 909	QMenu* audioChannels = avMenu->addMenu(tr("Audio channels"));
 910
 911	for (int i = 0; i < 4; ++i) {
 912		QAction* enableCh = new QAction(tr("Channel %0").arg(i + 1), audioChannels);
 913		enableCh->setCheckable(true);
 914		enableCh->setChecked(true);
 915		connect(enableCh, &QAction::triggered, [this, i](bool enable) { m_controller->thread()->gba->audio.forceDisableCh[i] = !enable; });
 916		m_gameActions.append(enableCh);
 917		addControlledAction(audioChannels, enableCh, QString("enableCh%0").arg(i + 1));
 918	}
 919
 920	QAction* enableChA = new QAction(tr("Channel A"), audioChannels);
 921	enableChA->setCheckable(true);
 922	enableChA->setChecked(true);
 923	connect(enableChA, &QAction::triggered, [this, i](bool enable) { m_controller->thread()->gba->audio.forceDisableChA = !enable; });
 924	m_gameActions.append(enableChA);
 925	addControlledAction(audioChannels, enableChA, QString("enableChA"));
 926
 927	QAction* enableChB = new QAction(tr("Channel B"), audioChannels);
 928	enableChB->setCheckable(true);
 929	enableChB->setChecked(true);
 930	connect(enableChB, &QAction::triggered, [this, i](bool enable) { m_controller->thread()->gba->audio.forceDisableChB = !enable; });
 931	m_gameActions.append(enableChB);
 932	addControlledAction(audioChannels, enableChB, QString("enableChB"));
 933
 934	QMenu* toolsMenu = menubar->addMenu(tr("&Tools"));
 935	m_shortcutController->addMenu(toolsMenu);
 936	QAction* viewLogs = new QAction(tr("View &logs..."), toolsMenu);
 937	connect(viewLogs, SIGNAL(triggered()), m_logView, SLOT(show()));
 938	addControlledAction(toolsMenu, viewLogs, "viewLogs");
 939
 940	QAction* overrides = new QAction(tr("Game &overrides..."), toolsMenu);
 941	connect(overrides, SIGNAL(triggered()), this, SLOT(openOverrideWindow()));
 942	addControlledAction(toolsMenu, overrides, "overrideWindow");
 943
 944	QAction* sensors = new QAction(tr("Game &Pak sensors..."), toolsMenu);
 945	connect(sensors, SIGNAL(triggered()), this, SLOT(openSensorWindow()));
 946	addControlledAction(toolsMenu, sensors, "sensorWindow");
 947
 948	QAction* cheats = new QAction(tr("&Cheats..."), toolsMenu);
 949	connect(cheats, SIGNAL(triggered()), this, SLOT(openCheatsWindow()));
 950	addControlledAction(toolsMenu, cheats, "cheatsWindow");
 951
 952#ifdef USE_GDB_STUB
 953	QAction* gdbWindow = new QAction(tr("Start &GDB server..."), toolsMenu);
 954	connect(gdbWindow, SIGNAL(triggered()), this, SLOT(gdbOpen()));
 955	addControlledAction(toolsMenu, gdbWindow, "gdbWindow");
 956#endif
 957
 958	toolsMenu->addSeparator();
 959	addControlledAction(toolsMenu, toolsMenu->addAction(tr("Settings..."), this, SLOT(openSettingsWindow())), "settings");
 960	addControlledAction(toolsMenu, toolsMenu->addAction(tr("Edit shortcuts..."), this, SLOT(openShortcutWindow())), "shortcuts");
 961
 962	QAction* keymap = new QAction(tr("Remap keyboard..."), toolsMenu);
 963	connect(keymap, SIGNAL(triggered()), this, SLOT(openKeymapWindow()));
 964	addControlledAction(toolsMenu, keymap, "remapKeyboard");
 965
 966#ifdef BUILD_SDL
 967	QAction* gamepad = new QAction(tr("Remap gamepad..."), toolsMenu);
 968	connect(gamepad, SIGNAL(triggered()), this, SLOT(openGamepadWindow()));
 969	addControlledAction(toolsMenu, gamepad, "remapGamepad");
 970#endif
 971
 972	toolsMenu->addSeparator();
 973
 974	QAction* paletteView = new QAction(tr("View &palette..."), toolsMenu);
 975	connect(paletteView, SIGNAL(triggered()), this, SLOT(openPaletteWindow()));
 976	m_gameActions.append(paletteView);
 977	addControlledAction(toolsMenu, paletteView, "paletteWindow");
 978
 979	QAction* memoryView = new QAction(tr("View memory..."), toolsMenu);
 980	connect(memoryView, SIGNAL(triggered()), this, SLOT(openMemoryWindow()));
 981	m_gameActions.append(memoryView);
 982	addControlledAction(toolsMenu, memoryView, "memoryView");
 983
 984	ConfigOption* skipBios = m_config->addOption("skipBios");
 985	skipBios->connect([this](const QVariant& value) {
 986		m_controller->setSkipBIOS(value.toBool());
 987	}, this);
 988
 989	ConfigOption* volume = m_config->addOption("volume");
 990	volume->connect([this](const QVariant& value) {
 991		m_controller->setVolume(value.toInt());
 992	}, this);
 993
 994	ConfigOption* mute = m_config->addOption("mute");
 995	mute->connect([this](const QVariant& value) {
 996		m_controller->setMute(value.toBool());
 997	}, this);
 998
 999	ConfigOption* rewindEnable = m_config->addOption("rewindEnable");
1000	rewindEnable->connect([this](const QVariant& value) {
1001		m_controller->setRewind(value.toBool(), m_config->getOption("rewindBufferCapacity").toInt(), m_config->getOption("rewindBufferInterval").toInt());
1002	}, this);
1003
1004	ConfigOption* rewindBufferCapacity = m_config->addOption("rewindBufferCapacity");
1005	rewindBufferCapacity->connect([this](const QVariant& value) {
1006		m_controller->setRewind(m_config->getOption("rewindEnable").toInt(), value.toInt(), m_config->getOption("rewindBufferInterval").toInt());
1007	}, this);
1008
1009	ConfigOption* rewindBufferInterval = m_config->addOption("rewindBufferInterval");
1010	rewindBufferInterval->connect([this](const QVariant& value) {
1011		m_controller->setRewind(m_config->getOption("rewindEnable").toInt(), m_config->getOption("rewindBufferCapacity").toInt(), value.toInt());
1012	}, this);
1013
1014	ConfigOption* allowOpposingDirections = m_config->addOption("allowOpposingDirections");
1015	allowOpposingDirections->connect([this](const QVariant& value) {
1016		m_inputController.setAllowOpposing(value.toBool());
1017	}, this);
1018
1019	QMenu* other = new QMenu(tr("Other"), this);
1020	m_shortcutController->addMenu(other);
1021
1022	addControlledAction(other, other->addAction(tr("Exit fullscreen"), this, SLOT(exitFullScreen()), QKeySequence("Esc")), "exitFullScreen");
1023
1024	foreach (QAction* action, m_gameActions) {
1025		action->setDisabled(true);
1026	}
1027}
1028
1029void Window::attachWidget(QWidget* widget) {
1030	m_screenWidget->layout()->addWidget(widget);
1031	static_cast<QStackedLayout*>(m_screenWidget->layout())->setCurrentWidget(widget);
1032}
1033
1034void Window::detachWidget(QWidget* widget) {
1035	m_screenWidget->layout()->removeWidget(widget);
1036}
1037
1038void Window::appendMRU(const QString& fname) {
1039	int index = m_mruFiles.indexOf(fname);
1040	if (index >= 0) {
1041		m_mruFiles.removeAt(index);
1042	}
1043	m_mruFiles.prepend(fname);
1044	while (m_mruFiles.size() > ConfigController::MRU_LIST_SIZE) {
1045		m_mruFiles.removeLast();
1046	}
1047	updateMRU();
1048}
1049
1050void Window::updateMRU() {
1051	if (!m_mruMenu) {
1052		return;
1053	}
1054	m_mruMenu->clear();
1055	int i = 0;
1056	for (const QString& file : m_mruFiles) {
1057		QAction* item = new QAction(file, m_mruMenu);
1058		item->setShortcut(QString("Ctrl+%1").arg(i));
1059		connect(item, &QAction::triggered, [this, file]() { m_controller->loadGame(file); });
1060		m_mruMenu->addAction(item);
1061		++i;
1062	}
1063	m_config->setMRU(m_mruFiles);
1064	m_config->write();
1065	m_mruMenu->setEnabled(i > 0);
1066}
1067
1068QAction* Window::addControlledAction(QMenu* menu, QAction* action, const QString& name) {
1069	m_shortcutController->addAction(menu, action, name);
1070	menu->addAction(action);
1071	action->setShortcutContext(Qt::WidgetShortcut);
1072	addAction(action);
1073	return action;
1074}
1075
1076WindowBackground::WindowBackground(QWidget* parent)
1077	: QLabel(parent)
1078{
1079	setLayout(new QStackedLayout());
1080	layout()->setContentsMargins(0, 0, 0, 0);
1081	setAlignment(Qt::AlignCenter);
1082}
1083
1084void WindowBackground::setSizeHint(const QSize& hint) {
1085	m_sizeHint = hint;
1086}
1087
1088QSize WindowBackground::sizeHint() const {
1089	return m_sizeHint;
1090}
1091
1092void WindowBackground::setLockAspectRatio(int width, int height) {
1093	m_aspectWidth = width;
1094	m_aspectHeight = height;
1095}
1096
1097void WindowBackground::paintEvent(QPaintEvent*) {
1098	const QPixmap* logo = pixmap();
1099	if (!logo) {
1100		return;
1101	}
1102	QPainter painter(this);
1103	painter.setRenderHint(QPainter::SmoothPixmapTransform);
1104	painter.fillRect(QRect(QPoint(), size()), Qt::black);
1105	QSize s = size();
1106	QSize ds = s;
1107	if (s.width() * m_aspectHeight > s.height() * m_aspectWidth) {
1108		ds.setWidth(s.height() * m_aspectWidth / m_aspectHeight);
1109	} else if (s.width() * m_aspectHeight < s.height() * m_aspectWidth) {
1110		ds.setHeight(s.width() * m_aspectHeight / m_aspectWidth);
1111	}
1112	QPoint origin = QPoint((s.width() - ds.width()) / 2, (s.height() - ds.height()) / 2);
1113	QRect full(origin, ds);
1114	painter.drawPixmap(full, *logo);
1115}