all repos — mgba @ b89b3b6d138383d235729f728149eaf3f69f01eb

mGBA Game Boy Advance Emulator

src/platform/qt/Window.cpp (view raw)

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