all repos — mgba @ acbd8a3688703772861241a9b87f08cf91a0f66d

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