all repos — mgba @ 4f246827a63b1874bd940f43dd8fe22dfae02ed6

mGBA Game Boy Advance Emulator

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

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