all repos — mgba @ 763eccd69a740c62ae283c7f7adfa0f532dfb34a

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