all repos — mgba @ 12cf61f9fc0f3a38104d69bd61964d0099e136b3

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