all repos — mgba @ c188e77b15daf35c2a4f0f85959119f8007c672f

mGBA Game Boy Advance Emulator

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

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