all repos — mgba @ e7226e76496ca7920daa5ea318a44ee4eb9d1378

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