all repos — mgba @ 4360e73d1427312396135125efa45fe9aeb58175

mGBA Game Boy Advance Emulator

src/platform/qt/Window.cpp (view raw)

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