all repos — mgba @ d708a1025d7b8246ae531828728114dad327e1ce

mGBA Game Boy Advance Emulator

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

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