all repos — mgba @ adb3dd5270f77d794441a0b3f93256735951e71b

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