all repos — mgba @ 03984ce0859bcd47118bf406cccc1333076e013d

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