all repos — mgba @ 8c8361477d8bd34d905368a3b76952aef65ff70d

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