all repos — mgba @ a32cb5cc5e4fa0f1590725036ca58a490d0f1164

mGBA Game Boy Advance Emulator

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

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