all repos — mgba @ a5852c6e126d82915fb5da23d8d3c347ec9755d2

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