all repos — mgba @ 43e2a6ab5d32d1a1165bc37699bcf9dfc6e1992e

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