all repos — mgba @ 8106c99c2ecd0bdc1d3afc25279f5c6d17511547

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