all repos — mgba @ 40703d9734792e21096c120ddab2613465f71e7a

mGBA Game Boy Advance Emulator

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

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