all repos — mgba @ c4b38790f211b65cb15af26cebe9fc25e3c19914

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