all repos — mgba @ 981072a2991ad9e42261e74c1e94f16c238c2678

mGBA Game Boy Advance Emulator

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

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