all repos — mgba @ 4f43b574e2df578159a38a984ce715ac2060395d

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