all repos — mgba @ c6ce7b0bb6cb1582e0dc94fd2a732f9b356868df

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