all repos — mgba @ 2f33926f64495965135533e6ac865e8ef0ba174e

mGBA Game Boy Advance Emulator

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

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