all repos — mgba @ 2f7d555f4995f3ef0801d8dda609a465cf196c75

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