all repos — mgba @ 7c8d253123733d667e271668f00bacceb390175d

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