all repos — mgba @ bb37a60765fafdce9db1aeb0f70f951c29522777

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