all repos — mgba @ 17e5b6a4553bd459ee5295585adb295cb72d65d8

mGBA Game Boy Advance Emulator

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

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