all repos — mgba @ 4f1788b2e05744fbb6e5ee24af3d02e2ba2304ba

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	m_controller->setOverrides(m_config->overrides());
  83	updateTitle();
  84
  85	m_display = Display::create(this);
  86	m_shaderView = new ShaderSelector(m_display, m_config);
  87
  88	m_logo.setDevicePixelRatio(m_screenWidget->devicePixelRatio());
  89	m_logo = m_logo; // Free memory left over in old pixmap
  90
  91	m_screenWidget->setMinimumSize(m_display->minimumSize());
  92	m_screenWidget->setSizePolicy(m_display->sizePolicy());
  93	m_screenWidget->setSizeHint(m_display->minimumSize() * 2);
  94	m_screenWidget->setPixmap(m_logo);
  95	m_screenWidget->setLockAspectRatio(m_logo.width(), m_logo.height());
  96	setCentralWidget(m_screenWidget);
  97
  98	connect(m_controller, SIGNAL(gameStarted(GBAThread*)), this, SLOT(gameStarted(GBAThread*)));
  99	connect(m_controller, SIGNAL(gameStarted(GBAThread*)), &m_inputController, SLOT(suspendScreensaver()));
 100	connect(m_controller, SIGNAL(gameStopped(GBAThread*)), m_display, SLOT(stopDrawing()));
 101	connect(m_controller, SIGNAL(gameStopped(GBAThread*)), this, SLOT(gameStopped()));
 102	connect(m_controller, SIGNAL(gameStopped(GBAThread*)), &m_inputController, SLOT(resumeScreensaver()));
 103	connect(m_controller, SIGNAL(stateLoaded(GBAThread*)), m_display, SLOT(forceDraw()));
 104	connect(m_controller, SIGNAL(rewound(GBAThread*)), m_display, SLOT(forceDraw()));
 105	connect(m_controller, &GameController::gamePaused, [this]() {
 106		QImage currentImage(reinterpret_cast<const uchar*>(m_controller->drawContext()), VIDEO_HORIZONTAL_PIXELS,
 107		                    VIDEO_VERTICAL_PIXELS, VIDEO_HORIZONTAL_PIXELS * BYTES_PER_PIXEL, QImage::Format_RGBX8888);
 108		QPixmap pixmap;
 109		pixmap.convertFromImage(currentImage);
 110		m_screenWidget->setPixmap(pixmap);
 111		m_screenWidget->setLockAspectRatio(3, 2);
 112	});
 113	connect(m_controller, SIGNAL(gamePaused(GBAThread*)), m_display, SLOT(pauseDrawing()));
 114#ifndef Q_OS_MAC
 115	connect(m_controller, SIGNAL(gamePaused(GBAThread*)), menuBar(), SLOT(show()));
 116	connect(m_controller, &GameController::gameUnpaused, [this]() {
 117		if(isFullScreen()) {
 118			menuBar()->hide();
 119		}
 120	});
 121#endif
 122	connect(m_controller, SIGNAL(gamePaused(GBAThread*)), &m_inputController, SLOT(resumeScreensaver()));
 123	connect(m_controller, SIGNAL(gameUnpaused(GBAThread*)), m_display, SLOT(unpauseDrawing()));
 124	connect(m_controller, SIGNAL(gameUnpaused(GBAThread*)), &m_inputController, SLOT(suspendScreensaver()));
 125	connect(m_controller, SIGNAL(postLog(int, const QString&)), &m_log, SLOT(postLog(int, const QString&)));
 126	connect(m_controller, SIGNAL(frameAvailable(const uint32_t*)), this, SLOT(recordFrame()));
 127	connect(m_controller, SIGNAL(frameAvailable(const uint32_t*)), m_display, SLOT(framePosted(const uint32_t*)));
 128	connect(m_controller, SIGNAL(gameCrashed(const QString&)), this, SLOT(gameCrashed(const QString&)));
 129	connect(m_controller, SIGNAL(gameFailed()), this, SLOT(gameFailed()));
 130	connect(m_controller, SIGNAL(unimplementedBiosCall(int)), this, SLOT(unimplementedBiosCall(int)));
 131	connect(m_controller, SIGNAL(statusPosted(const QString&)), m_display, SLOT(showMessage(const QString&)));
 132	connect(&m_log, SIGNAL(levelsSet(int)), m_controller, SLOT(setLogLevel(int)));
 133	connect(&m_log, SIGNAL(levelsEnabled(int)), m_controller, SLOT(enableLogLevel(int)));
 134	connect(&m_log, SIGNAL(levelsDisabled(int)), m_controller, SLOT(disableLogLevel(int)));
 135	connect(this, SIGNAL(startDrawing(GBAThread*)), m_display, SLOT(startDrawing(GBAThread*)), Qt::QueuedConnection);
 136	connect(this, SIGNAL(shutdown()), m_display, SLOT(stopDrawing()));
 137	connect(this, SIGNAL(shutdown()), m_controller, SLOT(closeGame()));
 138	connect(this, SIGNAL(shutdown()), m_logView, SLOT(hide()));
 139	connect(this, SIGNAL(shutdown()), m_shaderView, SLOT(hide()));
 140	connect(this, SIGNAL(audioBufferSamplesChanged(int)), m_controller, SLOT(setAudioBufferSamples(int)));
 141	connect(this, SIGNAL(sampleRateChanged(unsigned)), m_controller, SLOT(setAudioSampleRate(unsigned)));
 142	connect(this, SIGNAL(fpsTargetChanged(float)), m_controller, SLOT(setFPSTarget(float)));
 143	connect(&m_fpsTimer, SIGNAL(timeout()), this, SLOT(showFPS()));
 144	connect(&m_focusCheck, SIGNAL(timeout()), this, SLOT(focusCheck()));
 145	connect(m_display, &Display::hideCursor, [this]() {
 146		if (static_cast<QStackedLayout*>(m_screenWidget->layout())->currentWidget() == m_display) {
 147			m_screenWidget->setCursor(Qt::BlankCursor);
 148		}
 149	});
 150	connect(m_display, &Display::showCursor, [this]() {
 151		m_screenWidget->unsetCursor();
 152	});
 153	connect(&m_inputController, SIGNAL(profileLoaded(const QString&)), m_shortcutController, SLOT(loadProfile(const QString&)));
 154
 155	m_log.setLevels(GBA_LOG_WARN | GBA_LOG_ERROR | GBA_LOG_FATAL | GBA_LOG_STATUS);
 156	m_fpsTimer.setInterval(FPS_TIMER_INTERVAL);
 157	m_focusCheck.setInterval(200);
 158
 159	m_shortcutController->setConfigController(m_config);
 160	setupMenu(menuBar());
 161}
 162
 163Window::~Window() {
 164	delete m_logView;
 165
 166#ifdef USE_FFMPEG
 167	delete m_videoView;
 168#endif
 169
 170#ifdef USE_MAGICK
 171	delete m_gifView;
 172#endif
 173}
 174
 175void Window::argumentsPassed(GBAArguments* args) {
 176	loadConfig();
 177
 178	if (args->patch) {
 179		m_controller->loadPatch(args->patch);
 180	}
 181
 182	if (args->fname) {
 183		m_controller->loadGame(args->fname);
 184	}
 185}
 186
 187void Window::resizeFrame(int width, int height) {
 188	QSize newSize(width, height);
 189	m_screenWidget->setSizeHint(newSize);
 190	newSize -= m_screenWidget->size();
 191	newSize += size();
 192	resize(newSize);
 193}
 194
 195void Window::setConfig(ConfigController* config) {
 196	m_config = config;
 197}
 198
 199void Window::loadConfig() {
 200	const GBAOptions* opts = m_config->options();
 201	reloadConfig();
 202
 203	// TODO: Move these to ConfigController
 204	if (opts->fpsTarget) {
 205		emit fpsTargetChanged(opts->fpsTarget);
 206	}
 207
 208	if (opts->audioBuffers) {
 209		emit audioBufferSamplesChanged(opts->audioBuffers);
 210	}
 211
 212	if (opts->sampleRate) {
 213		emit sampleRateChanged(opts->sampleRate);
 214	}
 215
 216	if (opts->width && opts->height) {
 217		resizeFrame(opts->width, opts->height);
 218	}
 219
 220	if (opts->fullscreen) {
 221		enterFullScreen();
 222	}
 223
 224	if (opts->shader) {
 225		struct VDir* shader = VDirOpen(opts->shader);
 226		if (shader) {
 227			m_display->setShaders(shader);
 228			m_shaderView->refreshShaders();
 229			shader->close(shader);
 230		}
 231	}
 232
 233	m_mruFiles = m_config->getMRU();
 234	updateMRU();
 235
 236	m_inputController.setConfiguration(m_config);
 237}
 238
 239void Window::reloadConfig() {
 240	const GBAOptions* opts = m_config->options();
 241
 242	m_log.setLevels(opts->logLevel);
 243
 244	QString saveStateExtdata = m_config->getOption("saveStateExtdata");
 245	bool ok;
 246	int flags = saveStateExtdata.toInt(&ok);
 247	if (ok) {
 248		m_controller->setSaveStateExtdata(flags);
 249	}
 250
 251	QString loadStateExtdata = m_config->getOption("loadStateExtdata");
 252	flags = loadStateExtdata.toInt(&ok);
 253	if (ok) {
 254		m_controller->setLoadStateExtdata(flags);
 255	}
 256
 257	m_controller->setOptions(opts);
 258	m_display->lockAspectRatio(opts->lockAspectRatio);
 259	m_display->filter(opts->resampleVideo);
 260
 261	if (opts->bios) {
 262		m_controller->loadBIOS(opts->bios);
 263	}
 264
 265	m_inputController.setScreensaverSuspendable(opts->suspendScreensaver);
 266}
 267
 268void Window::saveConfig() {
 269	m_inputController.saveConfiguration();
 270	m_config->write();
 271}
 272
 273void Window::selectROM() {
 274	QStringList formats{
 275		"*.gba",
 276#ifdef USE_LIBZIP
 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#ifdef USE_LIBZIP
 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(GBAAVStream*)), m_controller, SLOT(setAVStream(GBAAVStream*)));
 420		connect(m_videoView, SIGNAL(recordingStopped()), m_controller, SLOT(clearAVStream()), Qt::DirectConnection);
 421		connect(m_controller, SIGNAL(gameStopped(GBAThread*)), m_videoView, SLOT(stopRecording()));
 422		connect(m_controller, SIGNAL(gameStopped(GBAThread*)), 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(GBAAVStream*)), m_controller, SLOT(setAVStream(GBAAVStream*)));
 434		connect(m_gifView, SIGNAL(recordingStopped()), m_controller, SLOT(clearAVStream()), Qt::DirectConnection);
 435		connect(m_controller, SIGNAL(gameStopped(GBAThread*)), m_gifView, SLOT(stopRecording()));
 436		connect(m_controller, SIGNAL(gameStopped(GBAThread*)), 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(GBAThread* 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, m_controller->thread()->gba->romCrc32, &game)) {
 720			title = QLatin1String(game.name);
 721		} else {
 722			char gameTitle[13] = { '\0' };
 723			GBAGetGameTitle(m_controller->thread()->gba, gameTitle);
 724			title = gameTitle;
 725		}
 726	}
 727	MultiplayerController* multiplayer = m_controller->multiplayerController();
 728	if (multiplayer && multiplayer->attached() > 1) {
 729		title += tr(" -  Player %1 of %2").arg(m_playerId + 1).arg(multiplayer->attached());
 730	}
 731	m_controller->threadContinue();
 732	if (title.isNull()) {
 733		setWindowTitle(tr("%1 - %2").arg(projectName).arg(projectVersion));
 734	} else if (isnan(fps)) {
 735		setWindowTitle(tr("%1 - %2 - %3").arg(projectName).arg(title).arg(projectVersion));
 736	} else {
 737		setWindowTitle(tr("%1 - %2 (%3 fps) - %4").arg(projectName).arg(title).arg(fps).arg(projectVersion));
 738	}
 739}
 740
 741void Window::openStateWindow(LoadSave ls) {
 742	if (m_stateWindow) {
 743		return;
 744	}
 745	MultiplayerController* multiplayer = m_controller->multiplayerController();
 746	if (multiplayer && multiplayer->attached() > 1) {
 747		return;
 748	}
 749	bool wasPaused = m_controller->isPaused();
 750	m_stateWindow = new LoadSaveState(m_controller);
 751	connect(this, SIGNAL(shutdown()), m_stateWindow, SLOT(close()));
 752	connect(m_controller, SIGNAL(gameStopped(GBAThread*)), m_stateWindow, SLOT(close()));
 753	connect(m_stateWindow, &LoadSaveState::closed, [this]() {
 754		detachWidget(m_stateWindow);
 755		m_stateWindow = nullptr;
 756		QMetaObject::invokeMethod(this, "setFocus", Qt::QueuedConnection);
 757	});
 758	if (!wasPaused) {
 759		m_controller->setPaused(true);
 760		connect(m_stateWindow, &LoadSaveState::closed, [this]() { m_controller->setPaused(false); });
 761	}
 762	m_stateWindow->setAttribute(Qt::WA_DeleteOnClose);
 763	m_stateWindow->setMode(ls);
 764	attachWidget(m_stateWindow);
 765}
 766
 767void Window::setupMenu(QMenuBar* menubar) {
 768	menubar->clear();
 769	QMenu* fileMenu = menubar->addMenu(tr("&File"));
 770	m_shortcutController->addMenu(fileMenu);
 771	installEventFilter(m_shortcutController);
 772	addControlledAction(fileMenu, fileMenu->addAction(tr("Load &ROM..."), this, SLOT(selectROM()), QKeySequence::Open),
 773	                    "loadROM");
 774	addControlledAction(fileMenu, fileMenu->addAction(tr("Load &BIOS..."), this, SLOT(selectBIOS())), "loadBIOS");
 775	addControlledAction(fileMenu, fileMenu->addAction(tr("Load &patch..."), this, SLOT(selectPatch())), "loadPatch");
 776	addControlledAction(fileMenu, fileMenu->addAction(tr("Boot BIOS"), m_controller, SLOT(bootBIOS())), "bootBIOS");
 777
 778	addControlledAction(fileMenu, fileMenu->addAction(tr("Replace ROM..."), this, SLOT(replaceROM())), "replaceROM");
 779
 780	QAction* romInfo = new QAction(tr("ROM &info..."), fileMenu);
 781	connect(romInfo, SIGNAL(triggered()), this, SLOT(openROMInfo()));
 782	m_gameActions.append(romInfo);
 783	addControlledAction(fileMenu, romInfo, "romInfo");
 784
 785	m_mruMenu = fileMenu->addMenu(tr("Recent"));
 786
 787	fileMenu->addSeparator();
 788
 789	addControlledAction(fileMenu, fileMenu->addAction(tr("Make portable"), this, SLOT(tryMakePortable())), "makePortable");
 790
 791	fileMenu->addSeparator();
 792
 793	QAction* loadState = new QAction(tr("&Load state"), fileMenu);
 794	loadState->setShortcut(tr("F10"));
 795	connect(loadState, &QAction::triggered, [this]() { this->openStateWindow(LoadSave::LOAD); });
 796	m_gameActions.append(loadState);
 797	m_nonMpActions.append(loadState);
 798	addControlledAction(fileMenu, loadState, "loadState");
 799
 800	QAction* saveState = new QAction(tr("&Save state"), fileMenu);
 801	saveState->setShortcut(tr("Shift+F10"));
 802	connect(saveState, &QAction::triggered, [this]() { this->openStateWindow(LoadSave::SAVE); });
 803	m_gameActions.append(saveState);
 804	m_nonMpActions.append(saveState);
 805	addControlledAction(fileMenu, saveState, "saveState");
 806
 807	QMenu* quickLoadMenu = fileMenu->addMenu(tr("Quick load"));
 808	QMenu* quickSaveMenu = fileMenu->addMenu(tr("Quick save"));
 809	m_shortcutController->addMenu(quickLoadMenu);
 810	m_shortcutController->addMenu(quickSaveMenu);
 811
 812	QAction* quickLoad = new QAction(tr("Load recent"), quickLoadMenu);
 813	connect(quickLoad, SIGNAL(triggered()), m_controller, SLOT(loadState()));
 814	m_gameActions.append(quickLoad);
 815	m_nonMpActions.append(quickLoad);
 816	addControlledAction(quickLoadMenu, quickLoad, "quickLoad");
 817
 818	QAction* quickSave = new QAction(tr("Save recent"), quickSaveMenu);
 819	connect(quickSave, SIGNAL(triggered()), m_controller, SLOT(saveState()));
 820	m_gameActions.append(quickSave);
 821	m_nonMpActions.append(quickSave);
 822	addControlledAction(quickSaveMenu, quickSave, "quickSave");
 823
 824	quickLoadMenu->addSeparator();
 825	quickSaveMenu->addSeparator();
 826
 827	QAction* undoLoadState = new QAction(tr("Undo load state"), quickLoadMenu);
 828	undoLoadState->setShortcut(tr("F11"));
 829	connect(undoLoadState, SIGNAL(triggered()), m_controller, SLOT(loadBackupState()));
 830	m_gameActions.append(undoLoadState);
 831	m_nonMpActions.append(undoLoadState);
 832	addControlledAction(quickLoadMenu, undoLoadState, "undoLoadState");
 833
 834	QAction* undoSaveState = new QAction(tr("Undo save state"), quickSaveMenu);
 835	undoSaveState->setShortcut(tr("Shift+F11"));
 836	connect(undoSaveState, SIGNAL(triggered()), m_controller, SLOT(saveBackupState()));
 837	m_gameActions.append(undoSaveState);
 838	m_nonMpActions.append(undoSaveState);
 839	addControlledAction(quickSaveMenu, undoSaveState, "undoSaveState");
 840
 841	quickLoadMenu->addSeparator();
 842	quickSaveMenu->addSeparator();
 843
 844	int i;
 845	for (i = 1; i < 10; ++i) {
 846		quickLoad = new QAction(tr("State &%1").arg(i), quickLoadMenu);
 847		quickLoad->setShortcut(tr("F%1").arg(i));
 848		connect(quickLoad, &QAction::triggered, [this, i]() { m_controller->loadState(i); });
 849		m_gameActions.append(quickLoad);
 850		m_nonMpActions.append(quickLoad);
 851		addControlledAction(quickLoadMenu, quickLoad, QString("quickLoad.%1").arg(i));
 852
 853		quickSave = new QAction(tr("State &%1").arg(i), quickSaveMenu);
 854		quickSave->setShortcut(tr("Shift+F%1").arg(i));
 855		connect(quickSave, &QAction::triggered, [this, i]() { m_controller->saveState(i); });
 856		m_gameActions.append(quickSave);
 857		m_nonMpActions.append(quickSave);
 858		addControlledAction(quickSaveMenu, quickSave, QString("quickSave.%1").arg(i));
 859	}
 860
 861	fileMenu->addSeparator();
 862	QAction* importShark = new QAction(tr("Import GameShark Save"), fileMenu);
 863	connect(importShark, SIGNAL(triggered()), this, SLOT(importSharkport()));
 864	m_gameActions.append(importShark);
 865	addControlledAction(fileMenu, importShark, "importShark");
 866
 867	QAction* exportShark = new QAction(tr("Export GameShark Save"), fileMenu);
 868	connect(exportShark, SIGNAL(triggered()), this, SLOT(exportSharkport()));
 869	m_gameActions.append(exportShark);
 870	addControlledAction(fileMenu, exportShark, "exportShark");
 871
 872	fileMenu->addSeparator();
 873	QAction* multiWindow = new QAction(tr("New multiplayer window"), fileMenu);
 874	connect(multiWindow, &QAction::triggered, [this]() {
 875		GBAApp::app()->newWindow();
 876	});
 877	addControlledAction(fileMenu, multiWindow, "multiWindow");
 878
 879#ifndef Q_OS_MAC
 880	fileMenu->addSeparator();
 881#endif
 882
 883	QAction* about = new QAction(tr("About"), fileMenu);
 884	connect(about, SIGNAL(triggered()), this, SLOT(openAboutScreen()));
 885	fileMenu->addAction(about);
 886
 887#ifndef Q_OS_MAC
 888	addControlledAction(fileMenu, fileMenu->addAction(tr("E&xit"), this, SLOT(close()), QKeySequence::Quit), "quit");
 889#endif
 890
 891	QMenu* emulationMenu = menubar->addMenu(tr("&Emulation"));
 892	m_shortcutController->addMenu(emulationMenu);
 893	QAction* reset = new QAction(tr("&Reset"), emulationMenu);
 894	reset->setShortcut(tr("Ctrl+R"));
 895	connect(reset, SIGNAL(triggered()), m_controller, SLOT(reset()));
 896	m_gameActions.append(reset);
 897	addControlledAction(emulationMenu, reset, "reset");
 898
 899	QAction* shutdown = new QAction(tr("Sh&utdown"), emulationMenu);
 900	connect(shutdown, SIGNAL(triggered()), m_controller, SLOT(closeGame()));
 901	m_gameActions.append(shutdown);
 902	addControlledAction(emulationMenu, shutdown, "shutdown");
 903
 904	QAction* yank = new QAction(tr("Yank game pak"), emulationMenu);
 905	connect(yank, SIGNAL(triggered()), m_controller, SLOT(yankPak()));
 906	m_gameActions.append(yank);
 907	addControlledAction(emulationMenu, yank, "yank");
 908	emulationMenu->addSeparator();
 909
 910	QAction* pause = new QAction(tr("&Pause"), emulationMenu);
 911	pause->setChecked(false);
 912	pause->setCheckable(true);
 913	pause->setShortcut(tr("Ctrl+P"));
 914	connect(pause, SIGNAL(triggered(bool)), m_controller, SLOT(setPaused(bool)));
 915	connect(m_controller, &GameController::gamePaused, [this, pause]() {
 916		pause->setChecked(true);
 917	});
 918	connect(m_controller, &GameController::gameUnpaused, [pause]() { pause->setChecked(false); });
 919	m_gameActions.append(pause);
 920	addControlledAction(emulationMenu, pause, "pause");
 921
 922	QAction* frameAdvance = new QAction(tr("&Next frame"), emulationMenu);
 923	frameAdvance->setShortcut(tr("Ctrl+N"));
 924	connect(frameAdvance, SIGNAL(triggered()), m_controller, SLOT(frameAdvance()));
 925	m_gameActions.append(frameAdvance);
 926	m_nonMpActions.append(frameAdvance);
 927	addControlledAction(emulationMenu, frameAdvance, "frameAdvance");
 928
 929	emulationMenu->addSeparator();
 930
 931	m_shortcutController->addFunctions(emulationMenu, [this]() {
 932		m_controller->setTurbo(true, false);
 933	}, [this]() {
 934		m_controller->setTurbo(false, false);
 935	}, QKeySequence(Qt::Key_Tab), tr("Fast forward (held)"), "holdFastForward");
 936
 937	QAction* turbo = new QAction(tr("&Fast forward"), emulationMenu);
 938	turbo->setCheckable(true);
 939	turbo->setChecked(false);
 940	turbo->setShortcut(tr("Shift+Tab"));
 941	connect(turbo, SIGNAL(triggered(bool)), m_controller, SLOT(setTurbo(bool)));
 942	addControlledAction(emulationMenu, turbo, "fastForward");
 943
 944	QMenu* ffspeedMenu = emulationMenu->addMenu(tr("Fast forward speed"));
 945	ConfigOption* ffspeed = m_config->addOption("fastForwardRatio");
 946	ffspeed->connect([this](const QVariant& value) {
 947		m_controller->setTurboSpeed(value.toFloat());
 948	}, this);
 949	ffspeed->addValue(tr("Unbounded"), -1.0f, ffspeedMenu);
 950	ffspeed->setValue(QVariant(-1.0f));
 951	ffspeedMenu->addSeparator();
 952	for (i = 2; i < 11; ++i) {
 953		ffspeed->addValue(tr("%0x").arg(i), i, ffspeedMenu);
 954	}
 955	m_config->updateOption("fastForwardRatio");
 956
 957	m_shortcutController->addFunctions(emulationMenu, [this]() {
 958		m_controller->startRewinding();
 959	}, [this]() {
 960		m_controller->stopRewinding();
 961	}, QKeySequence("~"), tr("Rewind (held)"), "holdRewind");
 962
 963	QAction* rewind = new QAction(tr("Re&wind"), emulationMenu);
 964	rewind->setShortcut(tr("`"));
 965	connect(rewind, SIGNAL(triggered()), m_controller, SLOT(rewind()));
 966	m_gameActions.append(rewind);
 967	m_nonMpActions.append(rewind);
 968	addControlledAction(emulationMenu, rewind, "rewind");
 969
 970	QAction* frameRewind = new QAction(tr("Step backwards"), emulationMenu);
 971	frameRewind->setShortcut(tr("Ctrl+B"));
 972	connect(frameRewind, &QAction::triggered, [this] () {
 973		m_controller->rewind(1);
 974	});
 975	m_gameActions.append(frameRewind);
 976	m_nonMpActions.append(frameRewind);
 977	addControlledAction(emulationMenu, frameRewind, "frameRewind");
 978
 979	ConfigOption* videoSync = m_config->addOption("videoSync");
 980	videoSync->addBoolean(tr("Sync to &video"), emulationMenu);
 981	videoSync->connect([this](const QVariant& value) {
 982		m_controller->setVideoSync(value.toBool());
 983	}, this);
 984	m_config->updateOption("videoSync");
 985
 986	ConfigOption* audioSync = m_config->addOption("audioSync");
 987	audioSync->addBoolean(tr("Sync to &audio"), emulationMenu);
 988	audioSync->connect([this](const QVariant& value) {
 989		m_controller->setAudioSync(value.toBool());
 990	}, this);
 991	m_config->updateOption("audioSync");
 992
 993	emulationMenu->addSeparator();
 994
 995	QMenu* solarMenu = emulationMenu->addMenu(tr("Solar sensor"));
 996	m_shortcutController->addMenu(solarMenu);
 997	QAction* solarIncrease = new QAction(tr("Increase solar level"), solarMenu);
 998	connect(solarIncrease, SIGNAL(triggered()), m_controller, SLOT(increaseLuminanceLevel()));
 999	addControlledAction(solarMenu, solarIncrease, "increaseLuminanceLevel");
1000
1001	QAction* solarDecrease = new QAction(tr("Decrease solar level"), solarMenu);
1002	connect(solarDecrease, SIGNAL(triggered()), m_controller, SLOT(decreaseLuminanceLevel()));
1003	addControlledAction(solarMenu, solarDecrease, "decreaseLuminanceLevel");
1004
1005	QAction* maxSolar = new QAction(tr("Brightest solar level"), solarMenu);
1006	connect(maxSolar, &QAction::triggered, [this]() { m_controller->setLuminanceLevel(10); });
1007	addControlledAction(solarMenu, maxSolar, "maxLuminanceLevel");
1008
1009	QAction* minSolar = new QAction(tr("Darkest solar level"), solarMenu);
1010	connect(minSolar, &QAction::triggered, [this]() { m_controller->setLuminanceLevel(0); });
1011	addControlledAction(solarMenu, minSolar, "minLuminanceLevel");
1012
1013	solarMenu->addSeparator();
1014	for (int i = 0; i <= 10; ++i) {
1015		QAction* setSolar = new QAction(tr("Brightness %1").arg(QString::number(i)), solarMenu);
1016		connect(setSolar, &QAction::triggered, [this, i]() {
1017			m_controller->setLuminanceLevel(i);
1018		});
1019		addControlledAction(solarMenu, setSolar, QString("luminanceLevel.%1").arg(QString::number(i)));
1020	}
1021
1022	QMenu* avMenu = menubar->addMenu(tr("Audio/&Video"));
1023	m_shortcutController->addMenu(avMenu);
1024	QMenu* frameMenu = avMenu->addMenu(tr("Frame size"));
1025	m_shortcutController->addMenu(frameMenu, avMenu);
1026	for (int i = 1; i <= 6; ++i) {
1027		QAction* setSize = new QAction(tr("%1x").arg(QString::number(i)), avMenu);
1028		setSize->setCheckable(true);
1029		connect(setSize, &QAction::triggered, [this, i, setSize]() {
1030			showNormal();
1031			resizeFrame(VIDEO_HORIZONTAL_PIXELS * i, VIDEO_VERTICAL_PIXELS * i);
1032			bool enableSignals = setSize->blockSignals(true);
1033			setSize->setChecked(true);
1034			setSize->blockSignals(enableSignals);
1035		});
1036		m_frameSizes[i] = setSize;
1037		addControlledAction(frameMenu, setSize, QString("frame%1x").arg(QString::number(i)));
1038	}
1039	QKeySequence fullscreenKeys;
1040#ifdef Q_OS_WIN
1041	fullscreenKeys = QKeySequence("Alt+Return");
1042#else
1043	fullscreenKeys = QKeySequence("Ctrl+F");
1044#endif
1045	addControlledAction(frameMenu, frameMenu->addAction(tr("Toggle fullscreen"), this, SLOT(toggleFullScreen()), fullscreenKeys), "fullscreen");
1046
1047	ConfigOption* lockAspectRatio = m_config->addOption("lockAspectRatio");
1048	lockAspectRatio->addBoolean(tr("Lock aspect ratio"), avMenu);
1049	lockAspectRatio->connect([this](const QVariant& value) {
1050		m_display->lockAspectRatio(value.toBool());
1051	}, this);
1052	m_config->updateOption("lockAspectRatio");
1053
1054	ConfigOption* resampleVideo = m_config->addOption("resampleVideo");
1055	resampleVideo->addBoolean(tr("Resample video"), avMenu);
1056	resampleVideo->connect([this](const QVariant& value) {
1057		m_display->filter(value.toBool());
1058	}, this);
1059	m_config->updateOption("resampleVideo");
1060
1061	QMenu* skipMenu = avMenu->addMenu(tr("Frame&skip"));
1062	ConfigOption* skip = m_config->addOption("frameskip");
1063	skip->connect([this](const QVariant& value) {
1064		m_controller->setFrameskip(value.toInt());
1065	}, this);
1066	for (int i = 0; i <= 10; ++i) {
1067		skip->addValue(QString::number(i), i, skipMenu);
1068	}
1069	m_config->updateOption("frameskip");
1070
1071	QAction* shaderView = new QAction(tr("Shader options..."), avMenu);
1072	connect(shaderView, SIGNAL(triggered()), m_shaderView, SLOT(show()));
1073	if (!m_display->supportsShaders()) {
1074		shaderView->setEnabled(false);
1075	}
1076	addControlledAction(avMenu, shaderView, "shaderSelector");
1077
1078	avMenu->addSeparator();
1079
1080	ConfigOption* mute = m_config->addOption("mute");
1081	mute->addBoolean(tr("Mute"), avMenu);
1082	mute->connect([this](const QVariant& value) {
1083		m_controller->setMute(value.toBool());
1084	}, this);
1085	m_config->updateOption("mute");
1086
1087	QMenu* target = avMenu->addMenu(tr("FPS target"));
1088	ConfigOption* fpsTargetOption = m_config->addOption("fpsTarget");
1089	fpsTargetOption->connect([this](const QVariant& value) {
1090		emit fpsTargetChanged(value.toFloat());
1091	}, this);
1092	fpsTargetOption->addValue(tr("15"), 15, target);
1093	fpsTargetOption->addValue(tr("30"), 30, target);
1094	fpsTargetOption->addValue(tr("45"), 45, target);
1095	fpsTargetOption->addValue(tr("Native (59.7)"), float(GBA_ARM7TDMI_FREQUENCY) / float(VIDEO_TOTAL_LENGTH), target);
1096	fpsTargetOption->addValue(tr("60"), 60, target);
1097	fpsTargetOption->addValue(tr("90"), 90, target);
1098	fpsTargetOption->addValue(tr("120"), 120, target);
1099	fpsTargetOption->addValue(tr("240"), 240, target);
1100	m_config->updateOption("fpsTarget");
1101
1102#if defined(USE_PNG) || defined(USE_FFMPEG) || defined(USE_MAGICK)
1103	avMenu->addSeparator();
1104#endif
1105
1106#ifdef USE_PNG
1107	QAction* screenshot = new QAction(tr("Take &screenshot"), avMenu);
1108	screenshot->setShortcut(tr("F12"));
1109	connect(screenshot, SIGNAL(triggered()), m_controller, SLOT(screenshot()));
1110	m_gameActions.append(screenshot);
1111	addControlledAction(avMenu, screenshot, "screenshot");
1112#endif
1113
1114#ifdef USE_FFMPEG
1115	QAction* recordOutput = new QAction(tr("Record output..."), avMenu);
1116	connect(recordOutput, SIGNAL(triggered()), this, SLOT(openVideoWindow()));
1117	addControlledAction(avMenu, recordOutput, "recordOutput");
1118#endif
1119
1120#ifdef USE_MAGICK
1121	QAction* recordGIF = new QAction(tr("Record GIF..."), avMenu);
1122	connect(recordGIF, SIGNAL(triggered()), this, SLOT(openGIFWindow()));
1123	addControlledAction(avMenu, recordGIF, "recordGIF");
1124#endif
1125
1126	avMenu->addSeparator();
1127	QMenu* videoLayers = avMenu->addMenu(tr("Video layers"));
1128
1129	for (int i = 0; i < 4; ++i) {
1130		QAction* enableBg = new QAction(tr("Background %0").arg(i), videoLayers);
1131		enableBg->setCheckable(true);
1132		enableBg->setChecked(true);
1133		connect(enableBg, &QAction::triggered, [this, i](bool enable) { m_controller->setVideoLayerEnabled(i, enable); });
1134		addControlledAction(videoLayers, enableBg, QString("enableBG%0").arg(i));
1135	}
1136
1137	QAction* enableObj = new QAction(tr("OBJ (sprites)"), videoLayers);
1138	enableObj->setCheckable(true);
1139	enableObj->setChecked(true);
1140	connect(enableObj, &QAction::triggered, [this](bool enable) { m_controller->setVideoLayerEnabled(4, enable); });
1141	addControlledAction(videoLayers, enableObj, "enableOBJ");
1142
1143	QMenu* audioChannels = avMenu->addMenu(tr("Audio channels"));
1144
1145	for (int i = 0; i < 4; ++i) {
1146		QAction* enableCh = new QAction(tr("Channel %0").arg(i + 1), audioChannels);
1147		enableCh->setCheckable(true);
1148		enableCh->setChecked(true);
1149		connect(enableCh, &QAction::triggered, [this, i](bool enable) { m_controller->setAudioChannelEnabled(i, enable); });
1150		addControlledAction(audioChannels, enableCh, QString("enableCh%0").arg(i + 1));
1151	}
1152
1153	QAction* enableChA = new QAction(tr("Channel A"), audioChannels);
1154	enableChA->setCheckable(true);
1155	enableChA->setChecked(true);
1156	connect(enableChA, &QAction::triggered, [this, i](bool enable) { m_controller->setAudioChannelEnabled(4, enable); });
1157	addControlledAction(audioChannels, enableChA, QString("enableChA"));
1158
1159	QAction* enableChB = new QAction(tr("Channel B"), audioChannels);
1160	enableChB->setCheckable(true);
1161	enableChB->setChecked(true);
1162	connect(enableChB, &QAction::triggered, [this, i](bool enable) { m_controller->setAudioChannelEnabled(5, enable); });
1163	addControlledAction(audioChannels, enableChB, QString("enableChB"));
1164
1165	QMenu* toolsMenu = menubar->addMenu(tr("&Tools"));
1166	m_shortcutController->addMenu(toolsMenu);
1167	QAction* viewLogs = new QAction(tr("View &logs..."), toolsMenu);
1168	connect(viewLogs, SIGNAL(triggered()), m_logView, SLOT(show()));
1169	addControlledAction(toolsMenu, viewLogs, "viewLogs");
1170
1171	QAction* overrides = new QAction(tr("Game &overrides..."), toolsMenu);
1172	connect(overrides, SIGNAL(triggered()), this, SLOT(openOverrideWindow()));
1173	addControlledAction(toolsMenu, overrides, "overrideWindow");
1174
1175	QAction* sensors = new QAction(tr("Game &Pak sensors..."), toolsMenu);
1176	connect(sensors, SIGNAL(triggered()), this, SLOT(openSensorWindow()));
1177	addControlledAction(toolsMenu, sensors, "sensorWindow");
1178
1179	QAction* cheats = new QAction(tr("&Cheats..."), toolsMenu);
1180	connect(cheats, SIGNAL(triggered()), this, SLOT(openCheatsWindow()));
1181	addControlledAction(toolsMenu, cheats, "cheatsWindow");
1182
1183#ifdef USE_GDB_STUB
1184	QAction* gdbWindow = new QAction(tr("Start &GDB server..."), toolsMenu);
1185	connect(gdbWindow, SIGNAL(triggered()), this, SLOT(gdbOpen()));
1186	addControlledAction(toolsMenu, gdbWindow, "gdbWindow");
1187#endif
1188
1189	toolsMenu->addSeparator();
1190	addControlledAction(toolsMenu, toolsMenu->addAction(tr("Settings..."), this, SLOT(openSettingsWindow())),
1191	                    "settings");
1192
1193	toolsMenu->addSeparator();
1194
1195	QAction* paletteView = new QAction(tr("View &palette..."), toolsMenu);
1196	connect(paletteView, SIGNAL(triggered()), this, SLOT(openPaletteWindow()));
1197	m_gameActions.append(paletteView);
1198	addControlledAction(toolsMenu, paletteView, "paletteWindow");
1199
1200	QAction* memoryView = new QAction(tr("View memory..."), toolsMenu);
1201	connect(memoryView, SIGNAL(triggered()), this, SLOT(openMemoryWindow()));
1202	m_gameActions.append(memoryView);
1203	addControlledAction(toolsMenu, memoryView, "memoryView");
1204
1205	QAction* ioViewer = new QAction(tr("View &I/O registers..."), toolsMenu);
1206	connect(ioViewer, SIGNAL(triggered()), this, SLOT(openIOViewer()));
1207	m_gameActions.append(ioViewer);
1208	addControlledAction(toolsMenu, ioViewer, "ioViewer");
1209
1210	ConfigOption* skipBios = m_config->addOption("skipBios");
1211	skipBios->connect([this](const QVariant& value) {
1212		m_controller->setSkipBIOS(value.toBool());
1213	}, this);
1214
1215	ConfigOption* useBios = m_config->addOption("useBios");
1216	useBios->connect([this](const QVariant& value) {
1217		m_controller->setUseBIOS(value.toBool());
1218	}, this);
1219
1220	ConfigOption* buffers = m_config->addOption("audioBuffers");
1221	buffers->connect([this](const QVariant& value) {
1222		emit audioBufferSamplesChanged(value.toInt());
1223	}, this);
1224
1225	ConfigOption* sampleRate = m_config->addOption("sampleRate");
1226	sampleRate->connect([this](const QVariant& value) {
1227		emit sampleRateChanged(value.toUInt());
1228	}, this);
1229
1230	ConfigOption* volume = m_config->addOption("volume");
1231	volume->connect([this](const QVariant& value) {
1232		m_controller->setVolume(value.toInt());
1233	}, this);
1234
1235	ConfigOption* rewindEnable = m_config->addOption("rewindEnable");
1236	rewindEnable->connect([this](const QVariant& value) {
1237		m_controller->setRewind(value.toBool(), m_config->getOption("rewindBufferCapacity").toInt(), m_config->getOption("rewindBufferInterval").toInt());
1238	}, this);
1239
1240	ConfigOption* rewindBufferCapacity = m_config->addOption("rewindBufferCapacity");
1241	rewindBufferCapacity->connect([this](const QVariant& value) {
1242		m_controller->setRewind(m_config->getOption("rewindEnable").toInt(), value.toInt(), m_config->getOption("rewindBufferInterval").toInt());
1243	}, this);
1244
1245	ConfigOption* rewindBufferInterval = m_config->addOption("rewindBufferInterval");
1246	rewindBufferInterval->connect([this](const QVariant& value) {
1247		m_controller->setRewind(m_config->getOption("rewindEnable").toInt(), m_config->getOption("rewindBufferCapacity").toInt(), value.toInt());
1248	}, this);
1249
1250	ConfigOption* allowOpposingDirections = m_config->addOption("allowOpposingDirections");
1251	allowOpposingDirections->connect([this](const QVariant& value) {
1252		m_inputController.setAllowOpposing(value.toBool());
1253	}, this);
1254
1255	ConfigOption* saveStateExtdata = m_config->addOption("saveStateExtdata");
1256	saveStateExtdata->connect([this](const QVariant& value) {
1257		m_controller->setSaveStateExtdata(value.toInt());
1258	}, this);
1259
1260	ConfigOption* loadStateExtdata = m_config->addOption("loadStateExtdata");
1261	loadStateExtdata->connect([this](const QVariant& value) {
1262		m_controller->setLoadStateExtdata(value.toInt());
1263	}, this);
1264
1265	QAction* exitFullScreen = new QAction(tr("Exit fullscreen"), frameMenu);
1266	connect(exitFullScreen, SIGNAL(triggered()), this, SLOT(exitFullScreen()));
1267	exitFullScreen->setShortcut(QKeySequence("Esc"));
1268	addHiddenAction(frameMenu, exitFullScreen, "exitFullScreen");
1269
1270	QMenu* autofireMenu = new QMenu(tr("Autofire"), this);
1271	m_shortcutController->addMenu(autofireMenu);
1272
1273	m_shortcutController->addFunctions(autofireMenu, [this]() {
1274		m_controller->setAutofire(GBA_KEY_A, true);
1275	}, [this]() {
1276		m_controller->setAutofire(GBA_KEY_A, false);
1277	}, QKeySequence("W"), tr("Autofire A"), "autofireA");
1278
1279	m_shortcutController->addFunctions(autofireMenu, [this]() {
1280		m_controller->setAutofire(GBA_KEY_B, true);
1281	}, [this]() {
1282		m_controller->setAutofire(GBA_KEY_B, false);
1283	}, QKeySequence("Q"), tr("Autofire B"), "autofireB");
1284
1285	m_shortcutController->addFunctions(autofireMenu, [this]() {
1286		m_controller->setAutofire(GBA_KEY_L, true);
1287	}, [this]() {
1288		m_controller->setAutofire(GBA_KEY_L, false);
1289	}, QKeySequence(), tr("Autofire L"), "autofireL");
1290
1291	m_shortcutController->addFunctions(autofireMenu, [this]() {
1292		m_controller->setAutofire(GBA_KEY_R, true);
1293	}, [this]() {
1294		m_controller->setAutofire(GBA_KEY_R, false);
1295	}, QKeySequence(), tr("Autofire R"), "autofireR");
1296
1297	m_shortcutController->addFunctions(autofireMenu, [this]() {
1298		m_controller->setAutofire(GBA_KEY_START, true);
1299	}, [this]() {
1300		m_controller->setAutofire(GBA_KEY_START, false);
1301	}, QKeySequence(), tr("Autofire Start"), "autofireStart");
1302
1303	m_shortcutController->addFunctions(autofireMenu, [this]() {
1304		m_controller->setAutofire(GBA_KEY_SELECT, true);
1305	}, [this]() {
1306		m_controller->setAutofire(GBA_KEY_SELECT, false);
1307	}, QKeySequence(), tr("Autofire Select"), "autofireSelect");
1308
1309	m_shortcutController->addFunctions(autofireMenu, [this]() {
1310		m_controller->setAutofire(GBA_KEY_UP, true);
1311	}, [this]() {
1312		m_controller->setAutofire(GBA_KEY_UP, false);
1313	}, QKeySequence(), tr("Autofire Up"), "autofireUp");
1314
1315	m_shortcutController->addFunctions(autofireMenu, [this]() {
1316		m_controller->setAutofire(GBA_KEY_RIGHT, true);
1317	}, [this]() {
1318		m_controller->setAutofire(GBA_KEY_RIGHT, false);
1319	}, QKeySequence(), tr("Autofire Right"), "autofireRight");
1320
1321	m_shortcutController->addFunctions(autofireMenu, [this]() {
1322		m_controller->setAutofire(GBA_KEY_DOWN, true);
1323	}, [this]() {
1324		m_controller->setAutofire(GBA_KEY_DOWN, false);
1325	}, QKeySequence(), tr("Autofire Down"), "autofireDown");
1326
1327	m_shortcutController->addFunctions(autofireMenu, [this]() {
1328		m_controller->setAutofire(GBA_KEY_LEFT, true);
1329	}, [this]() {
1330		m_controller->setAutofire(GBA_KEY_LEFT, false);
1331	}, QKeySequence(), tr("Autofire Left"), "autofireLeft");
1332
1333	foreach (QAction* action, m_gameActions) {
1334		action->setDisabled(true);
1335	}
1336}
1337
1338void Window::attachWidget(QWidget* widget) {
1339	m_screenWidget->layout()->addWidget(widget);
1340	m_screenWidget->unsetCursor();
1341	static_cast<QStackedLayout*>(m_screenWidget->layout())->setCurrentWidget(widget);
1342}
1343
1344void Window::detachWidget(QWidget* widget) {
1345	m_screenWidget->layout()->removeWidget(widget);
1346}
1347
1348void Window::appendMRU(const QString& fname) {
1349	int index = m_mruFiles.indexOf(fname);
1350	if (index >= 0) {
1351		m_mruFiles.removeAt(index);
1352	}
1353	m_mruFiles.prepend(fname);
1354	while (m_mruFiles.size() > ConfigController::MRU_LIST_SIZE) {
1355		m_mruFiles.removeLast();
1356	}
1357	updateMRU();
1358}
1359
1360void Window::updateMRU() {
1361	if (!m_mruMenu) {
1362		return;
1363	}
1364	m_mruMenu->clear();
1365	int i = 0;
1366	for (const QString& file : m_mruFiles) {
1367		QAction* item = new QAction(file, m_mruMenu);
1368		item->setShortcut(QString("Ctrl+%1").arg(i));
1369		connect(item, &QAction::triggered, [this, file]() { m_controller->loadGame(file); });
1370		m_mruMenu->addAction(item);
1371		++i;
1372	}
1373	m_config->setMRU(m_mruFiles);
1374	m_config->write();
1375	m_mruMenu->setEnabled(i > 0);
1376}
1377
1378QAction* Window::addControlledAction(QMenu* menu, QAction* action, const QString& name) {
1379	addHiddenAction(menu, action, name);
1380	menu->addAction(action);
1381	return action;
1382}
1383
1384QAction* Window::addHiddenAction(QMenu* menu, QAction* action, const QString& name) {
1385	m_shortcutController->addAction(menu, action, name);
1386	action->setShortcutContext(Qt::WidgetShortcut);
1387	addAction(action);
1388	return action;
1389}
1390
1391void Window::focusCheck() {
1392	if (!m_config->getOption("pauseOnFocusLost").toInt()) {
1393		return;
1394	}
1395	if (QGuiApplication::focusWindow() && m_autoresume) {
1396		m_controller->setPaused(false);
1397	} else if (!QGuiApplication::focusWindow() && !m_controller->isPaused()) {
1398		m_autoresume = true;
1399		m_controller->setPaused(true);
1400	}
1401}
1402
1403WindowBackground::WindowBackground(QWidget* parent)
1404	: QLabel(parent)
1405{
1406	setLayout(new QStackedLayout());
1407	layout()->setContentsMargins(0, 0, 0, 0);
1408	setAlignment(Qt::AlignCenter);
1409}
1410
1411void WindowBackground::setSizeHint(const QSize& hint) {
1412	m_sizeHint = hint;
1413}
1414
1415QSize WindowBackground::sizeHint() const {
1416	return m_sizeHint;
1417}
1418
1419void WindowBackground::setLockAspectRatio(int width, int height) {
1420	m_aspectWidth = width;
1421	m_aspectHeight = height;
1422}
1423
1424void WindowBackground::paintEvent(QPaintEvent*) {
1425	const QPixmap* logo = pixmap();
1426	if (!logo) {
1427		return;
1428	}
1429	QPainter painter(this);
1430	painter.setRenderHint(QPainter::SmoothPixmapTransform);
1431	painter.fillRect(QRect(QPoint(), size()), Qt::black);
1432	QSize s = size();
1433	QSize ds = s;
1434	if (ds.width() * m_aspectHeight > ds.height() * m_aspectWidth) {
1435		ds.setWidth(ds.height() * m_aspectWidth / m_aspectHeight);
1436	} else if (ds.width() * m_aspectHeight < ds.height() * m_aspectWidth) {
1437		ds.setHeight(ds.width() * m_aspectHeight / m_aspectWidth);
1438	}
1439	QPoint origin = QPoint((s.width() - ds.width()) / 2, (s.height() - ds.height()) / 2);
1440	QRect full(origin, ds);
1441	painter.drawPixmap(full, *logo);
1442}