all repos — mgba @ 2823ee1e02cc833f1d6c89ea04029aea973167e1

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