all repos — mgba @ ba186f1a78f54297af608d8ebd8c48e0184c66b5

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