all repos — mgba @ 9b2e5a5541870e92c1b8cb235fd57d88a74b58dc

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