all repos — mgba @ 1fd8b1b299e785ee75df6ec45bfb6a8d434af684

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