all repos — mgba @ c665f939e72d227189fd8064a1899f3724099147

mGBA Game Boy Advance Emulator

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

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