all repos — mgba @ 205db2df90a06716acc2626095c6a53cb7cd38a9

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