all repos — mgba @ 9de2189b2ef52ddb51dfde14befda9e4dff4e436

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