all repos — mgba @ c7a147598167b237530dedd924443f3144501cbe

mGBA Game Boy Advance Emulator

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

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