all repos — mgba @ 89d6770abdd1023a7a3e08bc745dfa50b5a61561

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