all repos — mgba @ 5bd0bacb8bbf7eac890fb9570fcbb8ae1c28407d

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