all repos — mgba @ 87d4dad893d5df04fac5575c12a1c7b82fc07a7b

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#ifdef M_CORE_GBA
 694	foreach (QAction* action, m_gbaActions) {
 695		action->setDisabled(context->core->platform(context->core) != PLATFORM_GBA);
 696	}
 697#endif
 698	multiplayerChanged();
 699	if (!fname.isEmpty()) {
 700		setWindowFilePath(fname);
 701		appendMRU(fname);
 702	}
 703	updateTitle();
 704	unsigned width, height;
 705	context->core->desiredVideoDimensions(context->core, &width, &height);
 706	m_display->setMinimumSize(width, height);
 707	attachWidget(m_display);
 708
 709#ifndef Q_OS_MAC
 710	if (isFullScreen()) {
 711		menuBar()->hide();
 712	}
 713#endif
 714
 715	m_hitUnimplementedBiosCall = false;
 716	m_fpsTimer.start();
 717	m_focusCheck.start();
 718}
 719
 720void Window::gameStopped() {
 721#ifdef M_CORE_GBA
 722	foreach (QAction* action, m_gbaActions) {
 723		action->setDisabled(false);
 724	}
 725#endif
 726	foreach (QAction* action, m_gameActions) {
 727		action->setDisabled(true);
 728	}
 729	setWindowFilePath(QString());
 730	updateTitle();
 731	detachWidget(m_display);
 732	m_screenWidget->setLockAspectRatio(m_logo.width(), m_logo.height());
 733	m_screenWidget->setPixmap(m_logo);
 734	m_screenWidget->unsetCursor();
 735
 736	m_fpsTimer.stop();
 737	m_focusCheck.stop();
 738}
 739
 740void Window::gameCrashed(const QString& errorMessage) {
 741	QMessageBox* crash = new QMessageBox(QMessageBox::Critical, tr("Crash"),
 742	                                     tr("The game has crashed with the following error:\n\n%1").arg(errorMessage),
 743	                                     QMessageBox::Ok, this, Qt::Sheet);
 744	crash->setAttribute(Qt::WA_DeleteOnClose);
 745	crash->show();
 746}
 747
 748void Window::gameFailed() {
 749	QMessageBox* fail = new QMessageBox(QMessageBox::Warning, tr("Couldn't Load"),
 750	                                    tr("Could not load game. Are you sure it's in the correct format?"),
 751	                                    QMessageBox::Ok, this, Qt::Sheet);
 752	fail->setAttribute(Qt::WA_DeleteOnClose);
 753	fail->show();
 754}
 755
 756void Window::unimplementedBiosCall(int call) {
 757	if (m_hitUnimplementedBiosCall) {
 758		return;
 759	}
 760	m_hitUnimplementedBiosCall = true;
 761
 762	QMessageBox* fail = new QMessageBox(
 763	    QMessageBox::Warning, tr("Unimplemented BIOS call"),
 764	    tr("This game uses a BIOS call that is not implemented. Please use the official BIOS for best experience."),
 765	    QMessageBox::Ok, this, Qt::Sheet);
 766	fail->setAttribute(Qt::WA_DeleteOnClose);
 767	fail->show();
 768}
 769
 770void Window::tryMakePortable() {
 771	QMessageBox* confirm = new QMessageBox(QMessageBox::Question, tr("Really make portable?"),
 772	                                       tr("This will make the emulator load its configuration from the same directory as the executable. Do you want to continue?"),
 773	                                       QMessageBox::Yes | QMessageBox::Cancel, this, Qt::Sheet);
 774	confirm->setAttribute(Qt::WA_DeleteOnClose);
 775	connect(confirm->button(QMessageBox::Yes), SIGNAL(clicked()), m_config, SLOT(makePortable()));
 776	confirm->show();
 777}
 778
 779void Window::mustRestart() {
 780	QMessageBox* dialog = new QMessageBox(QMessageBox::Warning, tr("Restart needed"),
 781	                                      tr("Some changes will not take effect until the emulator is restarted."),
 782	                                      QMessageBox::Ok, this, Qt::Sheet);
 783	dialog->setAttribute(Qt::WA_DeleteOnClose);
 784	dialog->show();
 785}
 786
 787void Window::recordFrame() {
 788	m_frameList.append(QDateTime::currentDateTime());
 789	while (m_frameList.count() > FRAME_LIST_SIZE) {
 790		m_frameList.removeFirst();
 791	}
 792}
 793
 794void Window::showFPS() {
 795	if (m_frameList.isEmpty()) {
 796		updateTitle();
 797		return;
 798	}
 799	qint64 interval = m_frameList.first().msecsTo(m_frameList.last());
 800	float fps = (m_frameList.count() - 1) * 10000.f / interval;
 801	fps = round(fps) / 10.f;
 802	updateTitle(fps);
 803}
 804
 805void Window::updateTitle(float fps) {
 806	QString title;
 807
 808	m_controller->threadInterrupt();
 809	if (m_controller->isLoaded()) {
 810		const NoIntroDB* db = GBAApp::app()->gameDB();
 811		NoIntroGame game{};
 812		uint32_t crc32 = 0;
 813
 814		switch (m_controller->thread()->core->platform(m_controller->thread()->core)) {
 815	#ifdef M_CORE_GBA
 816		case PLATFORM_GBA: {
 817			GBA* gba = static_cast<GBA*>(m_controller->thread()->core->board);
 818			crc32 = gba->romCrc32;
 819			break;
 820		}
 821	#endif
 822	#ifdef M_CORE_GB
 823		case PLATFORM_GB: {
 824			GB* gb = static_cast<GB*>(m_controller->thread()->core->board);
 825			crc32 = gb->romCrc32;
 826			break;
 827		}
 828	#endif
 829		default:
 830			break;
 831		}
 832
 833		if (db && crc32) {
 834			NoIntroDBLookupGameByCRC(db, crc32, &game);
 835			title = QLatin1String(game.name);
 836		} else {
 837			char gameTitle[17] = { '\0' };
 838			mCore* core = m_controller->thread()->core;
 839			core->getGameTitle(core, gameTitle);
 840			title = gameTitle;
 841		}
 842	}
 843	MultiplayerController* multiplayer = m_controller->multiplayerController();
 844	if (multiplayer && multiplayer->attached() > 1) {
 845		title += tr(" -  Player %1 of %2").arg(m_playerId + 1).arg(multiplayer->attached());
 846	}
 847	m_controller->threadContinue();
 848	if (title.isNull()) {
 849		setWindowTitle(tr("%1 - %2").arg(projectName).arg(projectVersion));
 850	} else if (fps < 0) {
 851		setWindowTitle(tr("%1 - %2 - %3").arg(projectName).arg(title).arg(projectVersion));
 852	} else {
 853		setWindowTitle(tr("%1 - %2 (%3 fps) - %4").arg(projectName).arg(title).arg(fps).arg(projectVersion));
 854	}
 855}
 856
 857void Window::openStateWindow(LoadSave ls) {
 858	if (m_stateWindow) {
 859		return;
 860	}
 861	MultiplayerController* multiplayer = m_controller->multiplayerController();
 862	if (multiplayer && multiplayer->attached() > 1) {
 863		return;
 864	}
 865	bool wasPaused = m_controller->isPaused();
 866	m_stateWindow = new LoadSaveState(m_controller);
 867	connect(this, SIGNAL(shutdown()), m_stateWindow, SLOT(close()));
 868	connect(m_controller, SIGNAL(gameStopped(mCoreThread*)), m_stateWindow, SLOT(close()));
 869	connect(m_stateWindow, &LoadSaveState::closed, [this]() {
 870		detachWidget(m_stateWindow);
 871		m_stateWindow = nullptr;
 872		QMetaObject::invokeMethod(this, "setFocus", Qt::QueuedConnection);
 873	});
 874	if (!wasPaused) {
 875		m_controller->setPaused(true);
 876		connect(m_stateWindow, &LoadSaveState::closed, [this]() { m_controller->setPaused(false); });
 877	}
 878	m_stateWindow->setAttribute(Qt::WA_DeleteOnClose);
 879	m_stateWindow->setMode(ls);
 880	attachWidget(m_stateWindow);
 881}
 882
 883void Window::setupMenu(QMenuBar* menubar) {
 884	menubar->clear();
 885	QMenu* fileMenu = menubar->addMenu(tr("&File"));
 886	m_shortcutController->addMenu(fileMenu);
 887	installEventFilter(m_shortcutController);
 888	addControlledAction(fileMenu, fileMenu->addAction(tr("Load &ROM..."), this, SLOT(selectROM()), QKeySequence::Open),
 889	                    "loadROM");
 890	addControlledAction(fileMenu, fileMenu->addAction(tr("Load ROM in archive..."), this, SLOT(selectROMInArchive())),
 891	                    "loadROMInArchive");
 892
 893	addControlledAction(fileMenu, fileMenu->addAction(tr("Load &BIOS..."), this, SLOT(selectBIOS())), "loadBIOS");
 894
 895	QAction* loadTemporarySave = new QAction(tr("Load temporary save..."), fileMenu);
 896	connect(loadTemporarySave, &QAction::triggered, [this]() { this->selectSave(true); });
 897	m_gameActions.append(loadTemporarySave);
 898	addControlledAction(fileMenu, loadTemporarySave, "loadTemporarySave");
 899
 900	addControlledAction(fileMenu, fileMenu->addAction(tr("Load &patch..."), this, SLOT(selectPatch())), "loadPatch");
 901	addControlledAction(fileMenu, fileMenu->addAction(tr("Boot BIOS"), m_controller, SLOT(bootBIOS())), "bootBIOS");
 902
 903	addControlledAction(fileMenu, fileMenu->addAction(tr("Replace ROM..."), this, SLOT(replaceROM())), "replaceROM");
 904
 905	QAction* romInfo = new QAction(tr("ROM &info..."), fileMenu);
 906	connect(romInfo, SIGNAL(triggered()), this, SLOT(openROMInfo()));
 907	m_gameActions.append(romInfo);
 908	addControlledAction(fileMenu, romInfo, "romInfo");
 909
 910	m_mruMenu = fileMenu->addMenu(tr("Recent"));
 911
 912	fileMenu->addSeparator();
 913
 914	addControlledAction(fileMenu, fileMenu->addAction(tr("Make portable"), this, SLOT(tryMakePortable())), "makePortable");
 915
 916	fileMenu->addSeparator();
 917
 918	QAction* loadState = new QAction(tr("&Load state"), fileMenu);
 919	loadState->setShortcut(tr("F10"));
 920	connect(loadState, &QAction::triggered, [this]() { this->openStateWindow(LoadSave::LOAD); });
 921	m_gameActions.append(loadState);
 922	m_nonMpActions.append(loadState);
 923	addControlledAction(fileMenu, loadState, "loadState");
 924
 925	QAction* saveState = new QAction(tr("&Save state"), fileMenu);
 926	saveState->setShortcut(tr("Shift+F10"));
 927	connect(saveState, &QAction::triggered, [this]() { this->openStateWindow(LoadSave::SAVE); });
 928	m_gameActions.append(saveState);
 929	m_nonMpActions.append(saveState);
 930	addControlledAction(fileMenu, saveState, "saveState");
 931
 932	QMenu* quickLoadMenu = fileMenu->addMenu(tr("Quick load"));
 933	QMenu* quickSaveMenu = fileMenu->addMenu(tr("Quick save"));
 934	m_shortcutController->addMenu(quickLoadMenu);
 935	m_shortcutController->addMenu(quickSaveMenu);
 936
 937	QAction* quickLoad = new QAction(tr("Load recent"), quickLoadMenu);
 938	connect(quickLoad, SIGNAL(triggered()), m_controller, SLOT(loadState()));
 939	m_gameActions.append(quickLoad);
 940	m_nonMpActions.append(quickLoad);
 941	addControlledAction(quickLoadMenu, quickLoad, "quickLoad");
 942
 943	QAction* quickSave = new QAction(tr("Save recent"), quickSaveMenu);
 944	connect(quickSave, SIGNAL(triggered()), m_controller, SLOT(saveState()));
 945	m_gameActions.append(quickSave);
 946	m_nonMpActions.append(quickSave);
 947	addControlledAction(quickSaveMenu, quickSave, "quickSave");
 948
 949	quickLoadMenu->addSeparator();
 950	quickSaveMenu->addSeparator();
 951
 952	QAction* undoLoadState = new QAction(tr("Undo load state"), quickLoadMenu);
 953	undoLoadState->setShortcut(tr("F11"));
 954	connect(undoLoadState, SIGNAL(triggered()), m_controller, SLOT(loadBackupState()));
 955	m_gameActions.append(undoLoadState);
 956	m_nonMpActions.append(undoLoadState);
 957	addControlledAction(quickLoadMenu, undoLoadState, "undoLoadState");
 958
 959	QAction* undoSaveState = new QAction(tr("Undo save state"), quickSaveMenu);
 960	undoSaveState->setShortcut(tr("Shift+F11"));
 961	connect(undoSaveState, SIGNAL(triggered()), m_controller, SLOT(saveBackupState()));
 962	m_gameActions.append(undoSaveState);
 963	m_nonMpActions.append(undoSaveState);
 964	addControlledAction(quickSaveMenu, undoSaveState, "undoSaveState");
 965
 966	quickLoadMenu->addSeparator();
 967	quickSaveMenu->addSeparator();
 968
 969	int i;
 970	for (i = 1; i < 10; ++i) {
 971		quickLoad = new QAction(tr("State &%1").arg(i), quickLoadMenu);
 972		quickLoad->setShortcut(tr("F%1").arg(i));
 973		connect(quickLoad, &QAction::triggered, [this, i]() { m_controller->loadState(i); });
 974		m_gameActions.append(quickLoad);
 975		m_nonMpActions.append(quickLoad);
 976		addControlledAction(quickLoadMenu, quickLoad, QString("quickLoad.%1").arg(i));
 977
 978		quickSave = new QAction(tr("State &%1").arg(i), quickSaveMenu);
 979		quickSave->setShortcut(tr("Shift+F%1").arg(i));
 980		connect(quickSave, &QAction::triggered, [this, i]() { m_controller->saveState(i); });
 981		m_gameActions.append(quickSave);
 982		m_nonMpActions.append(quickSave);
 983		addControlledAction(quickSaveMenu, quickSave, QString("quickSave.%1").arg(i));
 984	}
 985
 986#ifdef M_CORE_GBA
 987	fileMenu->addSeparator();
 988	QAction* importShark = new QAction(tr("Import GameShark Save"), fileMenu);
 989	connect(importShark, SIGNAL(triggered()), this, SLOT(importSharkport()));
 990	m_gameActions.append(importShark);
 991	m_gbaActions.append(importShark);
 992	addControlledAction(fileMenu, importShark, "importShark");
 993
 994	QAction* exportShark = new QAction(tr("Export GameShark Save"), fileMenu);
 995	connect(exportShark, SIGNAL(triggered()), this, SLOT(exportSharkport()));
 996	m_gameActions.append(exportShark);
 997	m_gbaActions.append(exportShark);
 998	addControlledAction(fileMenu, exportShark, "exportShark");
 999#endif
1000
1001	fileMenu->addSeparator();
1002	QAction* multiWindow = new QAction(tr("New multiplayer window"), fileMenu);
1003	connect(multiWindow, &QAction::triggered, [this]() {
1004		GBAApp::app()->newWindow();
1005	});
1006	addControlledAction(fileMenu, multiWindow, "multiWindow");
1007
1008#ifndef Q_OS_MAC
1009	fileMenu->addSeparator();
1010#endif
1011
1012	QAction* about = new QAction(tr("About"), fileMenu);
1013	connect(about, SIGNAL(triggered()), this, SLOT(openAboutScreen()));
1014	fileMenu->addAction(about);
1015
1016#ifndef Q_OS_MAC
1017	addControlledAction(fileMenu, fileMenu->addAction(tr("E&xit"), this, SLOT(close()), QKeySequence::Quit), "quit");
1018#endif
1019
1020	QMenu* emulationMenu = menubar->addMenu(tr("&Emulation"));
1021	m_shortcutController->addMenu(emulationMenu);
1022	QAction* reset = new QAction(tr("&Reset"), emulationMenu);
1023	reset->setShortcut(tr("Ctrl+R"));
1024	connect(reset, SIGNAL(triggered()), m_controller, SLOT(reset()));
1025	m_gameActions.append(reset);
1026	addControlledAction(emulationMenu, reset, "reset");
1027
1028	QAction* shutdown = new QAction(tr("Sh&utdown"), emulationMenu);
1029	connect(shutdown, SIGNAL(triggered()), m_controller, SLOT(closeGame()));
1030	m_gameActions.append(shutdown);
1031	addControlledAction(emulationMenu, shutdown, "shutdown");
1032
1033#ifdef M_CORE_GBA
1034	QAction* yank = new QAction(tr("Yank game pak"), emulationMenu);
1035	connect(yank, SIGNAL(triggered()), m_controller, SLOT(yankPak()));
1036	m_gameActions.append(yank);
1037	m_gbaActions.append(yank);
1038	addControlledAction(emulationMenu, yank, "yank");
1039#endif
1040	emulationMenu->addSeparator();
1041
1042	QAction* pause = new QAction(tr("&Pause"), emulationMenu);
1043	pause->setChecked(false);
1044	pause->setCheckable(true);
1045	pause->setShortcut(tr("Ctrl+P"));
1046	connect(pause, SIGNAL(triggered(bool)), m_controller, SLOT(setPaused(bool)));
1047	connect(m_controller, &GameController::gamePaused, [this, pause]() {
1048		pause->setChecked(true);
1049	});
1050	connect(m_controller, &GameController::gameUnpaused, [pause]() { pause->setChecked(false); });
1051	m_gameActions.append(pause);
1052	addControlledAction(emulationMenu, pause, "pause");
1053
1054	QAction* frameAdvance = new QAction(tr("&Next frame"), emulationMenu);
1055	frameAdvance->setShortcut(tr("Ctrl+N"));
1056	connect(frameAdvance, SIGNAL(triggered()), m_controller, SLOT(frameAdvance()));
1057	m_gameActions.append(frameAdvance);
1058	m_nonMpActions.append(frameAdvance);
1059	addControlledAction(emulationMenu, frameAdvance, "frameAdvance");
1060
1061	emulationMenu->addSeparator();
1062
1063	m_shortcutController->addFunctions(emulationMenu, [this]() {
1064		m_controller->setTurbo(true, false);
1065	}, [this]() {
1066		m_controller->setTurbo(false, false);
1067	}, QKeySequence(Qt::Key_Tab), tr("Fast forward (held)"), "holdFastForward");
1068
1069	QAction* turbo = new QAction(tr("&Fast forward"), emulationMenu);
1070	turbo->setCheckable(true);
1071	turbo->setChecked(false);
1072	turbo->setShortcut(tr("Shift+Tab"));
1073	connect(turbo, SIGNAL(triggered(bool)), m_controller, SLOT(setTurbo(bool)));
1074	addControlledAction(emulationMenu, turbo, "fastForward");
1075
1076	QMenu* ffspeedMenu = emulationMenu->addMenu(tr("Fast forward speed"));
1077	ConfigOption* ffspeed = m_config->addOption("fastForwardRatio");
1078	ffspeed->connect([this](const QVariant& value) {
1079		m_controller->setTurboSpeed(value.toFloat());
1080	}, this);
1081	ffspeed->addValue(tr("Unbounded"), -1.0f, ffspeedMenu);
1082	ffspeed->setValue(QVariant(-1.0f));
1083	ffspeedMenu->addSeparator();
1084	for (i = 2; i < 11; ++i) {
1085		ffspeed->addValue(tr("%0x").arg(i), i, ffspeedMenu);
1086	}
1087	m_config->updateOption("fastForwardRatio");
1088
1089	m_shortcutController->addFunctions(emulationMenu, [this]() {
1090		m_controller->startRewinding();
1091	}, [this]() {
1092		m_controller->stopRewinding();
1093	}, QKeySequence("~"), tr("Rewind (held)"), "holdRewind");
1094
1095	QAction* rewind = new QAction(tr("Re&wind"), emulationMenu);
1096	rewind->setShortcut(tr("`"));
1097	connect(rewind, SIGNAL(triggered()), m_controller, SLOT(rewind()));
1098	m_gameActions.append(rewind);
1099	m_nonMpActions.append(rewind);
1100	addControlledAction(emulationMenu, rewind, "rewind");
1101
1102	QAction* frameRewind = new QAction(tr("Step backwards"), emulationMenu);
1103	frameRewind->setShortcut(tr("Ctrl+B"));
1104	connect(frameRewind, &QAction::triggered, [this] () {
1105		m_controller->rewind(1);
1106	});
1107	m_gameActions.append(frameRewind);
1108	m_nonMpActions.append(frameRewind);
1109	addControlledAction(emulationMenu, frameRewind, "frameRewind");
1110
1111	ConfigOption* videoSync = m_config->addOption("videoSync");
1112	videoSync->addBoolean(tr("Sync to &video"), emulationMenu);
1113	videoSync->connect([this](const QVariant& value) {
1114		reloadConfig();
1115	}, this);
1116	m_config->updateOption("videoSync");
1117
1118	ConfigOption* audioSync = m_config->addOption("audioSync");
1119	audioSync->addBoolean(tr("Sync to &audio"), emulationMenu);
1120	audioSync->connect([this](const QVariant& value) {
1121		reloadConfig();
1122	}, this);
1123	m_config->updateOption("audioSync");
1124
1125	emulationMenu->addSeparator();
1126
1127	QMenu* solarMenu = emulationMenu->addMenu(tr("Solar sensor"));
1128	m_shortcutController->addMenu(solarMenu);
1129	QAction* solarIncrease = new QAction(tr("Increase solar level"), solarMenu);
1130	connect(solarIncrease, SIGNAL(triggered()), m_controller, SLOT(increaseLuminanceLevel()));
1131	addControlledAction(solarMenu, solarIncrease, "increaseLuminanceLevel");
1132
1133	QAction* solarDecrease = new QAction(tr("Decrease solar level"), solarMenu);
1134	connect(solarDecrease, SIGNAL(triggered()), m_controller, SLOT(decreaseLuminanceLevel()));
1135	addControlledAction(solarMenu, solarDecrease, "decreaseLuminanceLevel");
1136
1137	QAction* maxSolar = new QAction(tr("Brightest solar level"), solarMenu);
1138	connect(maxSolar, &QAction::triggered, [this]() { m_controller->setLuminanceLevel(10); });
1139	addControlledAction(solarMenu, maxSolar, "maxLuminanceLevel");
1140
1141	QAction* minSolar = new QAction(tr("Darkest solar level"), solarMenu);
1142	connect(minSolar, &QAction::triggered, [this]() { m_controller->setLuminanceLevel(0); });
1143	addControlledAction(solarMenu, minSolar, "minLuminanceLevel");
1144
1145	solarMenu->addSeparator();
1146	for (int i = 0; i <= 10; ++i) {
1147		QAction* setSolar = new QAction(tr("Brightness %1").arg(QString::number(i)), solarMenu);
1148		connect(setSolar, &QAction::triggered, [this, i]() {
1149			m_controller->setLuminanceLevel(i);
1150		});
1151		addControlledAction(solarMenu, setSolar, QString("luminanceLevel.%1").arg(QString::number(i)));
1152	}
1153
1154	QMenu* avMenu = menubar->addMenu(tr("Audio/&Video"));
1155	m_shortcutController->addMenu(avMenu);
1156	QMenu* frameMenu = avMenu->addMenu(tr("Frame size"));
1157	m_shortcutController->addMenu(frameMenu, avMenu);
1158	for (int i = 1; i <= 6; ++i) {
1159		QAction* setSize = new QAction(tr("%1x").arg(QString::number(i)), avMenu);
1160		setSize->setCheckable(true);
1161		connect(setSize, &QAction::triggered, [this, i, setSize]() {
1162			showNormal();
1163			QSize size(VIDEO_HORIZONTAL_PIXELS, VIDEO_VERTICAL_PIXELS);
1164			if (m_controller->isLoaded()) {
1165				size = m_controller->screenDimensions();
1166			}
1167			size *= i;
1168			resizeFrame(size);
1169			bool enableSignals = setSize->blockSignals(true);
1170			setSize->setChecked(true);
1171			setSize->blockSignals(enableSignals);
1172		});
1173		m_frameSizes[i] = setSize;
1174		addControlledAction(frameMenu, setSize, QString("frame%1x").arg(QString::number(i)));
1175	}
1176	QKeySequence fullscreenKeys;
1177#ifdef Q_OS_WIN
1178	fullscreenKeys = QKeySequence("Alt+Return");
1179#else
1180	fullscreenKeys = QKeySequence("Ctrl+F");
1181#endif
1182	addControlledAction(frameMenu, frameMenu->addAction(tr("Toggle fullscreen"), this, SLOT(toggleFullScreen()), fullscreenKeys), "fullscreen");
1183
1184	ConfigOption* lockAspectRatio = m_config->addOption("lockAspectRatio");
1185	lockAspectRatio->addBoolean(tr("Lock aspect ratio"), avMenu);
1186	lockAspectRatio->connect([this](const QVariant& value) {
1187		m_display->lockAspectRatio(value.toBool());
1188	}, this);
1189	m_config->updateOption("lockAspectRatio");
1190
1191	ConfigOption* resampleVideo = m_config->addOption("resampleVideo");
1192	resampleVideo->addBoolean(tr("Resample video"), avMenu);
1193	resampleVideo->connect([this](const QVariant& value) {
1194		m_display->filter(value.toBool());
1195	}, this);
1196	m_config->updateOption("resampleVideo");
1197
1198	QMenu* skipMenu = avMenu->addMenu(tr("Frame&skip"));
1199	ConfigOption* skip = m_config->addOption("frameskip");
1200	skip->connect([this](const QVariant& value) {
1201		reloadConfig();
1202	}, this);
1203	for (int i = 0; i <= 10; ++i) {
1204		skip->addValue(QString::number(i), i, skipMenu);
1205	}
1206	m_config->updateOption("frameskip");
1207
1208	QAction* shaderView = new QAction(tr("Shader options..."), avMenu);
1209	connect(shaderView, SIGNAL(triggered()), m_shaderView, SLOT(show()));
1210	if (!m_display->supportsShaders()) {
1211		shaderView->setEnabled(false);
1212	}
1213	addControlledAction(avMenu, shaderView, "shaderSelector");
1214
1215	avMenu->addSeparator();
1216
1217	ConfigOption* mute = m_config->addOption("mute");
1218	mute->addBoolean(tr("Mute"), avMenu);
1219	mute->connect([this](const QVariant& value) {
1220		reloadConfig();
1221	}, this);
1222	m_config->updateOption("mute");
1223
1224	QMenu* target = avMenu->addMenu(tr("FPS target"));
1225	ConfigOption* fpsTargetOption = m_config->addOption("fpsTarget");
1226	fpsTargetOption->connect([this](const QVariant& value) {
1227		emit fpsTargetChanged(value.toFloat());
1228	}, this);
1229	fpsTargetOption->addValue(tr("15"), 15, target);
1230	fpsTargetOption->addValue(tr("30"), 30, target);
1231	fpsTargetOption->addValue(tr("45"), 45, target);
1232	fpsTargetOption->addValue(tr("Native (59.7)"), float(GBA_ARM7TDMI_FREQUENCY) / float(VIDEO_TOTAL_LENGTH), target);
1233	fpsTargetOption->addValue(tr("60"), 60, target);
1234	fpsTargetOption->addValue(tr("90"), 90, target);
1235	fpsTargetOption->addValue(tr("120"), 120, target);
1236	fpsTargetOption->addValue(tr("240"), 240, target);
1237	m_config->updateOption("fpsTarget");
1238
1239#if defined(USE_PNG) || defined(USE_FFMPEG) || defined(USE_MAGICK)
1240	avMenu->addSeparator();
1241#endif
1242
1243#ifdef USE_PNG
1244	QAction* screenshot = new QAction(tr("Take &screenshot"), avMenu);
1245	screenshot->setShortcut(tr("F12"));
1246	connect(screenshot, SIGNAL(triggered()), m_controller, SLOT(screenshot()));
1247	m_gameActions.append(screenshot);
1248	addControlledAction(avMenu, screenshot, "screenshot");
1249#endif
1250
1251#ifdef USE_FFMPEG
1252	QAction* recordOutput = new QAction(tr("Record output..."), avMenu);
1253	connect(recordOutput, SIGNAL(triggered()), this, SLOT(openVideoWindow()));
1254	addControlledAction(avMenu, recordOutput, "recordOutput");
1255#endif
1256
1257#ifdef USE_MAGICK
1258	QAction* recordGIF = new QAction(tr("Record GIF..."), avMenu);
1259	connect(recordGIF, SIGNAL(triggered()), this, SLOT(openGIFWindow()));
1260	addControlledAction(avMenu, recordGIF, "recordGIF");
1261#endif
1262
1263	avMenu->addSeparator();
1264	QMenu* videoLayers = avMenu->addMenu(tr("Video layers"));
1265	m_shortcutController->addMenu(videoLayers, avMenu);
1266
1267	for (int i = 0; i < 4; ++i) {
1268		QAction* enableBg = new QAction(tr("Background %0").arg(i), videoLayers);
1269		enableBg->setCheckable(true);
1270		enableBg->setChecked(true);
1271		connect(enableBg, &QAction::triggered, [this, i](bool enable) { m_controller->setVideoLayerEnabled(i, enable); });
1272		addControlledAction(videoLayers, enableBg, QString("enableBG%0").arg(i));
1273	}
1274
1275	QAction* enableObj = new QAction(tr("OBJ (sprites)"), videoLayers);
1276	enableObj->setCheckable(true);
1277	enableObj->setChecked(true);
1278	connect(enableObj, &QAction::triggered, [this](bool enable) { m_controller->setVideoLayerEnabled(4, enable); });
1279	addControlledAction(videoLayers, enableObj, "enableOBJ");
1280
1281	QMenu* audioChannels = avMenu->addMenu(tr("Audio channels"));
1282	m_shortcutController->addMenu(audioChannels, avMenu);
1283
1284	for (int i = 0; i < 4; ++i) {
1285		QAction* enableCh = new QAction(tr("Channel %0").arg(i + 1), audioChannels);
1286		enableCh->setCheckable(true);
1287		enableCh->setChecked(true);
1288		connect(enableCh, &QAction::triggered, [this, i](bool enable) { m_controller->setAudioChannelEnabled(i, enable); });
1289		addControlledAction(audioChannels, enableCh, QString("enableCh%0").arg(i + 1));
1290	}
1291
1292	QAction* enableChA = new QAction(tr("Channel A"), audioChannels);
1293	enableChA->setCheckable(true);
1294	enableChA->setChecked(true);
1295	connect(enableChA, &QAction::triggered, [this, i](bool enable) { m_controller->setAudioChannelEnabled(4, enable); });
1296	addControlledAction(audioChannels, enableChA, QString("enableChA"));
1297
1298	QAction* enableChB = new QAction(tr("Channel B"), audioChannels);
1299	enableChB->setCheckable(true);
1300	enableChB->setChecked(true);
1301	connect(enableChB, &QAction::triggered, [this, i](bool enable) { m_controller->setAudioChannelEnabled(5, enable); });
1302	addControlledAction(audioChannels, enableChB, QString("enableChB"));
1303
1304	QMenu* toolsMenu = menubar->addMenu(tr("&Tools"));
1305	m_shortcutController->addMenu(toolsMenu);
1306	QAction* viewLogs = new QAction(tr("View &logs..."), toolsMenu);
1307	connect(viewLogs, SIGNAL(triggered()), m_logView, SLOT(show()));
1308	addControlledAction(toolsMenu, viewLogs, "viewLogs");
1309
1310#ifdef M_CORE_GBA
1311	QAction* overrides = new QAction(tr("Game &overrides..."), toolsMenu);
1312	connect(overrides, SIGNAL(triggered()), this, SLOT(openOverrideWindow()));
1313	m_gbaActions.append(overrides);
1314	addControlledAction(toolsMenu, overrides, "overrideWindow");
1315#endif
1316
1317	QAction* sensors = new QAction(tr("Game &Pak sensors..."), toolsMenu);
1318	connect(sensors, SIGNAL(triggered()), this, SLOT(openSensorWindow()));
1319	addControlledAction(toolsMenu, sensors, "sensorWindow");
1320
1321	QAction* cheats = new QAction(tr("&Cheats..."), toolsMenu);
1322	connect(cheats, SIGNAL(triggered()), this, SLOT(openCheatsWindow()));
1323	m_gameActions.append(cheats);
1324	addControlledAction(toolsMenu, cheats, "cheatsWindow");
1325
1326#ifdef USE_GDB_STUB
1327	QAction* gdbWindow = new QAction(tr("Start &GDB server..."), toolsMenu);
1328	connect(gdbWindow, SIGNAL(triggered()), this, SLOT(gdbOpen()));
1329	m_gbaActions.append(gdbWindow);
1330	addControlledAction(toolsMenu, gdbWindow, "gdbWindow");
1331#endif
1332
1333	toolsMenu->addSeparator();
1334	addControlledAction(toolsMenu, toolsMenu->addAction(tr("Settings..."), this, SLOT(openSettingsWindow())),
1335	                    "settings");
1336
1337	toolsMenu->addSeparator();
1338
1339	QAction* paletteView = new QAction(tr("View &palette..."), toolsMenu);
1340	connect(paletteView, SIGNAL(triggered()), this, SLOT(openPaletteWindow()));
1341	m_gameActions.append(paletteView);
1342	addControlledAction(toolsMenu, paletteView, "paletteWindow");
1343
1344#ifdef M_CORE_GBA
1345	QAction* tileView = new QAction(tr("View &tiles..."), toolsMenu);
1346	connect(tileView, SIGNAL(triggered()), this, SLOT(openTileWindow()));
1347	m_gameActions.append(tileView);
1348	m_gbaActions.append(tileView);
1349	addControlledAction(toolsMenu, tileView, "tileWindow");
1350#endif
1351
1352	QAction* memoryView = new QAction(tr("View memory..."), toolsMenu);
1353	connect(memoryView, SIGNAL(triggered()), this, SLOT(openMemoryWindow()));
1354	m_gameActions.append(memoryView);
1355	addControlledAction(toolsMenu, memoryView, "memoryView");
1356
1357#ifdef M_CORE_GBA
1358	QAction* ioViewer = new QAction(tr("View &I/O registers..."), toolsMenu);
1359	connect(ioViewer, SIGNAL(triggered()), this, SLOT(openIOViewer()));
1360	m_gameActions.append(ioViewer);
1361	m_gbaActions.append(ioViewer);
1362	addControlledAction(toolsMenu, ioViewer, "ioViewer");
1363#endif
1364
1365	ConfigOption* skipBios = m_config->addOption("skipBios");
1366	skipBios->connect([this](const QVariant& value) {
1367		reloadConfig();
1368	}, this);
1369
1370	ConfigOption* useBios = m_config->addOption("useBios");
1371	useBios->connect([this](const QVariant& value) {
1372		m_controller->setUseBIOS(value.toBool());
1373	}, this);
1374
1375	ConfigOption* buffers = m_config->addOption("audioBuffers");
1376	buffers->connect([this](const QVariant& value) {
1377		emit audioBufferSamplesChanged(value.toInt());
1378	}, this);
1379
1380	ConfigOption* sampleRate = m_config->addOption("sampleRate");
1381	sampleRate->connect([this](const QVariant& value) {
1382		emit sampleRateChanged(value.toUInt());
1383	}, this);
1384
1385	ConfigOption* volume = m_config->addOption("volume");
1386	volume->connect([this](const QVariant& value) {
1387		reloadConfig();
1388	}, this);
1389
1390	ConfigOption* rewindEnable = m_config->addOption("rewindEnable");
1391	rewindEnable->connect([this](const QVariant& value) {
1392		m_controller->setRewind(value.toBool(), m_config->getOption("rewindBufferCapacity").toInt());
1393	}, this);
1394
1395	ConfigOption* rewindBufferCapacity = m_config->addOption("rewindBufferCapacity");
1396	rewindBufferCapacity->connect([this](const QVariant& value) {
1397		m_controller->setRewind(m_config->getOption("rewindEnable").toInt(), value.toInt());
1398	}, this);
1399
1400	ConfigOption* allowOpposingDirections = m_config->addOption("allowOpposingDirections");
1401	allowOpposingDirections->connect([this](const QVariant& value) {
1402		m_inputController.setAllowOpposing(value.toBool());
1403	}, this);
1404
1405	ConfigOption* saveStateExtdata = m_config->addOption("saveStateExtdata");
1406	saveStateExtdata->connect([this](const QVariant& value) {
1407		m_controller->setSaveStateExtdata(value.toInt());
1408	}, this);
1409
1410	ConfigOption* loadStateExtdata = m_config->addOption("loadStateExtdata");
1411	loadStateExtdata->connect([this](const QVariant& value) {
1412		m_controller->setLoadStateExtdata(value.toInt());
1413	}, this);
1414
1415	QAction* exitFullScreen = new QAction(tr("Exit fullscreen"), frameMenu);
1416	connect(exitFullScreen, SIGNAL(triggered()), this, SLOT(exitFullScreen()));
1417	exitFullScreen->setShortcut(QKeySequence("Esc"));
1418	addHiddenAction(frameMenu, exitFullScreen, "exitFullScreen");
1419
1420	QMenu* autofireMenu = new QMenu(tr("Autofire"), this);
1421	m_shortcutController->addMenu(autofireMenu);
1422
1423	m_shortcutController->addFunctions(autofireMenu, [this]() {
1424		m_controller->setAutofire(GBA_KEY_A, true);
1425	}, [this]() {
1426		m_controller->setAutofire(GBA_KEY_A, false);
1427	}, QKeySequence(), tr("Autofire A"), "autofireA");
1428
1429	m_shortcutController->addFunctions(autofireMenu, [this]() {
1430		m_controller->setAutofire(GBA_KEY_B, true);
1431	}, [this]() {
1432		m_controller->setAutofire(GBA_KEY_B, false);
1433	}, QKeySequence(), tr("Autofire B"), "autofireB");
1434
1435	m_shortcutController->addFunctions(autofireMenu, [this]() {
1436		m_controller->setAutofire(GBA_KEY_L, true);
1437	}, [this]() {
1438		m_controller->setAutofire(GBA_KEY_L, false);
1439	}, QKeySequence(), tr("Autofire L"), "autofireL");
1440
1441	m_shortcutController->addFunctions(autofireMenu, [this]() {
1442		m_controller->setAutofire(GBA_KEY_R, true);
1443	}, [this]() {
1444		m_controller->setAutofire(GBA_KEY_R, false);
1445	}, QKeySequence(), tr("Autofire R"), "autofireR");
1446
1447	m_shortcutController->addFunctions(autofireMenu, [this]() {
1448		m_controller->setAutofire(GBA_KEY_START, true);
1449	}, [this]() {
1450		m_controller->setAutofire(GBA_KEY_START, false);
1451	}, QKeySequence(), tr("Autofire Start"), "autofireStart");
1452
1453	m_shortcutController->addFunctions(autofireMenu, [this]() {
1454		m_controller->setAutofire(GBA_KEY_SELECT, true);
1455	}, [this]() {
1456		m_controller->setAutofire(GBA_KEY_SELECT, false);
1457	}, QKeySequence(), tr("Autofire Select"), "autofireSelect");
1458
1459	m_shortcutController->addFunctions(autofireMenu, [this]() {
1460		m_controller->setAutofire(GBA_KEY_UP, true);
1461	}, [this]() {
1462		m_controller->setAutofire(GBA_KEY_UP, false);
1463	}, QKeySequence(), tr("Autofire Up"), "autofireUp");
1464
1465	m_shortcutController->addFunctions(autofireMenu, [this]() {
1466		m_controller->setAutofire(GBA_KEY_RIGHT, true);
1467	}, [this]() {
1468		m_controller->setAutofire(GBA_KEY_RIGHT, false);
1469	}, QKeySequence(), tr("Autofire Right"), "autofireRight");
1470
1471	m_shortcutController->addFunctions(autofireMenu, [this]() {
1472		m_controller->setAutofire(GBA_KEY_DOWN, true);
1473	}, [this]() {
1474		m_controller->setAutofire(GBA_KEY_DOWN, false);
1475	}, QKeySequence(), tr("Autofire Down"), "autofireDown");
1476
1477	m_shortcutController->addFunctions(autofireMenu, [this]() {
1478		m_controller->setAutofire(GBA_KEY_LEFT, true);
1479	}, [this]() {
1480		m_controller->setAutofire(GBA_KEY_LEFT, false);
1481	}, QKeySequence(), tr("Autofire Left"), "autofireLeft");
1482
1483	foreach (QAction* action, m_gameActions) {
1484		action->setDisabled(true);
1485	}
1486}
1487
1488void Window::attachWidget(QWidget* widget) {
1489	m_screenWidget->layout()->addWidget(widget);
1490	m_screenWidget->unsetCursor();
1491	static_cast<QStackedLayout*>(m_screenWidget->layout())->setCurrentWidget(widget);
1492}
1493
1494void Window::detachWidget(QWidget* widget) {
1495	m_screenWidget->layout()->removeWidget(widget);
1496}
1497
1498void Window::appendMRU(const QString& fname) {
1499	int index = m_mruFiles.indexOf(fname);
1500	if (index >= 0) {
1501		m_mruFiles.removeAt(index);
1502	}
1503	m_mruFiles.prepend(fname);
1504	while (m_mruFiles.size() > ConfigController::MRU_LIST_SIZE) {
1505		m_mruFiles.removeLast();
1506	}
1507	updateMRU();
1508}
1509
1510void Window::updateMRU() {
1511	if (!m_mruMenu) {
1512		return;
1513	}
1514	m_mruMenu->clear();
1515	int i = 0;
1516	for (const QString& file : m_mruFiles) {
1517		QAction* item = new QAction(file, m_mruMenu);
1518		item->setShortcut(QString("Ctrl+%1").arg(i));
1519		connect(item, &QAction::triggered, [this, file]() { m_controller->loadGame(file); });
1520		m_mruMenu->addAction(item);
1521		++i;
1522	}
1523	m_config->setMRU(m_mruFiles);
1524	m_config->write();
1525	m_mruMenu->setEnabled(i > 0);
1526}
1527
1528QAction* Window::addControlledAction(QMenu* menu, QAction* action, const QString& name) {
1529	addHiddenAction(menu, action, name);
1530	menu->addAction(action);
1531	return action;
1532}
1533
1534QAction* Window::addHiddenAction(QMenu* menu, QAction* action, const QString& name) {
1535	m_shortcutController->addAction(menu, action, name);
1536	action->setShortcutContext(Qt::WidgetShortcut);
1537	addAction(action);
1538	return action;
1539}
1540
1541void Window::focusCheck() {
1542	if (!m_config->getOption("pauseOnFocusLost").toInt()) {
1543		return;
1544	}
1545	if (QGuiApplication::focusWindow() && m_autoresume) {
1546		m_controller->setPaused(false);
1547		m_autoresume = false;
1548	} else if (!QGuiApplication::focusWindow() && !m_controller->isPaused()) {
1549		m_autoresume = true;
1550		m_controller->setPaused(true);
1551	}
1552}
1553
1554WindowBackground::WindowBackground(QWidget* parent)
1555	: QLabel(parent)
1556{
1557	setLayout(new QStackedLayout());
1558	layout()->setContentsMargins(0, 0, 0, 0);
1559	setAlignment(Qt::AlignCenter);
1560}
1561
1562void WindowBackground::setSizeHint(const QSize& hint) {
1563	m_sizeHint = hint;
1564}
1565
1566QSize WindowBackground::sizeHint() const {
1567	return m_sizeHint;
1568}
1569
1570void WindowBackground::setLockAspectRatio(int width, int height) {
1571	m_aspectWidth = width;
1572	m_aspectHeight = height;
1573}
1574
1575void WindowBackground::paintEvent(QPaintEvent*) {
1576	const QPixmap* logo = pixmap();
1577	if (!logo) {
1578		return;
1579	}
1580	QPainter painter(this);
1581	painter.setRenderHint(QPainter::SmoothPixmapTransform);
1582	painter.fillRect(QRect(QPoint(), size()), Qt::black);
1583	QSize s = size();
1584	QSize ds = s;
1585	if (ds.width() * m_aspectHeight > ds.height() * m_aspectWidth) {
1586		ds.setWidth(ds.height() * m_aspectWidth / m_aspectHeight);
1587	} else if (ds.width() * m_aspectHeight < ds.height() * m_aspectWidth) {
1588		ds.setHeight(ds.width() * m_aspectHeight / m_aspectWidth);
1589	}
1590	QPoint origin = QPoint((s.width() - ds.width()) / 2, (s.height() - ds.height()) / 2);
1591	QRect full(origin, ds);
1592	painter.drawPixmap(full, *logo);
1593}