all repos — mgba @ 306139a73c77131fd7d4d76bc3750ffd49717fd9

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