all repos — mgba @ 29b2262e9a13ccc681e3ef74a18073571810125f

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