all repos — mgba @ ae633d9c86f8a42051a135ffa9e17488936f1144

mGBA Game Boy Advance Emulator

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

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