all repos — mgba @ 2c59cb8211c4bf46665d12ed174cf7efe512e0d0

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