all repos — mgba @ c6f0d6c5dbb9c77047439fdea8f7b2e28e207428

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