all repos — mgba @ 8c68d867e61f6227dad735390444ff8e41510f4f

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