all repos — mgba @ 9f3c68cb6ab310343e736b17e4b2f230c5e272e2

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