all repos — mgba @ 64b44efbf15168b03ee5f02ca03f55f519e4824f

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