all repos — mgba @ 567e473f7c7914f444e9df194bb469d3aef3e04a

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