all repos — mgba @ 1868ccaadd9e50ad929a72666956f6b01e2e219c

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