all repos — mgba @ dbd3aba5272012e16d66d6bc80a7cd653b8c8dbe

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::mustRestart);
 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	detachWidget(m_display.get());
 810	m_screenWidget->setDimensions(m_logo.width(), m_logo.height());
 811	m_screenWidget->setLockIntegerScaling(false);
 812	m_screenWidget->setLockAspectRatio(true);
 813	m_screenWidget->setPixmap(m_logo);
 814	m_screenWidget->unsetCursor();
 815	if (m_display) {
 816#ifdef M_CORE_GB
 817		m_display->setMinimumSize(GB_VIDEO_HORIZONTAL_PIXELS, GB_VIDEO_VERTICAL_PIXELS);
 818#elif defined(M_CORE_GBA)
 819		m_display->setMinimumSize(GBA_VIDEO_HORIZONTAL_PIXELS, GBA_VIDEO_VERTICAL_PIXELS);
 820#endif
 821	}
 822
 823	m_actions.clearMenu("videoLayers");
 824	m_actions.clearMenu("audioChannels");
 825
 826	m_fpsTimer.stop();
 827	m_focusCheck.stop();
 828
 829	if (m_audioProcessor) {
 830		m_audioProcessor->stop();
 831		m_audioProcessor.reset();
 832	}
 833	m_display->stopDrawing();
 834
 835	m_controller.reset();
 836	updateTitle();
 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		if (m_controller->hardwareAccelerated()) {
 887			mustRestart();
 888			return;
 889		}
 890		m_display->stopDrawing();
 891		detachWidget(m_display.get());
 892	}
 893	m_display = std::move(std::unique_ptr<Display>(Display::create(this)));
 894#if defined(BUILD_GL) || defined(BUILD_GLES2)
 895	m_shaderView.reset();
 896	m_shaderView = std::make_unique<ShaderSelector>(m_display.get(), m_config);
 897#endif
 898
 899	connect(m_display.get(), &Display::hideCursor, [this]() {
 900		if (static_cast<QStackedLayout*>(m_screenWidget->layout())->currentWidget() == m_display.get()) {
 901			m_screenWidget->setCursor(Qt::BlankCursor);
 902		}
 903	});
 904	connect(m_display.get(), &Display::showCursor, [this]() {
 905		m_screenWidget->unsetCursor();
 906	});
 907
 908	const mCoreOptions* opts = m_config->options();
 909	m_display->lockAspectRatio(opts->lockAspectRatio);
 910	m_display->lockIntegerScaling(opts->lockIntegerScaling);
 911	m_display->interframeBlending(opts->interframeBlending);
 912	m_display->filter(opts->resampleVideo);
 913	m_screenWidget->filter(opts->resampleVideo);
 914	m_config->updateOption("showOSD");
 915#if defined(BUILD_GL) || defined(BUILD_GLES2)
 916	if (opts->shader) {
 917		struct VDir* shader = VDirOpen(opts->shader);
 918		if (shader && m_display->supportsShaders()) {
 919			m_display->setShaders(shader);
 920			m_shaderView->refreshShaders();
 921			shader->close(shader);
 922		}
 923	}
 924#endif
 925
 926	if (m_controller) {
 927		connect(m_controller.get(), &CoreController::stateLoaded, m_display.get(), &Display::resizeContext);
 928		connect(m_controller.get(), &CoreController::stateLoaded, m_display.get(), &Display::forceDraw);
 929		connect(m_controller.get(), &CoreController::rewound, m_display.get(), &Display::forceDraw);
 930		connect(m_controller.get(), &CoreController::paused, m_display.get(), &Display::pauseDrawing);
 931		connect(m_controller.get(), &CoreController::unpaused, m_display.get(), &Display::unpauseDrawing);
 932		connect(m_controller.get(), &CoreController::frameAvailable, m_display.get(), &Display::framePosted);
 933		connect(m_controller.get(), &CoreController::statusPosted, m_display.get(), &Display::showMessage);
 934		connect(m_controller.get(), &CoreController::didReset, m_display.get(), &Display::resizeContext);
 935
 936		attachWidget(m_display.get());
 937		m_display->startDrawing(m_controller);
 938	}
 939#ifdef M_CORE_GB
 940	m_display->setMinimumSize(GB_VIDEO_HORIZONTAL_PIXELS, GB_VIDEO_VERTICAL_PIXELS);
 941#elif defined(M_CORE_GBA)
 942	m_display->setMinimumSize(GBA_VIDEO_HORIZONTAL_PIXELS, GBA_VIDEO_VERTICAL_PIXELS);
 943#endif
 944}
 945
 946void Window::reloadAudioDriver() {
 947	if (!m_controller) {
 948		return;
 949	}
 950	if (m_audioProcessor) {
 951		m_audioProcessor->stop();
 952		m_audioProcessor.reset();
 953	}
 954
 955	const mCoreOptions* opts = m_config->options();
 956	m_audioProcessor = std::move(std::unique_ptr<AudioProcessor>(AudioProcessor::create()));
 957	m_audioProcessor->setInput(m_controller);
 958	m_audioProcessor->setBufferSamples(opts->audioBuffers);
 959	m_audioProcessor->requestSampleRate(opts->sampleRate);
 960	m_audioProcessor->start();
 961	connect(m_controller.get(), &CoreController::stopping, m_audioProcessor.get(), &AudioProcessor::stop);
 962	connect(m_controller.get(), &CoreController::fastForwardChanged, m_audioProcessor.get(), &AudioProcessor::inputParametersChanged);
 963	connect(m_controller.get(), &CoreController::paused, m_audioProcessor.get(), &AudioProcessor::pause);
 964	connect(m_controller.get(), &CoreController::unpaused, m_audioProcessor.get(), &AudioProcessor::start);
 965}
 966
 967void Window::tryMakePortable() {
 968	QMessageBox* confirm = new QMessageBox(QMessageBox::Question, tr("Really make portable?"),
 969	                                       tr("This will make the emulator load its configuration from the same directory as the executable. Do you want to continue?"),
 970	                                       QMessageBox::Yes | QMessageBox::Cancel, this, Qt::Sheet);
 971	confirm->setAttribute(Qt::WA_DeleteOnClose);
 972	connect(confirm->button(QMessageBox::Yes), &QAbstractButton::clicked, m_config, &ConfigController::makePortable);
 973	confirm->show();
 974}
 975
 976void Window::mustRestart() {
 977	if (m_mustRestart.isActive()) {
 978		return;
 979	}
 980	m_mustRestart.start();
 981	QMessageBox* dialog = new QMessageBox(QMessageBox::Warning, tr("Restart needed"),
 982	                                      tr("Some changes will not take effect until the emulator is restarted."),
 983	                                      QMessageBox::Ok, this, Qt::Sheet);
 984	dialog->setAttribute(Qt::WA_DeleteOnClose);
 985	dialog->show();
 986}
 987
 988void Window::recordFrame() {
 989	m_frameList.append(m_frameTimer.nsecsElapsed());
 990	m_frameTimer.restart();
 991}
 992
 993void Window::showFPS() {
 994	if (m_frameList.isEmpty()) {
 995		updateTitle();
 996		return;
 997	}
 998	qint64 total = 0;
 999	for (qint64 t : m_frameList) {
1000		total += t;
1001	}
1002	double fps = (m_frameList.size() * 1e10) / total;
1003	m_frameList.clear();
1004	fps = round(fps) / 10.f;
1005	updateTitle(fps);
1006}
1007
1008void Window::updateTitle(float fps) {
1009	QString title;
1010
1011	if (m_controller) {
1012		CoreController::Interrupter interrupter(m_controller);
1013		const NoIntroDB* db = GBAApp::app()->gameDB();
1014		NoIntroGame game{};
1015		uint32_t crc32 = 0;
1016		m_controller->thread()->core->checksum(m_controller->thread()->core, &crc32, CHECKSUM_CRC32);
1017
1018		char gameTitle[17] = { '\0' };
1019		mCore* core = m_controller->thread()->core;
1020		core->getGameTitle(core, gameTitle);
1021		title = gameTitle;
1022
1023#ifdef USE_SQLITE3
1024		if (db && crc32 && NoIntroDBLookupGameByCRC(db, crc32, &game)) {
1025			title = QLatin1String(game.name);
1026		}
1027#endif
1028		MultiplayerController* multiplayer = m_controller->multiplayerController();
1029		if (multiplayer && multiplayer->attached() > 1) {
1030			title += tr(" -  Player %1 of %2").arg(multiplayer->playerId(m_controller.get()) + 1).arg(multiplayer->attached());
1031			for (Action* action : m_nonMpActions) {
1032				action->setEnabled(false);
1033			}
1034		} else {
1035			for (Action* action : m_nonMpActions) {
1036				action->setEnabled(true);
1037			}
1038		}
1039	}
1040	if (title.isNull()) {
1041		setWindowTitle(tr("%1 - %2").arg(projectName).arg(projectVersion));
1042	} else if (fps < 0) {
1043		setWindowTitle(tr("%1 - %2 - %3").arg(projectName).arg(title).arg(projectVersion));
1044	} else {
1045		setWindowTitle(tr("%1 - %2 (%3 fps) - %4").arg(projectName).arg(title).arg(fps).arg(projectVersion));
1046	}
1047}
1048
1049void Window::openStateWindow(LoadSave ls) {
1050	if (m_stateWindow) {
1051		return;
1052	}
1053	MultiplayerController* multiplayer = m_controller->multiplayerController();
1054	if (multiplayer && multiplayer->attached() > 1) {
1055		return;
1056	}
1057	bool wasPaused = m_controller->isPaused();
1058	m_stateWindow = new LoadSaveState(m_controller);
1059	connect(this, &Window::shutdown, m_stateWindow, &QWidget::close);
1060	connect(m_stateWindow, &LoadSaveState::closed, [this]() {
1061		detachWidget(m_stateWindow);
1062		m_stateWindow = nullptr;
1063		QMetaObject::invokeMethod(this, "setFocus", Qt::QueuedConnection);
1064	});
1065	if (!wasPaused) {
1066		m_controller->setPaused(true);
1067		connect(m_stateWindow, &LoadSaveState::closed, [this]() {
1068			if (m_controller) {
1069				m_controller->setPaused(false);
1070			}
1071		});
1072	}
1073	m_stateWindow->setAttribute(Qt::WA_DeleteOnClose);
1074	m_stateWindow->setMode(ls);
1075	updateFrame();
1076#ifndef Q_OS_MAC
1077	menuBar()->show();
1078#endif
1079	attachWidget(m_stateWindow);
1080}
1081
1082void Window::setupMenu(QMenuBar* menubar) {
1083	installEventFilter(m_shortcutController);
1084
1085	menubar->clear();
1086	m_actions.addMenu(tr("&File"), "file");
1087
1088	m_actions.addAction(tr("Load &ROM..."), "loadROM", this, &Window::selectROM, "file", QKeySequence::Open);
1089
1090#ifdef USE_SQLITE3
1091	m_actions.addAction(tr("Load ROM in archive..."), "loadROMInArchive", this, &Window::selectROMInArchive, "file");
1092	m_actions.addAction(tr("Add folder to library..."), "addDirToLibrary", this, &Window::addDirToLibrary, "file");
1093#endif
1094
1095	addGameAction(tr("Load alternate save..."), "loadAlternateSave", [this]() {
1096		this->selectSave(false);
1097	}, "file");
1098	addGameAction(tr("Load temporary save..."), "loadTemporarySave", [this]() {
1099		this->selectSave(true);
1100	}, "file");
1101
1102	m_actions.addAction(tr("Load &patch..."), "loadPatch", this, &Window::selectPatch, "file");
1103
1104#ifdef M_CORE_GBA
1105	Action* bootBIOS = m_actions.addAction(tr("Boot BIOS"), "bootBIOS", [this]() {
1106		setController(m_manager->loadBIOS(PLATFORM_GBA, m_config->getOption("gba.bios")), QString());
1107	}, "file");
1108#endif
1109
1110	m_actions.addAction(tr("Replace ROM..."), "replaceROM", this, &Window::replaceROM, "file");
1111
1112	Action* romInfo = addGameAction(tr("ROM &info..."), "romInfo", openControllerTView<ROMInfo>(), "file");
1113
1114	m_actions.addMenu(tr("Recent"), "mru", "file");
1115	m_actions.addSeparator("file");
1116
1117	m_actions.addAction(tr("Make portable"), "makePortable", this, &Window::tryMakePortable, "file");
1118	m_actions.addSeparator("file");
1119
1120	Action* loadState = addGameAction(tr("&Load state"), "loadState", [this]() {
1121		this->openStateWindow(LoadSave::LOAD);
1122	}, "file", QKeySequence("F10"));
1123	m_nonMpActions.append(loadState);
1124
1125	Action* loadStateFile = addGameAction(tr("Load state file..."), "loadStateFile", [this]() {
1126		this->selectState(true);
1127	}, "file");
1128	m_nonMpActions.append(loadStateFile);
1129
1130	Action* saveState = addGameAction(tr("&Save state"), "saveState", [this]() {
1131		this->openStateWindow(LoadSave::SAVE);
1132	}, "file", QKeySequence("Shift+F10"));
1133	m_nonMpActions.append(saveState);
1134
1135	Action* saveStateFile = addGameAction(tr("Save state file..."), "saveStateFile", [this]() {
1136		this->selectState(false);
1137	}, "file");
1138	m_nonMpActions.append(saveStateFile);
1139
1140	m_actions.addMenu(tr("Quick load"), "quickLoad", "file");
1141	m_actions.addMenu(tr("Quick save"), "quickSave", "file");
1142
1143	Action* quickLoad = addGameAction(tr("Load recent"), "quickLoad", [this] {
1144		m_controller->loadState();
1145	}, "quickLoad");
1146	m_nonMpActions.append(quickLoad);
1147
1148	Action* quickSave = addGameAction(tr("Save recent"), "quickSave", [this] {
1149		m_controller->saveState();
1150	}, "quickSave");
1151	m_nonMpActions.append(quickSave);
1152
1153	m_actions.addSeparator("quickLoad");
1154	m_actions.addSeparator("quickSave");
1155
1156	Action* undoLoadState = addGameAction(tr("Undo load state"), "undoLoadState", [this]() {
1157		m_controller->loadBackupState();
1158	}, "quickLoad", QKeySequence("F11"));
1159	m_nonMpActions.append(undoLoadState);
1160
1161	Action* undoSaveState = addGameAction(tr("Undo save state"), "undoSaveState", [this]() {
1162		m_controller->saveBackupState();
1163	}, "quickSave", QKeySequence("Shift+F11"));
1164	m_nonMpActions.append(undoSaveState);
1165
1166	m_actions.addSeparator("quickLoad");
1167	m_actions.addSeparator("quickSave");
1168
1169	for (int i = 1; i < 10; ++i) {
1170		Action* quickLoad = addGameAction(tr("State &%1").arg(i),  QString("quickLoad.%1").arg(i), [this, i]() {
1171			m_controller->loadState(i);
1172		}, "quickLoad", QString("F%1").arg(i));
1173		m_nonMpActions.append(quickLoad);
1174
1175		Action* quickSave = addGameAction(tr("State &%1").arg(i),  QString("quickSave.%1").arg(i), [this, i]() {
1176			m_controller->saveState(i);
1177		}, "quickSave", QString("Shift+F%1").arg(i));
1178		m_nonMpActions.append(quickSave);
1179	}
1180
1181	m_actions.addSeparator("file");
1182	m_actions.addAction(tr("Load camera image..."), "loadCamImage", this, &Window::loadCamImage, "file");
1183
1184#ifdef M_CORE_GBA
1185	m_actions.addSeparator("file");
1186	Action* importShark = addGameAction(tr("Import GameShark Save"), "importShark", this, &Window::importSharkport, "file");
1187	m_platformActions.insert(PLATFORM_GBA, importShark);
1188
1189	Action* exportShark = addGameAction(tr("Export GameShark Save"), "exportShark", this, &Window::exportSharkport, "file");
1190	m_platformActions.insert(PLATFORM_GBA, exportShark);
1191#endif
1192
1193	m_actions.addSeparator("file");
1194	m_multiWindow = m_actions.addAction(tr("New multiplayer window"), "multiWindow", [this]() {
1195		GBAApp::app()->newWindow();
1196	}, "file");
1197
1198#ifndef Q_OS_MAC
1199	m_actions.addSeparator("file");
1200#endif
1201
1202	m_actions.addAction(tr("About..."), "about", openTView<AboutScreen>(), "file");
1203
1204#ifndef Q_OS_MAC
1205	m_actions.addAction(tr("E&xit"), "quit", static_cast<QWidget*>(this), &QWidget::close, "file", QKeySequence::Quit);
1206#endif
1207
1208	m_actions.addMenu(tr("&Emulation"), "emu");
1209	addGameAction(tr("&Reset"), "reset", [this]() {
1210		m_controller->reset();
1211	}, "emu", QKeySequence("Ctrl+R"));
1212
1213	addGameAction(tr("Sh&utdown"), "shutdown", [this]() {
1214		m_controller->stop();
1215	}, "emu");
1216
1217	Action* yank = addGameAction(tr("Yank game pak"), "yank", [this]() {
1218		m_controller->yankPak();
1219	}, "emu");
1220
1221	m_actions.addSeparator("emu");
1222
1223	Action* pause = m_actions.addBooleanAction(tr("&Pause"), "pause", [this](bool paused) {
1224		if (m_controller) {
1225			m_controller->setPaused(paused);
1226		} else {
1227			m_pendingPause = paused;
1228		}
1229	}, "emu", QKeySequence("Ctrl+P"));
1230	connect(this, &Window::paused, pause, &Action::setActive);
1231
1232	addGameAction(tr("&Next frame"), "frameAdvance", [this]() {
1233		m_controller->frameAdvance();
1234	}, "emu", QKeySequence("Ctrl+N"));
1235
1236	m_actions.addSeparator("emu");
1237
1238	m_actions.addHeldAction(tr("Fast forward (held)"), "holdFastForward", [this](bool held) {
1239		if (m_controller) {
1240			m_controller->setFastForward(held);
1241		}
1242	}, "emu", QKeySequence(Qt::Key_Tab));
1243
1244	addGameAction(tr("&Fast forward"), "fastForward", [this](bool value) {
1245		m_controller->forceFastForward(value);
1246	}, "emu", QKeySequence("Shift+Tab"));
1247
1248	m_actions.addMenu(tr("Fast forward speed"), "fastForwardSpeed", "emu");
1249	ConfigOption* ffspeed = m_config->addOption("fastForwardRatio");
1250	ffspeed->connect([this](const QVariant& value) {
1251		reloadConfig();
1252	}, this);
1253	ffspeed->addValue(tr("Unbounded"), -1.0f, &m_actions, "fastForwardSpeed");
1254	ffspeed->setValue(QVariant(-1.0f));
1255	m_actions.addSeparator("fastForwardSpeed");
1256	for (int i = 2; i < 11; ++i) {
1257		ffspeed->addValue(tr("%0x").arg(i), i, &m_actions, "fastForwardSpeed");
1258	}
1259	m_config->updateOption("fastForwardRatio");
1260
1261	Action* rewindHeld = m_actions.addHeldAction(tr("Rewind (held)"), "holdRewind", [this](bool held) {
1262		if (m_controller) {
1263			m_controller->setRewinding(held);
1264		}
1265	}, "emu", QKeySequence("`"));
1266	m_nonMpActions.append(rewindHeld);
1267
1268	Action* rewind = addGameAction(tr("Re&wind"), "rewind", [this]() {
1269		m_controller->rewind();
1270	}, "emu", QKeySequence("~"));
1271	m_nonMpActions.append(rewind);
1272
1273	Action* frameRewind = addGameAction(tr("Step backwards"), "frameRewind", [this] () {
1274		m_controller->rewind(1);
1275	}, "emu", QKeySequence("Ctrl+B"));
1276	m_nonMpActions.append(frameRewind);
1277
1278	ConfigOption* videoSync = m_config->addOption("videoSync");
1279	videoSync->addBoolean(tr("Sync to &video"), &m_actions, "emu");
1280	videoSync->connect([this](const QVariant& value) {
1281		reloadConfig();
1282	}, this);
1283	m_config->updateOption("videoSync");
1284
1285	ConfigOption* audioSync = m_config->addOption("audioSync");
1286	audioSync->addBoolean(tr("Sync to &audio"), &m_actions, "emu");
1287	audioSync->connect([this](const QVariant& value) {
1288		reloadConfig();
1289	}, this);
1290	m_config->updateOption("audioSync");
1291
1292	m_actions.addSeparator("emu");
1293
1294	m_actions.addMenu(tr("Solar sensor"), "solar", "emu");
1295	m_actions.addAction(tr("Increase solar level"), "increaseLuminanceLevel", &m_inputController, &InputController::increaseLuminanceLevel, "solar");
1296	m_actions.addAction(tr("Decrease solar level"), "decreaseLuminanceLevel", &m_inputController, &InputController::decreaseLuminanceLevel, "solar");
1297	m_actions.addAction(tr("Brightest solar level"), "maxLuminanceLevel", [this]() {
1298		m_inputController.setLuminanceLevel(10);
1299	}, "solar");
1300	m_actions.addAction(tr("Darkest solar level"), "minLuminanceLevel", [this]() {
1301		m_inputController.setLuminanceLevel(0);
1302	}, "solar");
1303
1304	m_actions.addSeparator("solar");
1305	for (int i = 0; i <= 10; ++i) {
1306		m_actions.addAction(tr("Brightness %1").arg(QString::number(i)), QString("luminanceLevel.%1").arg(QString::number(i)), [this, i]() {
1307			m_inputController.setLuminanceLevel(i);
1308		}, "solar");
1309	}
1310
1311#ifdef M_CORE_GB
1312	Action* gbPrint = addGameAction(tr("Game Boy Printer..."), "gbPrint", [this]() {
1313		PrinterView* view = new PrinterView(m_controller);
1314		openView(view);
1315		m_controller->attachPrinter();
1316	}, "emu");
1317	m_platformActions.insert(PLATFORM_GB, gbPrint);
1318#endif
1319
1320#ifdef M_CORE_GBA
1321	Action* bcGate = addGameAction(tr("BattleChip Gate..."), "bcGate", openControllerTView<BattleChipView>(this), "emu");
1322	m_platformActions.insert(PLATFORM_GBA, bcGate);
1323#endif
1324
1325	m_actions.addMenu(tr("Audio/&Video"), "av");
1326	m_actions.addMenu(tr("Frame size"), "frame", "av");
1327	for (int i = 1; i <= 8; ++i) {
1328		Action* setSize = m_actions.addAction(tr("%1×").arg(QString::number(i)), QString("frame.%1x").arg(QString::number(i)), [this, i]() {
1329			Action* setSize = m_frameSizes[i];
1330			showNormal();
1331			QSize size(GBA_VIDEO_HORIZONTAL_PIXELS, GBA_VIDEO_VERTICAL_PIXELS);
1332			if (m_controller) {
1333				size = m_controller->screenDimensions();
1334			}
1335			size *= i;
1336			m_savedScale = i;
1337			m_config->setOption("scaleMultiplier", i); // TODO: Port to other
1338			resizeFrame(size);
1339			setSize->setActive(true);
1340		}, "frame");
1341		setSize->setExclusive(true);
1342		if (m_savedScale == i) {
1343			setSize->setActive(true);
1344		}
1345		m_frameSizes[i] = setSize;
1346	}
1347	QKeySequence fullscreenKeys;
1348#ifdef Q_OS_WIN
1349	fullscreenKeys = QKeySequence("Alt+Return");
1350#else
1351	fullscreenKeys = QKeySequence("Ctrl+F");
1352#endif
1353	m_actions.addAction(tr("Toggle fullscreen"), "fullscreen", this, &Window::toggleFullScreen, "frame", fullscreenKeys);
1354
1355	ConfigOption* lockAspectRatio = m_config->addOption("lockAspectRatio");
1356	lockAspectRatio->addBoolean(tr("Lock aspect ratio"), &m_actions, "av");
1357	lockAspectRatio->connect([this](const QVariant& value) {
1358		if (m_display) {
1359			m_display->lockAspectRatio(value.toBool());
1360		}
1361		if (m_controller) {
1362			m_screenWidget->setLockAspectRatio(value.toBool());
1363		}
1364	}, this);
1365	m_config->updateOption("lockAspectRatio");
1366
1367	ConfigOption* lockIntegerScaling = m_config->addOption("lockIntegerScaling");
1368	lockIntegerScaling->addBoolean(tr("Force integer scaling"), &m_actions, "av");
1369	lockIntegerScaling->connect([this](const QVariant& value) {
1370		if (m_display) {
1371			m_display->lockIntegerScaling(value.toBool());
1372		}
1373		if (m_controller) {
1374			m_screenWidget->setLockIntegerScaling(value.toBool());
1375		}
1376	}, this);
1377	m_config->updateOption("lockIntegerScaling");
1378
1379	ConfigOption* interframeBlending = m_config->addOption("interframeBlending");
1380	interframeBlending->addBoolean(tr("Interframe blending"), &m_actions, "av");
1381	interframeBlending->connect([this](const QVariant& value) {
1382		if (m_display) {
1383			m_display->interframeBlending(value.toBool());
1384		}
1385	}, this);
1386	m_config->updateOption("interframeBlending");
1387
1388	ConfigOption* resampleVideo = m_config->addOption("resampleVideo");
1389	resampleVideo->addBoolean(tr("Bilinear filtering"), &m_actions, "av");
1390	resampleVideo->connect([this](const QVariant& value) {
1391		if (m_display) {
1392			m_display->filter(value.toBool());
1393		}
1394		m_screenWidget->filter(value.toBool());
1395	}, this);
1396	m_config->updateOption("resampleVideo");
1397
1398	m_actions.addMenu(tr("Frame&skip"),"skip", "av");
1399	ConfigOption* skip = m_config->addOption("frameskip");
1400	skip->connect([this](const QVariant& value) {
1401		reloadConfig();
1402	}, this);
1403	for (int i = 0; i <= 10; ++i) {
1404		skip->addValue(QString::number(i), i, &m_actions, "skip");
1405	}
1406	m_config->updateOption("frameskip");
1407
1408	m_actions.addSeparator("av");
1409
1410	ConfigOption* mute = m_config->addOption("mute");
1411	mute->addBoolean(tr("Mute"), &m_actions, "av");
1412	mute->connect([this](const QVariant& value) {
1413		if (value.toInt()) {
1414			m_config->setOption("fastForwardMute", true);
1415		}
1416		reloadConfig();
1417	}, this);
1418	m_config->updateOption("mute");
1419
1420	m_actions.addMenu(tr("FPS target"),"target", "av");
1421	ConfigOption* fpsTargetOption = m_config->addOption("fpsTarget");
1422	QMap<double, Action*> fpsTargets;
1423	for (int fps : {15, 30, 45, 60, 90, 120, 240}) {
1424		fpsTargets[fps] = fpsTargetOption->addValue(QString::number(fps), fps, &m_actions, "target");
1425	}
1426	m_actions.addSeparator("target");
1427	double nativeGB = double(GBA_ARM7TDMI_FREQUENCY) / double(VIDEO_TOTAL_LENGTH);
1428	fpsTargets[nativeGB] = fpsTargetOption->addValue(tr("Native (59.7275)"), nativeGB, &m_actions, "target");
1429
1430	fpsTargetOption->connect([this, fpsTargets](const QVariant& value) {
1431		reloadConfig();
1432		for (auto iter = fpsTargets.begin(); iter != fpsTargets.end(); ++iter) {
1433			bool enableSignals = iter.value()->blockSignals(true);
1434			iter.value()->setActive(abs(iter.key() - value.toDouble()) < 0.001);
1435			iter.value()->blockSignals(enableSignals);
1436		}
1437	}, this);
1438	m_config->updateOption("fpsTarget");
1439
1440	m_actions.addSeparator("av");
1441
1442#ifdef USE_PNG
1443	addGameAction(tr("Take &screenshot"), "screenshot", [this]() {
1444		m_controller->screenshot();
1445	}, "av", tr("F12"));
1446#endif
1447
1448#ifdef USE_FFMPEG
1449	addGameAction(tr("Record A/V..."), "recordOutput", this, &Window::openVideoWindow, "av");
1450	addGameAction(tr("Record GIF..."), "recordGIF", this, &Window::openGIFWindow, "av");
1451#endif
1452
1453	m_actions.addSeparator("av");
1454	m_actions.addMenu(tr("Video layers"), "videoLayers", "av");
1455	m_actions.addMenu(tr("Audio channels"), "audioChannels", "av");
1456
1457	addGameAction(tr("Adjust layer placement..."), "placementControl", openControllerTView<PlacementControl>(), "av");
1458
1459	m_actions.addMenu(tr("&Tools"), "tools");
1460	m_actions.addAction(tr("View &logs..."), "viewLogs", static_cast<QWidget*>(m_logView), &QWidget::show, "tools");
1461
1462	m_actions.addAction(tr("Game &overrides..."), "overrideWindow", [this]() {
1463		if (!m_overrideView) {
1464			m_overrideView = std::move(std::make_unique<OverrideView>(m_config));
1465			if (m_controller) {
1466				m_overrideView->setController(m_controller);
1467			}
1468			connect(this, &Window::shutdown, m_overrideView.get(), &QWidget::close);
1469		}
1470		m_overrideView->show();
1471		m_overrideView->recheck();
1472	}, "tools");
1473
1474	m_actions.addAction(tr("Game Pak sensors..."), "sensorWindow", [this]() {
1475		if (!m_sensorView) {
1476			m_sensorView = std::move(std::make_unique<SensorView>(&m_inputController));
1477			if (m_controller) {
1478				m_sensorView->setController(m_controller);
1479			}
1480			connect(this, &Window::shutdown, m_sensorView.get(), &QWidget::close);
1481		}
1482		m_sensorView->show();
1483	}, "tools");
1484
1485	addGameAction(tr("&Cheats..."), "cheatsWindow", openControllerTView<CheatsView>(), "tools");
1486
1487	m_actions.addSeparator("tools");
1488	m_actions.addAction(tr("Settings..."), "settings", this, &Window::openSettingsWindow, "tools");
1489
1490#ifdef USE_DEBUGGERS
1491	m_actions.addSeparator("tools");
1492	m_actions.addAction(tr("Open debugger console..."), "debuggerWindow", this, &Window::consoleOpen, "tools");
1493#ifdef USE_GDB_STUB
1494	Action* gdbWindow = addGameAction(tr("Start &GDB server..."), "gdbWindow", this, &Window::gdbOpen, "tools");
1495	m_platformActions.insert(PLATFORM_GBA, gdbWindow);
1496#endif
1497#endif
1498	m_actions.addSeparator("tools");
1499
1500	addGameAction(tr("View &palette..."), "paletteWindow", openControllerTView<PaletteView>(), "tools");
1501	addGameAction(tr("View &sprites..."), "spriteWindow", openControllerTView<ObjView>(), "tools");
1502	addGameAction(tr("View &tiles..."), "tileWindow", openControllerTView<TileView>(), "tools");
1503	addGameAction(tr("View &map..."), "mapWindow", openControllerTView<MapView>(), "tools");
1504
1505#ifdef M_CORE_GBA
1506	Action* frameWindow = addGameAction(tr("&Frame inspector..."), "frameWindow", [this]() {
1507		if (!m_frameView) {
1508			m_frameView = new FrameView(m_controller);
1509			connect(this, &Window::shutdown, this, [this]() {
1510				if (m_frameView) {
1511					m_frameView->close();
1512				}
1513			});
1514			connect(m_frameView, &QObject::destroyed, this, [this]() {
1515				m_frameView = nullptr;
1516			});
1517			m_frameView->setAttribute(Qt::WA_DeleteOnClose);
1518		}
1519		m_frameView->show();
1520	}, "tools");
1521	m_platformActions.insert(PLATFORM_GBA, frameWindow);
1522#endif
1523
1524	addGameAction(tr("View memory..."), "memoryView", openControllerTView<MemoryView>(), "tools");
1525	addGameAction(tr("Search memory..."), "memorySearch", openControllerTView<MemorySearch>(), "tools");
1526
1527#ifdef M_CORE_GBA
1528	Action* ioViewer = addGameAction(tr("View &I/O registers..."), "ioViewer", openControllerTView<IOViewer>(), "tools");
1529	m_platformActions.insert(PLATFORM_GBA, ioViewer);
1530#endif
1531
1532	m_actions.addSeparator("tools");
1533	addGameAction(tr("Record debug video log..."), "recordVL", this, &Window::startVideoLog, "tools");
1534	addGameAction(tr("Stop debug video log"), "stopVL", [this]() {
1535		m_controller->endVideoLog();
1536	}, "tools");
1537
1538	ConfigOption* skipBios = m_config->addOption("skipBios");
1539	skipBios->connect([this](const QVariant& value) {
1540		reloadConfig();
1541	}, this);
1542
1543	ConfigOption* useBios = m_config->addOption("useBios");
1544	useBios->connect([this](const QVariant& value) {
1545		reloadConfig();
1546	}, this);
1547
1548	ConfigOption* buffers = m_config->addOption("audioBuffers");
1549	buffers->connect([this](const QVariant& value) {
1550		reloadConfig();
1551	}, this);
1552
1553	ConfigOption* sampleRate = m_config->addOption("sampleRate");
1554	sampleRate->connect([this](const QVariant& value) {
1555		reloadConfig();
1556	}, this);
1557
1558	ConfigOption* volume = m_config->addOption("volume");
1559	volume->connect([this](const QVariant& value) {
1560		reloadConfig();
1561	}, this);
1562
1563	ConfigOption* volumeFf = m_config->addOption("fastForwardVolume");
1564	volumeFf->connect([this](const QVariant& value) {
1565		reloadConfig();
1566	}, this);
1567
1568	ConfigOption* muteFf = m_config->addOption("fastForwardMute");
1569	muteFf->connect([this](const QVariant& value) {
1570		reloadConfig();
1571	}, this);
1572
1573	ConfigOption* rewindEnable = m_config->addOption("rewindEnable");
1574	rewindEnable->connect([this](const QVariant& value) {
1575		reloadConfig();
1576	}, this);
1577
1578	ConfigOption* rewindBufferCapacity = m_config->addOption("rewindBufferCapacity");
1579	rewindBufferCapacity->connect([this](const QVariant& value) {
1580		reloadConfig();
1581	}, this);
1582
1583	ConfigOption* allowOpposingDirections = m_config->addOption("allowOpposingDirections");
1584	allowOpposingDirections->connect([this](const QVariant& value) {
1585		reloadConfig();
1586	}, this);
1587
1588	ConfigOption* saveStateExtdata = m_config->addOption("saveStateExtdata");
1589	saveStateExtdata->connect([this](const QVariant& value) {
1590		reloadConfig();
1591	}, this);
1592
1593	ConfigOption* loadStateExtdata = m_config->addOption("loadStateExtdata");
1594	loadStateExtdata->connect([this](const QVariant& value) {
1595		reloadConfig();
1596	}, this);
1597
1598	ConfigOption* preload = m_config->addOption("preload");
1599	preload->connect([this](const QVariant& value) {
1600		m_manager->setPreload(value.toBool());
1601	}, this);
1602	m_config->updateOption("preload");
1603
1604	ConfigOption* showFps = m_config->addOption("showFps");
1605	showFps->connect([this](const QVariant& value) {
1606		if (!value.toInt()) {
1607			m_fpsTimer.stop();
1608			updateTitle();
1609		} else if (m_controller) {
1610			m_fpsTimer.start();
1611			m_frameTimer.start();
1612		}
1613	}, this);
1614
1615	ConfigOption* showOSD = m_config->addOption("showOSD");
1616	showOSD->connect([this](const QVariant& value) {
1617		if (m_display) {
1618			m_display->showOSDMessages(value.toBool());
1619		}
1620	}, this);
1621
1622	ConfigOption* videoScale = m_config->addOption("videoScale");
1623	videoScale->connect([this](const QVariant& value) {
1624		if (m_display) {
1625			m_display->setVideoScale(value.toInt());
1626		}
1627	}, this);
1628
1629	m_actions.addHiddenAction(tr("Exit fullscreen"), "exitFullScreen", this, &Window::exitFullScreen, "frame", QKeySequence("Esc"));
1630
1631	m_actions.addHeldAction(tr("GameShark Button (held)"), "holdGSButton", [this](bool held) {
1632		if (m_controller) {
1633			mCheatPressButton(m_controller->cheatDevice(), held);
1634		}
1635	}, "tools", QKeySequence(Qt::Key_Apostrophe));
1636
1637	m_actions.addHiddenMenu(tr("Autofire"), "autofire");
1638	m_actions.addHeldAction(tr("Autofire A"), "autofireA", [this](bool held) {
1639		if (m_controller) {
1640			m_controller->setAutofire(GBA_KEY_A, held);
1641		}
1642	}, "autofire");
1643	m_actions.addHeldAction(tr("Autofire B"), "autofireB", [this](bool held) {
1644		if (m_controller) {
1645			m_controller->setAutofire(GBA_KEY_B, held);
1646		}
1647	}, "autofire");
1648	m_actions.addHeldAction(tr("Autofire L"), "autofireL", [this](bool held) {
1649		if (m_controller) {
1650			m_controller->setAutofire(GBA_KEY_L, held);
1651		}
1652	}, "autofire");
1653	m_actions.addHeldAction(tr("Autofire R"), "autofireR", [this](bool held) {
1654		if (m_controller) {
1655			m_controller->setAutofire(GBA_KEY_R, held);
1656		}
1657	}, "autofire");
1658	m_actions.addHeldAction(tr("Autofire Start"), "autofireStart", [this](bool held) {
1659		if (m_controller) {
1660			m_controller->setAutofire(GBA_KEY_START, held);
1661		}
1662	}, "autofire");
1663	m_actions.addHeldAction(tr("Autofire Select"), "autofireSelect", [this](bool held) {
1664		if (m_controller) {
1665			m_controller->setAutofire(GBA_KEY_SELECT, held);
1666		}
1667	}, "autofire");
1668	m_actions.addHeldAction(tr("Autofire Up"), "autofireUp", [this](bool held) {
1669		if (m_controller) {
1670			m_controller->setAutofire(GBA_KEY_UP, held);
1671		}
1672	}, "autofire");
1673	m_actions.addHeldAction(tr("Autofire Right"), "autofireRight", [this](bool held) {
1674		if (m_controller) {
1675			m_controller->setAutofire(GBA_KEY_RIGHT, held);
1676		}
1677	}, "autofire");
1678	m_actions.addHeldAction(tr("Autofire Down"), "autofireDown", [this](bool held) {
1679		if (m_controller) {
1680			m_controller->setAutofire(GBA_KEY_DOWN, held);
1681		}
1682	}, "autofire");
1683	m_actions.addHeldAction(tr("Autofire Left"), "autofireLeft", [this](bool held) {
1684		if (m_controller) {
1685			m_controller->setAutofire(GBA_KEY_LEFT, held);
1686		}
1687	}, "autofire");
1688
1689	for (Action* action : m_gameActions) {
1690		action->setEnabled(false);
1691	}
1692
1693	m_shortcutController->rebuildItems();
1694	m_actions.rebuildMenu(menuBar(), this, *m_shortcutController);
1695}
1696
1697void Window::attachWidget(QWidget* widget) {
1698	m_screenWidget->layout()->addWidget(widget);
1699	m_screenWidget->unsetCursor();
1700	static_cast<QStackedLayout*>(m_screenWidget->layout())->setCurrentWidget(widget);
1701}
1702
1703void Window::detachWidget(QWidget* widget) {
1704	m_screenWidget->layout()->removeWidget(widget);
1705}
1706
1707void Window::appendMRU(const QString& fname) {
1708	int index = m_mruFiles.indexOf(fname);
1709	if (index >= 0) {
1710		m_mruFiles.removeAt(index);
1711	}
1712	m_mruFiles.prepend(fname);
1713	while (m_mruFiles.size() > ConfigController::MRU_LIST_SIZE) {
1714		m_mruFiles.removeLast();
1715	}
1716	updateMRU();
1717}
1718
1719void Window::clearMRU() {
1720	m_mruFiles.clear();
1721	updateMRU();
1722}
1723
1724void Window::updateMRU() {
1725	m_actions.clearMenu("mru");
1726	int i = 0;
1727	for (const QString& file : m_mruFiles) {
1728		QString displayName(QDir::toNativeSeparators(file).replace("&", "&&"));
1729		m_actions.addAction(displayName, QString("mru.%1").arg(QString::number(i)), [this, file]() {
1730			setController(m_manager->loadGame(file), file);
1731		}, "mru", QString("Ctrl+%1").arg(i));
1732		++i;
1733	}
1734	m_config->setMRU(m_mruFiles);
1735	m_config->write();
1736	m_actions.addSeparator("mru");
1737	m_actions.addAction(tr("Clear"), "resetMru", this, &Window::clearMRU, "mru");
1738
1739	m_actions.rebuildMenu(menuBar(), this, *m_shortcutController);
1740}
1741
1742Action* Window::addGameAction(const QString& visibleName, const QString& name, Action::Function function, const QString& menu, const QKeySequence& shortcut) {
1743	Action* action = m_actions.addAction(visibleName, name, [this, function]() {
1744		if (m_controller) {
1745			function();
1746		}
1747	}, menu, shortcut);
1748	m_gameActions.append(action);
1749	return action;
1750}
1751
1752template<typename T, typename V>
1753Action* Window::addGameAction(const QString& visibleName, const QString& name, T* obj, V (T::*method)(), const QString& menu, const QKeySequence& shortcut) {
1754	return addGameAction(visibleName, name, [this, obj, method]() {
1755		if (m_controller) {
1756			(obj->*method)();
1757		}
1758	}, menu, shortcut);
1759}
1760
1761Action* Window::addGameAction(const QString& visibleName, const QString& name, Action::BooleanFunction function, const QString& menu, const QKeySequence& shortcut) {
1762	Action* action = m_actions.addBooleanAction(visibleName, name, [this, function](bool value) {
1763		if (m_controller) {
1764			function(value);
1765		}
1766	}, menu, shortcut);
1767	m_gameActions.append(action);
1768	return action;
1769}
1770
1771void Window::focusCheck() {
1772	if (!m_config->getOption("pauseOnFocusLost").toInt() || !m_controller) {
1773		return;
1774	}
1775	if (QGuiApplication::focusWindow() && m_autoresume) {
1776		m_controller->setPaused(false);
1777		m_autoresume = false;
1778	} else if (!QGuiApplication::focusWindow() && !m_controller->isPaused()) {
1779		m_autoresume = true;
1780		m_controller->setPaused(true);
1781	}
1782}
1783
1784void Window::updateFrame() {
1785	QPixmap pixmap;
1786	pixmap.convertFromImage(m_controller->getPixels());
1787	m_screenWidget->setPixmap(pixmap);
1788	emit paused(true);
1789}
1790
1791void Window::setController(CoreController* controller, const QString& fname) {
1792	if (!controller) {
1793		return;
1794	}
1795	if (m_pendingClose) {
1796		return;
1797	}
1798
1799	if (m_controller) {
1800		m_controller->stop();
1801		QTimer::singleShot(0, this, [this, controller, fname]() {
1802			setController(controller, fname);
1803		});
1804		return;
1805	}
1806	if (!fname.isEmpty()) {
1807		setWindowFilePath(fname);
1808		appendMRU(fname);
1809	}
1810
1811	if (!m_display) {
1812		reloadDisplayDriver();
1813	}
1814
1815	if (m_config->getOption("hwaccelVideo").toInt() && m_display->supportsShaders() && controller->supportsFeature(CoreController::Feature::OPENGL)) {
1816		std::shared_ptr<VideoProxy> proxy = std::make_shared<VideoProxy>();
1817		m_display->setVideoProxy(proxy);
1818		proxy->attach(controller);
1819
1820		int fb = m_display->framebufferHandle();
1821		if (fb >= 0) {
1822			controller->setFramebufferHandle(fb);
1823		}
1824	}
1825
1826	m_controller = std::shared_ptr<CoreController>(controller);
1827	m_inputController.recalibrateAxes();
1828	m_controller->setInputController(&m_inputController);
1829	m_controller->setLogger(&m_log);
1830	m_display->startDrawing(m_controller);
1831
1832	connect(this, &Window::shutdown, [this]() {
1833		if (!m_controller) {
1834			return;
1835		}
1836		m_controller->stop();
1837		disconnect(m_controller.get(), &CoreController::started, this, &Window::gameStarted);
1838	});
1839
1840	connect(m_controller.get(), &CoreController::started, this, &Window::gameStarted);
1841	connect(m_controller.get(), &CoreController::started, &m_inputController, &InputController::suspendScreensaver);
1842	connect(m_controller.get(), &CoreController::stopping, this, &Window::gameStopped);
1843	{
1844		connect(m_controller.get(), &CoreController::stopping, [this]() {
1845			m_controller.reset();
1846		});
1847	}
1848	connect(m_controller.get(), &CoreController::stopping, &m_inputController, &InputController::resumeScreensaver);
1849	connect(m_controller.get(), &CoreController::paused, this, &Window::updateFrame);
1850
1851#ifndef Q_OS_MAC
1852	connect(m_controller.get(), &CoreController::paused, menuBar(), &QWidget::show);
1853	connect(m_controller.get(), &CoreController::unpaused, [this]() {
1854		if(isFullScreen()) {
1855			menuBar()->hide();
1856		}
1857	});
1858#endif
1859
1860	connect(m_controller.get(), &CoreController::paused, &m_inputController, &InputController::resumeScreensaver);
1861	connect(m_controller.get(), &CoreController::unpaused, [this]() {
1862		emit paused(false);
1863	});
1864
1865	connect(m_controller.get(), &CoreController::stateLoaded, m_display.get(), &Display::resizeContext);
1866	connect(m_controller.get(), &CoreController::stateLoaded, m_display.get(), &Display::forceDraw);
1867	connect(m_controller.get(), &CoreController::rewound, m_display.get(), &Display::forceDraw);
1868	connect(m_controller.get(), &CoreController::paused, m_display.get(), &Display::pauseDrawing);
1869	connect(m_controller.get(), &CoreController::unpaused, m_display.get(), &Display::unpauseDrawing);
1870	connect(m_controller.get(), &CoreController::frameAvailable, m_display.get(), &Display::framePosted);
1871	connect(m_controller.get(), &CoreController::statusPosted, m_display.get(), &Display::showMessage);
1872	connect(m_controller.get(), &CoreController::didReset, m_display.get(), &Display::resizeContext);
1873
1874	connect(m_controller.get(), &CoreController::unpaused, &m_inputController, &InputController::suspendScreensaver);
1875	connect(m_controller.get(), &CoreController::frameAvailable, this, &Window::recordFrame);
1876	connect(m_controller.get(), &CoreController::crashed, this, &Window::gameCrashed);
1877	connect(m_controller.get(), &CoreController::failed, this, &Window::gameFailed);
1878	connect(m_controller.get(), &CoreController::unimplementedBiosCall, this, &Window::unimplementedBiosCall);
1879
1880#ifdef USE_GDB_STUB
1881	if (m_gdbController) {
1882		m_gdbController->setController(m_controller);
1883	}
1884#endif
1885
1886#ifdef USE_DEBUGGERS
1887	if (m_console) {
1888		m_console->setController(m_controller);
1889	}
1890#endif
1891
1892#ifdef USE_FFMPEG
1893	if (m_gifView) {
1894		m_gifView->setController(m_controller);
1895	}
1896
1897	if (m_videoView) {
1898		m_videoView->setController(m_controller);
1899	}
1900#endif
1901
1902	if (m_sensorView) {
1903		m_sensorView->setController(m_controller);
1904	}
1905
1906	if (m_overrideView) {
1907		m_overrideView->setController(m_controller);
1908	}
1909
1910	if (!m_pendingPatch.isEmpty()) {
1911		m_controller->loadPatch(m_pendingPatch);
1912		m_pendingPatch = QString();
1913	}
1914
1915	m_controller->loadConfig(m_config);
1916	m_controller->start();
1917
1918	if (!m_pendingState.isEmpty()) {
1919		m_controller->loadState(m_pendingState);
1920		m_pendingState = QString();
1921	}
1922
1923	if (m_pendingPause) {
1924		m_controller->setPaused(true);
1925		m_pendingPause = false;
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::filter(bool filter) {
1963	m_filter = filter;
1964}
1965
1966void WindowBackground::paintEvent(QPaintEvent* event) {
1967	QWidget::paintEvent(event);
1968	const QPixmap& logo = pixmap();
1969	QPainter painter(this);
1970	painter.setRenderHint(QPainter::SmoothPixmapTransform, m_filter);
1971	painter.fillRect(QRect(QPoint(), size()), Qt::black);
1972	QSize s = size();
1973	QSize ds = s;
1974	if (m_lockAspectRatio) {
1975		if (ds.width() * m_aspectHeight > ds.height() * m_aspectWidth) {
1976			ds.setWidth(ds.height() * m_aspectWidth / m_aspectHeight);
1977		} else if (ds.width() * m_aspectHeight < ds.height() * m_aspectWidth) {
1978			ds.setHeight(ds.width() * m_aspectHeight / m_aspectWidth);
1979		}
1980	}
1981	if (m_lockIntegerScaling) {
1982		if (ds.width() >= m_aspectWidth) {
1983			ds.setWidth(ds.width() - ds.width() % m_aspectWidth);
1984		}
1985		if (ds.height() >= m_aspectHeight) {
1986			ds.setHeight(ds.height() - ds.height() % m_aspectHeight);
1987		}
1988	}
1989	QPoint origin = QPoint((s.width() - ds.width()) / 2, (s.height() - ds.height()) / 2);
1990	QRect full(origin, ds);
1991	painter.drawPixmap(full, logo);
1992}