all repos — mgba @ 91fd2c6b4768fbeb58c74d2f119e7d55685a9800

mGBA Game Boy Advance Emulator

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

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