all repos — mgba @ aaf1fef5ade790f1e57887e78ff92e5302c3d882

mGBA Game Boy Advance Emulator

src/platform/qt/Window.cpp (view raw)

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