all repos — mgba @ 5973433aa06cbe46e0262161aaefbc3df9ca1c63

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