all repos — mgba @ 3ace420e3fa7a4a43b4f4a5649113ebded7eb5dc

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 <QFileDialog>
   9#include <QFileInfo>
  10#include <QKeyEvent>
  11#include <QKeySequence>
  12#include <QMenuBar>
  13#include <QMessageBox>
  14#include <QMimeData>
  15#include <QPainter>
  16#include <QStackedLayout>
  17
  18#include "CheatsView.h"
  19#include "ConfigController.h"
  20#include "DisplayGL.h"
  21#include "GameController.h"
  22#include "GBAKeyEditor.h"
  23#include "GDBController.h"
  24#include "GDBWindow.h"
  25#include "GIFView.h"
  26#include "LoadSaveState.h"
  27#include "LogView.h"
  28#include "MultiplayerController.h"
  29#include "MemoryView.h"
  30#include "OverrideView.h"
  31#include "PaletteView.h"
  32#include "SensorView.h"
  33#include "SettingsView.h"
  34#include "ShortcutController.h"
  35#include "ShortcutView.h"
  36#include "VideoView.h"
  37
  38extern "C" {
  39#include "platform/commandline.h"
  40}
  41
  42using namespace QGBA;
  43
  44#ifdef __WIN32
  45// This is a macro everywhere except MinGW, it seems
  46using std::isnan;
  47#endif
  48
  49Window::Window(ConfigController* config, int playerId, QWidget* parent)
  50	: QMainWindow(parent)
  51	, m_logView(new LogView())
  52	, m_stateWindow(nullptr)
  53	, m_screenWidget(new WindowBackground())
  54	, m_logo(":/res/mgba-1024.png")
  55	, m_config(config)
  56	, m_inputController(playerId)
  57#ifdef USE_FFMPEG
  58	, m_videoView(nullptr)
  59#endif
  60#ifdef USE_MAGICK
  61	, m_gifView(nullptr)
  62#endif
  63#ifdef USE_GDB_STUB
  64	, m_gdbController(nullptr)
  65#endif
  66	, m_mruMenu(nullptr)
  67	, m_shortcutController(new ShortcutController(this))
  68	, m_playerId(playerId)
  69{
  70	setFocusPolicy(Qt::StrongFocus);
  71	setAcceptDrops(true);
  72	m_controller = new GameController(this);
  73	m_controller->setInputController(&m_inputController);
  74	m_controller->setOverrides(m_config->overrides());
  75	updateTitle();
  76
  77	QGLFormat format(QGLFormat(QGL::Rgba | QGL::DoubleBuffer));
  78	format.setSwapInterval(1);
  79	m_display = new DisplayGL(format, this);
  80
  81	m_logo.setDevicePixelRatio(m_screenWidget->devicePixelRatio());
  82	m_logo = m_logo; // Free memory left over in old pixmap
  83
  84	m_screenWidget->setMinimumSize(m_display->minimumSize());
  85	m_screenWidget->setSizePolicy(m_display->sizePolicy());
  86	m_screenWidget->setSizeHint(m_display->minimumSize() * 2);
  87	m_screenWidget->setPixmap(m_logo);
  88	m_screenWidget->setLockAspectRatio(m_logo.width(), m_logo.height());
  89	setCentralWidget(m_screenWidget);
  90
  91	QVariant windowPos = m_config->getQtOption("windowPos");
  92	if (!windowPos.isNull()) {
  93		move(windowPos.toPoint());
  94	}
  95
  96	connect(m_controller, SIGNAL(gameStarted(GBAThread*)), this, SLOT(gameStarted(GBAThread*)));
  97	connect(m_controller, SIGNAL(gameStarted(GBAThread*)), &m_inputController, SLOT(suspendScreensaver()));
  98	connect(m_controller, SIGNAL(gameStopped(GBAThread*)), m_display, SLOT(stopDrawing()));
  99	connect(m_controller, SIGNAL(gameStopped(GBAThread*)), this, SLOT(gameStopped()));
 100	connect(m_controller, SIGNAL(gameStopped(GBAThread*)), &m_inputController, SLOT(resumeScreensaver()));
 101	connect(m_controller, SIGNAL(stateLoaded(GBAThread*)), m_display, SLOT(forceDraw()));
 102	connect(m_controller, SIGNAL(rewound(GBAThread*)), m_display, SLOT(forceDraw()));
 103	connect(m_controller, SIGNAL(gamePaused(GBAThread*)), m_display, SLOT(pauseDrawing()));
 104#ifndef Q_OS_MAC
 105	connect(m_controller, SIGNAL(gamePaused(GBAThread*)), menuBar(), SLOT(show()));
 106	connect(m_controller, &GameController::gameUnpaused, [this]() {
 107		if(isFullScreen()) {
 108			menuBar()->hide();
 109		}
 110	});
 111#endif
 112	connect(m_controller, SIGNAL(gamePaused(GBAThread*)), &m_inputController, SLOT(resumeScreensaver()));
 113	connect(m_controller, SIGNAL(gameUnpaused(GBAThread*)), m_display, SLOT(unpauseDrawing()));
 114	connect(m_controller, SIGNAL(gameUnpaused(GBAThread*)), &m_inputController, SLOT(suspendScreensaver()));
 115	connect(m_controller, SIGNAL(postLog(int, const QString&)), m_logView, SLOT(postLog(int, const QString&)));
 116	connect(m_controller, SIGNAL(frameAvailable(const uint32_t*)), this, SLOT(recordFrame()));
 117	connect(m_controller, SIGNAL(frameAvailable(const uint32_t*)), m_display, SLOT(framePosted(const uint32_t*)));
 118	connect(m_controller, SIGNAL(gameCrashed(const QString&)), this, SLOT(gameCrashed(const QString&)));
 119	connect(m_controller, SIGNAL(gameFailed()), this, SLOT(gameFailed()));
 120	connect(m_controller, SIGNAL(unimplementedBiosCall(int)), this, SLOT(unimplementedBiosCall(int)));
 121	connect(m_controller, SIGNAL(statusPosted(const QString&)), m_display, SLOT(showMessage(const QString&)));
 122	connect(m_logView, SIGNAL(levelsSet(int)), m_controller, SLOT(setLogLevel(int)));
 123	connect(m_logView, SIGNAL(levelsEnabled(int)), m_controller, SLOT(enableLogLevel(int)));
 124	connect(m_logView, SIGNAL(levelsDisabled(int)), m_controller, SLOT(disableLogLevel(int)));
 125	connect(this, SIGNAL(startDrawing(GBAThread*)), m_display, SLOT(startDrawing(GBAThread*)), Qt::QueuedConnection);
 126	connect(this, SIGNAL(shutdown()), m_display, SLOT(stopDrawing()));
 127	connect(this, SIGNAL(shutdown()), m_controller, SLOT(closeGame()));
 128	connect(this, SIGNAL(shutdown()), m_logView, SLOT(hide()));
 129	connect(this, SIGNAL(audioBufferSamplesChanged(int)), m_controller, SLOT(setAudioBufferSamples(int)));
 130	connect(this, SIGNAL(fpsTargetChanged(float)), m_controller, SLOT(setFPSTarget(float)));
 131	connect(&m_fpsTimer, SIGNAL(timeout()), this, SLOT(showFPS()));
 132
 133	m_logView->setLevels(GBA_LOG_WARN | GBA_LOG_ERROR | GBA_LOG_FATAL | GBA_LOG_STATUS);
 134	m_fpsTimer.setInterval(FPS_TIMER_INTERVAL);
 135
 136	m_shortcutController->setConfigController(m_config);
 137	setupMenu(menuBar());
 138}
 139
 140Window::~Window() {
 141	delete m_logView;
 142
 143#ifdef USE_FFMPEG
 144	delete m_videoView;
 145#endif
 146
 147#ifdef USE_MAGICK
 148	delete m_gifView;
 149#endif
 150}
 151
 152void Window::argumentsPassed(GBAArguments* args) {
 153	loadConfig();
 154
 155	if (args->patch) {
 156		m_controller->loadPatch(args->patch);
 157	}
 158
 159	if (args->fname) {
 160		m_controller->loadGame(args->fname, args->dirmode);
 161	}
 162}
 163
 164void Window::resizeFrame(int width, int height) {
 165	QSize newSize(width, height);
 166	newSize -= m_screenWidget->size();
 167	newSize += size();
 168	resize(newSize);
 169}
 170
 171void Window::setConfig(ConfigController* config) {
 172	m_config = config;
 173}
 174
 175void Window::loadConfig() {
 176	const GBAOptions* opts = m_config->options();
 177
 178	m_logView->setLevels(opts->logLevel);
 179
 180	m_controller->setOptions(opts);
 181	m_display->lockAspectRatio(opts->lockAspectRatio);
 182	m_display->filter(opts->resampleVideo);
 183
 184	if (opts->bios) {
 185		m_controller->loadBIOS(opts->bios);
 186	}
 187
 188	if (opts->fpsTarget) {
 189		emit fpsTargetChanged(opts->fpsTarget);
 190	}
 191
 192	if (opts->audioBuffers) {
 193		emit audioBufferSamplesChanged(opts->audioBuffers);
 194	}
 195
 196	if (opts->width && opts->height) {
 197		resizeFrame(opts->width, opts->height);
 198	}
 199
 200	if (opts->fullscreen) {
 201		enterFullScreen();
 202	}
 203
 204	m_inputController.setScreensaverSuspendable(opts->suspendScreensaver);
 205
 206	m_mruFiles = m_config->getMRU();
 207	updateMRU();
 208
 209	m_inputController.setConfiguration(m_config);
 210}
 211
 212void Window::saveConfig() {
 213	m_inputController.saveConfiguration();
 214	m_config->write();
 215}
 216
 217void Window::selectROM() {
 218	bool doPause = m_controller->isLoaded() && !m_controller->isPaused();
 219	if (doPause) {
 220		m_controller->setPaused(true);
 221	}
 222	QStringList formats{
 223		"*.gba",
 224#ifdef USE_LIBZIP
 225		"*.zip",
 226#endif
 227#ifdef USE_LZMA
 228		"*.7z",
 229#endif
 230		"*.rom",
 231		"*.bin"};
 232	QString filter = tr("Game Boy Advance ROMs (%1)").arg(formats.join(QChar(' ')));
 233	QString filename = QFileDialog::getOpenFileName(this, tr("Select ROM"), m_config->getQtOption("lastDirectory").toString(), filter);
 234	if (doPause) {
 235		m_controller->setPaused(false);
 236	}
 237	if (!filename.isEmpty()) {
 238		m_config->setQtOption("lastDirectory", QFileInfo(filename).dir().path());
 239		m_controller->loadGame(filename);
 240	}
 241}
 242
 243void Window::selectBIOS() {
 244	bool doPause = m_controller->isLoaded() && !m_controller->isPaused();
 245	if (doPause) {
 246		m_controller->setPaused(true);
 247	}
 248	QString filename = QFileDialog::getOpenFileName(this, tr("Select BIOS"), m_config->getQtOption("lastDirectory").toString());
 249	if (doPause) {
 250		m_controller->setPaused(false);
 251	}
 252	if (!filename.isEmpty()) {
 253		m_config->setQtOption("lastDirectory", QFileInfo(filename).dir().path());
 254		m_config->setOption("bios", filename);
 255		m_config->updateOption("bios");
 256		m_config->setOption("useBios", true);
 257		m_config->updateOption("useBios");
 258		m_controller->loadBIOS(filename);
 259	}
 260}
 261
 262void Window::selectPatch() {
 263	bool doPause = m_controller->isLoaded() && !m_controller->isPaused();
 264	if (doPause) {
 265		m_controller->setPaused(true);
 266	}
 267	QString filename = QFileDialog::getOpenFileName(this, tr("Select patch"), m_config->getQtOption("lastDirectory").toString(), tr("Patches (*.ips *.ups *.bps)"));
 268	if (doPause) {
 269		m_controller->setPaused(false);
 270	}
 271	if (!filename.isEmpty()) {
 272		m_config->setQtOption("lastDirectory", QFileInfo(filename).dir().path());
 273		m_controller->loadPatch(filename);
 274	}
 275}
 276
 277void Window::openView(QWidget* widget) {
 278	connect(this, SIGNAL(shutdown()), widget, SLOT(close()));
 279	widget->setAttribute(Qt::WA_DeleteOnClose);
 280	widget->show();
 281}
 282
 283void Window::importSharkport() {
 284	bool doPause = m_controller->isLoaded() && !m_controller->isPaused();
 285	if (doPause) {
 286		m_controller->setPaused(true);
 287	}
 288	QString filename = QFileDialog::getOpenFileName(this, tr("Select save"), m_config->getQtOption("lastDirectory").toString(), tr("GameShark saves (*.sps *.xps)"));
 289	if (doPause) {
 290		m_controller->setPaused(false);
 291	}
 292	if (!filename.isEmpty()) {
 293		m_config->setQtOption("lastDirectory", QFileInfo(filename).dir().path());
 294		m_controller->importSharkport(filename);
 295	}
 296}
 297
 298void Window::exportSharkport() {
 299	bool doPause = m_controller->isLoaded() && !m_controller->isPaused();
 300	if (doPause) {
 301		m_controller->setPaused(true);
 302	}
 303	QString filename = QFileDialog::getSaveFileName(this, tr("Select save"), m_config->getQtOption("lastDirectory").toString(), tr("GameShark saves (*.sps *.xps)"));
 304	if (doPause) {
 305		m_controller->setPaused(false);
 306	}
 307	if (!filename.isEmpty()) {
 308		m_config->setQtOption("lastDirectory", QFileInfo(filename).dir().path());
 309		m_controller->exportSharkport(filename);
 310	}
 311}
 312
 313void Window::openKeymapWindow() {
 314	GBAKeyEditor* keyEditor = new GBAKeyEditor(&m_inputController, InputController::KEYBOARD);
 315	openView(keyEditor);
 316}
 317
 318void Window::openSettingsWindow() {
 319	SettingsView* settingsWindow = new SettingsView(m_config);
 320	connect(settingsWindow, SIGNAL(biosLoaded(const QString&)), m_controller, SLOT(loadBIOS(const QString&)));
 321	connect(settingsWindow, SIGNAL(audioDriverChanged()), m_controller, SLOT(reloadAudioDriver()));
 322	openView(settingsWindow);
 323}
 324
 325void Window::openShortcutWindow() {
 326#ifdef BUILD_SDL
 327	m_inputController.recalibrateAxes();
 328#endif
 329	ShortcutView* shortcutView = new ShortcutView();
 330	shortcutView->setController(m_shortcutController);
 331	openView(shortcutView);
 332}
 333
 334void Window::openOverrideWindow() {
 335	OverrideView* overrideWindow = new OverrideView(m_controller, m_config);
 336	openView(overrideWindow);
 337}
 338
 339void Window::openSensorWindow() {
 340	SensorView* sensorWindow = new SensorView(m_controller, &m_inputController);
 341	openView(sensorWindow);
 342}
 343
 344void Window::openCheatsWindow() {
 345	CheatsView* cheatsWindow = new CheatsView(m_controller);
 346	openView(cheatsWindow);
 347}
 348
 349void Window::openPaletteWindow() {
 350	PaletteView* paletteWindow = new PaletteView(m_controller);
 351	openView(paletteWindow);
 352}
 353
 354void Window::openMemoryWindow() {
 355	MemoryView* memoryWindow = new MemoryView(m_controller);
 356	openView(memoryWindow);
 357}
 358
 359#ifdef BUILD_SDL
 360void Window::openGamepadWindow() {
 361	const char* profile = m_inputController.profileForType(SDL_BINDING_BUTTON);
 362	GBAKeyEditor* keyEditor = new GBAKeyEditor(&m_inputController, SDL_BINDING_BUTTON, profile);
 363	openView(keyEditor);
 364}
 365#endif
 366
 367#ifdef USE_FFMPEG
 368void Window::openVideoWindow() {
 369	if (!m_videoView) {
 370		m_videoView = new VideoView();
 371		connect(m_videoView, SIGNAL(recordingStarted(GBAAVStream*)), m_controller, SLOT(setAVStream(GBAAVStream*)));
 372		connect(m_videoView, SIGNAL(recordingStopped()), m_controller, SLOT(clearAVStream()), Qt::DirectConnection);
 373		connect(m_controller, SIGNAL(gameStopped(GBAThread*)), m_videoView, SLOT(stopRecording()));
 374		connect(m_controller, SIGNAL(gameStopped(GBAThread*)), m_videoView, SLOT(close()));
 375		connect(this, SIGNAL(shutdown()), m_videoView, SLOT(close()));
 376	}
 377	m_videoView->show();
 378}
 379#endif
 380
 381#ifdef USE_MAGICK
 382void Window::openGIFWindow() {
 383	if (!m_gifView) {
 384		m_gifView = new GIFView();
 385		connect(m_gifView, SIGNAL(recordingStarted(GBAAVStream*)), m_controller, SLOT(setAVStream(GBAAVStream*)));
 386		connect(m_gifView, SIGNAL(recordingStopped()), m_controller, SLOT(clearAVStream()), Qt::DirectConnection);
 387		connect(m_controller, SIGNAL(gameStopped(GBAThread*)), m_gifView, SLOT(stopRecording()));
 388		connect(m_controller, SIGNAL(gameStopped(GBAThread*)), m_gifView, SLOT(close()));
 389		connect(this, SIGNAL(shutdown()), m_gifView, SLOT(close()));
 390	}
 391	m_gifView->show();
 392}
 393#endif
 394
 395#ifdef USE_GDB_STUB
 396void Window::gdbOpen() {
 397	if (!m_gdbController) {
 398		m_gdbController = new GDBController(m_controller, this);
 399	}
 400	GDBWindow* window = new GDBWindow(m_gdbController);
 401	connect(this, SIGNAL(shutdown()), window, SLOT(close()));
 402	window->setAttribute(Qt::WA_DeleteOnClose);
 403	window->show();
 404}
 405#endif
 406
 407void Window::keyPressEvent(QKeyEvent* event) {
 408	if (event->isAutoRepeat()) {
 409		QWidget::keyPressEvent(event);
 410		return;
 411	}
 412	GBAKey key = m_inputController.mapKeyboard(event->key());
 413	if (key == GBA_KEY_NONE) {
 414		QWidget::keyPressEvent(event);
 415		return;
 416	}
 417	m_controller->keyPressed(key);
 418	event->accept();
 419}
 420
 421void Window::keyReleaseEvent(QKeyEvent* event) {
 422	if (event->isAutoRepeat()) {
 423		QWidget::keyReleaseEvent(event);
 424		return;
 425	}
 426	GBAKey key = m_inputController.mapKeyboard(event->key());
 427	if (key == GBA_KEY_NONE) {
 428		QWidget::keyPressEvent(event);
 429		return;
 430	}
 431	m_controller->keyReleased(key);
 432	event->accept();
 433}
 434
 435void Window::resizeEvent(QResizeEvent*) {
 436	m_config->setOption("height", m_screenWidget->height());
 437	m_config->setOption("width", m_screenWidget->width());
 438	m_config->setOption("fullscreen", isFullScreen());
 439}
 440
 441void Window::closeEvent(QCloseEvent* event) {
 442	emit shutdown();
 443	m_config->setQtOption("windowPos", pos());
 444	saveConfig();
 445	QMainWindow::closeEvent(event);
 446}
 447
 448void Window::focusOutEvent(QFocusEvent*) {
 449	m_controller->setTurbo(false, false);
 450	m_controller->clearKeys();
 451}
 452
 453void Window::dragEnterEvent(QDragEnterEvent* event) {
 454	if (event->mimeData()->hasFormat("text/uri-list")) {
 455		event->acceptProposedAction();
 456	}
 457}
 458
 459void Window::dropEvent(QDropEvent* event) {
 460	QString uris = event->mimeData()->data("text/uri-list");
 461	uris = uris.trimmed();
 462	if (uris.contains("\n")) {
 463		// Only one file please
 464		return;
 465	}
 466	QUrl url(uris);
 467	if (!url.isLocalFile()) {
 468		// No remote loading
 469		return;
 470	}
 471	event->accept();
 472	m_controller->loadGame(url.path());
 473}
 474
 475void Window::mouseDoubleClickEvent(QMouseEvent* event) {
 476	if (event->button() != Qt::LeftButton) {
 477		return;
 478	}
 479	toggleFullScreen();
 480}
 481
 482void Window::enterFullScreen() {
 483	if (isFullScreen()) {
 484		return;
 485	}
 486	showFullScreen();
 487#ifndef Q_OS_MAC
 488	if (m_controller->isLoaded() && !m_controller->isPaused()) {
 489		menuBar()->hide();
 490	}
 491#endif
 492}
 493
 494void Window::exitFullScreen() {
 495	if (!isFullScreen()) {
 496		return;
 497	}
 498	showNormal();
 499	menuBar()->show();
 500}
 501
 502void Window::toggleFullScreen() {
 503	if (isFullScreen()) {
 504		exitFullScreen();
 505	} else {
 506		enterFullScreen();
 507	}
 508}
 509
 510void Window::gameStarted(GBAThread* context) {
 511	char title[13] = { '\0' };
 512	MutexLock(&context->stateMutex);
 513	if (context->state < THREAD_EXITING) {
 514		emit startDrawing(context);
 515		GBAGetGameTitle(context->gba, title);
 516	} else {
 517		MutexUnlock(&context->stateMutex);
 518		return;
 519	}
 520	MutexUnlock(&context->stateMutex);
 521	foreach (QAction* action, m_gameActions) {
 522		action->setDisabled(false);
 523	}
 524	appendMRU(context->fname);
 525	updateTitle();
 526	attachWidget(m_display);
 527
 528#ifndef Q_OS_MAC
 529	if(isFullScreen()) {
 530		menuBar()->hide();
 531	}
 532#endif
 533
 534	m_hitUnimplementedBiosCall = false;
 535	m_fpsTimer.start();
 536}
 537
 538void Window::gameStopped() {
 539	foreach (QAction* action, m_gameActions) {
 540		action->setDisabled(true);
 541	}
 542	updateTitle();
 543	detachWidget(m_display);
 544	m_screenWidget->setLockAspectRatio(m_logo.width(), m_logo.height());
 545	m_screenWidget->setPixmap(m_logo);
 546
 547	m_fpsTimer.stop();
 548}
 549
 550void Window::gameCrashed(const QString& errorMessage) {
 551	QMessageBox* crash = new QMessageBox(QMessageBox::Critical, tr("Crash"),
 552		tr("The game has crashed with the following error:\n\n%1").arg(errorMessage),
 553		QMessageBox::Ok, this,  Qt::Sheet);
 554	crash->setAttribute(Qt::WA_DeleteOnClose);
 555	crash->show();
 556}
 557
 558void Window::gameFailed() {
 559	QMessageBox* fail = new QMessageBox(QMessageBox::Warning, tr("Couldn't Load"),
 560		tr("Could not load game. Are you sure it's in the correct format?"),
 561		QMessageBox::Ok, this,  Qt::Sheet);
 562	fail->setAttribute(Qt::WA_DeleteOnClose);
 563	fail->show();
 564}
 565
 566void Window::unimplementedBiosCall(int call) {
 567	if (m_hitUnimplementedBiosCall) {
 568		return;
 569	}
 570	m_hitUnimplementedBiosCall = true;
 571
 572	QMessageBox* fail = new QMessageBox(QMessageBox::Warning, tr("Unimplemented BIOS call"),
 573		tr("This game uses a BIOS call that is not implemented. Please use the official BIOS for best experience."),
 574		QMessageBox::Ok, this,  Qt::Sheet);
 575	fail->setAttribute(Qt::WA_DeleteOnClose);
 576	fail->show();
 577}
 578
 579void Window::recordFrame() {
 580	m_frameList.append(QDateTime::currentDateTime());
 581	while (m_frameList.count() > FRAME_LIST_SIZE) {
 582		m_frameList.removeFirst();
 583	}
 584}
 585
 586void Window::showFPS() {
 587	if (m_frameList.isEmpty()) {
 588		updateTitle();
 589		return;
 590	}
 591	qint64 interval = m_frameList.first().msecsTo(m_frameList.last());
 592	float fps = (m_frameList.count() - 1) * 10000.f / interval;
 593	fps = round(fps) / 10.f;
 594	updateTitle(fps);
 595}
 596
 597void Window::updateTitle(float fps) {
 598	QString title;
 599
 600	m_controller->threadInterrupt();
 601	if (m_controller->isLoaded()) {
 602		char gameTitle[13] = { '\0' };
 603		GBAGetGameTitle(m_controller->thread()->gba, gameTitle);
 604
 605		title = (gameTitle);
 606	}
 607	std::shared_ptr<MultiplayerController> multiplayer = m_controller->multiplayerController();
 608	if (multiplayer && multiplayer->attached() > 1) {
 609		title += tr(" -  Player %1 of %2").arg(m_playerId + 1).arg(multiplayer->attached());
 610	}
 611	m_controller->threadContinue();
 612	if (title.isNull()) {
 613		setWindowTitle(tr("%1 - %2").arg(projectName).arg(projectVersion));
 614	} else if (isnan(fps)) {
 615		setWindowTitle(tr("%1 - %2 - %3").arg(projectName).arg(title).arg(projectVersion));
 616	} else {
 617		setWindowTitle(tr("%1 - %2 (%3 fps) - %4").arg(projectName).arg(title).arg(fps).arg(projectVersion));
 618	}
 619}
 620
 621void Window::openStateWindow(LoadSave ls) {
 622	if (m_stateWindow) {
 623		return;
 624	}
 625	bool wasPaused = m_controller->isPaused();
 626	m_stateWindow = new LoadSaveState(m_controller);
 627	connect(this, SIGNAL(shutdown()), m_stateWindow, SLOT(close()));
 628	connect(m_controller, SIGNAL(gameStopped(GBAThread*)), m_stateWindow, SLOT(close()));
 629	connect(m_stateWindow, &LoadSaveState::closed, [this]() {
 630		m_screenWidget->layout()->removeWidget(m_stateWindow);
 631		m_stateWindow = nullptr;
 632		QMetaObject::invokeMethod(this, "setFocus", Qt::QueuedConnection);
 633	});
 634	if (!wasPaused) {
 635		m_controller->setPaused(true);
 636		connect(m_stateWindow, &LoadSaveState::closed, [this]() { m_controller->setPaused(false); });
 637	}
 638	m_stateWindow->setAttribute(Qt::WA_DeleteOnClose);
 639	m_stateWindow->setMode(ls);
 640	attachWidget(m_stateWindow);
 641}
 642
 643void Window::setupMenu(QMenuBar* menubar) {
 644	menubar->clear();
 645	QMenu* fileMenu = menubar->addMenu(tr("&File"));
 646	m_shortcutController->addMenu(fileMenu);
 647	installEventFilter(m_shortcutController);
 648	addControlledAction(fileMenu, fileMenu->addAction(tr("Load &ROM..."), this, SLOT(selectROM()), QKeySequence::Open), "loadROM");
 649	addControlledAction(fileMenu, fileMenu->addAction(tr("Load &BIOS..."), this, SLOT(selectBIOS())), "loadBIOS");
 650	addControlledAction(fileMenu, fileMenu->addAction(tr("Load &patch..."), this, SLOT(selectPatch())), "loadPatch");
 651
 652	m_mruMenu = fileMenu->addMenu(tr("Recent"));
 653
 654	fileMenu->addSeparator();
 655
 656	QAction* loadState = new QAction(tr("&Load state"), fileMenu);
 657	loadState->setShortcut(tr("F10"));
 658	connect(loadState, &QAction::triggered, [this]() { this->openStateWindow(LoadSave::LOAD); });
 659	m_gameActions.append(loadState);
 660	addControlledAction(fileMenu, loadState, "loadState");
 661
 662	QAction* saveState = new QAction(tr("&Save state"), fileMenu);
 663	saveState->setShortcut(tr("Shift+F10"));
 664	connect(saveState, &QAction::triggered, [this]() { this->openStateWindow(LoadSave::SAVE); });
 665	m_gameActions.append(saveState);
 666	addControlledAction(fileMenu, saveState, "saveState");
 667
 668	QMenu* quickLoadMenu = fileMenu->addMenu(tr("Quick load"));
 669	QMenu* quickSaveMenu = fileMenu->addMenu(tr("Quick save"));
 670	m_shortcutController->addMenu(quickLoadMenu);
 671	m_shortcutController->addMenu(quickSaveMenu);
 672
 673	QAction* quickLoad = new QAction(tr("Load recent"), quickLoadMenu);
 674	connect(quickLoad, SIGNAL(triggered()), m_controller, SLOT(loadState()));
 675	m_gameActions.append(quickLoad);
 676	addControlledAction(quickLoadMenu, quickLoad, "quickLoad");
 677
 678	QAction* quickSave = new QAction(tr("Save recent"), quickSaveMenu);
 679	connect(quickSave, SIGNAL(triggered()), m_controller, SLOT(saveState()));
 680	m_gameActions.append(quickSave);
 681	addControlledAction(quickSaveMenu, quickSave, "quickSave");
 682
 683	quickLoadMenu->addSeparator();
 684	quickSaveMenu->addSeparator();
 685
 686	int i;
 687	for (i = 1; i < 10; ++i) {
 688		quickLoad = new QAction(tr("State &%1").arg(i), quickLoadMenu);
 689		quickLoad->setShortcut(tr("F%1").arg(i));
 690		connect(quickLoad, &QAction::triggered, [this, i]() { m_controller->loadState(i); });
 691		m_gameActions.append(quickLoad);
 692		addControlledAction(quickLoadMenu, quickLoad, QString("quickLoad.%1").arg(i));
 693
 694		quickSave = new QAction(tr("State &%1").arg(i), quickSaveMenu);
 695		quickSave->setShortcut(tr("Shift+F%1").arg(i));
 696		connect(quickSave, &QAction::triggered, [this, i]() { m_controller->saveState(i); });
 697		m_gameActions.append(quickSave);
 698		addControlledAction(quickSaveMenu, quickSave, QString("quickSave.%1").arg(i));
 699	}
 700
 701	fileMenu->addSeparator();
 702	QAction* importShark = new QAction(tr("Import GameShark Save"), fileMenu);
 703	connect(importShark, SIGNAL(triggered()), this, SLOT(importSharkport()));
 704	m_gameActions.append(importShark);
 705	addControlledAction(fileMenu, importShark, "importShark");
 706
 707	QAction* exportShark = new QAction(tr("Export GameShark Save"), fileMenu);
 708	connect(exportShark, SIGNAL(triggered()), this, SLOT(exportSharkport()));
 709	m_gameActions.append(exportShark);
 710	addControlledAction(fileMenu, exportShark, "exportShark");
 711
 712	fileMenu->addSeparator();
 713	QAction* multiWindow = new QAction(tr("New multiplayer window"), fileMenu);
 714	connect(multiWindow, &QAction::triggered, [this]() {
 715		std::shared_ptr<MultiplayerController> multiplayer = m_controller->multiplayerController();
 716		if (!multiplayer) {
 717			multiplayer = std::make_shared<MultiplayerController>();
 718			m_controller->setMultiplayerController(multiplayer);
 719		}
 720		Window* w2 = new Window(m_config, multiplayer->attached());
 721		w2->setAttribute(Qt::WA_DeleteOnClose);
 722#ifndef Q_OS_MAC
 723		w2->show();
 724#endif
 725		w2->loadConfig();
 726		w2->controller()->setMultiplayerController(multiplayer);
 727#ifdef Q_OS_MAC
 728		w2->show();
 729#endif
 730	});
 731	addControlledAction(fileMenu, multiWindow, "multiWindow");
 732
 733#ifndef Q_OS_MAC
 734	addControlledAction(fileMenu, fileMenu->addAction(tr("E&xit"), this, SLOT(close()), QKeySequence::Quit), "quit");
 735#endif
 736
 737	QMenu* emulationMenu = menubar->addMenu(tr("&Emulation"));
 738	m_shortcutController->addMenu(emulationMenu);
 739	QAction* reset = new QAction(tr("&Reset"), emulationMenu);
 740	reset->setShortcut(tr("Ctrl+R"));
 741	connect(reset, SIGNAL(triggered()), m_controller, SLOT(reset()));
 742	m_gameActions.append(reset);
 743	addControlledAction(emulationMenu, reset, "reset");
 744
 745	QAction* shutdown = new QAction(tr("Sh&utdown"), emulationMenu);
 746	connect(shutdown, SIGNAL(triggered()), m_controller, SLOT(closeGame()));
 747	m_gameActions.append(shutdown);
 748	addControlledAction(emulationMenu, shutdown, "shutdown");
 749	emulationMenu->addSeparator();
 750
 751	QAction* pause = new QAction(tr("&Pause"), emulationMenu);
 752	pause->setChecked(false);
 753	pause->setCheckable(true);
 754	pause->setShortcut(tr("Ctrl+P"));
 755	connect(pause, SIGNAL(triggered(bool)), m_controller, SLOT(setPaused(bool)));
 756	connect(m_controller, &GameController::gamePaused, [this, pause]() {
 757		pause->setChecked(true);
 758
 759		QImage currentImage(reinterpret_cast<const uchar*>(m_controller->drawContext()), VIDEO_HORIZONTAL_PIXELS, VIDEO_VERTICAL_PIXELS, 1024, QImage::Format_RGB32);
 760		QPixmap pixmap;
 761		pixmap.convertFromImage(currentImage.rgbSwapped());
 762		m_screenWidget->setPixmap(pixmap);
 763		m_screenWidget->setLockAspectRatio(3, 2);
 764	});
 765	connect(m_controller, &GameController::gameUnpaused, [pause]() { pause->setChecked(false); });
 766	m_gameActions.append(pause);
 767	addControlledAction(emulationMenu, pause, "pause");
 768
 769	QAction* frameAdvance = new QAction(tr("&Next frame"), emulationMenu);
 770	frameAdvance->setShortcut(tr("Ctrl+N"));
 771	connect(frameAdvance, SIGNAL(triggered()), m_controller, SLOT(frameAdvance()));
 772	m_gameActions.append(frameAdvance);
 773	addControlledAction(emulationMenu, frameAdvance, "frameAdvance");
 774
 775	emulationMenu->addSeparator();
 776
 777	m_shortcutController->addFunctions(emulationMenu, [this]() {
 778		m_controller->setTurbo(true, false);
 779	}, [this]() {
 780		m_controller->setTurbo(false, false);
 781	}, QKeySequence(Qt::Key_Tab), tr("Fast forward (held)"), "holdFastForward");
 782
 783	QAction* turbo = new QAction(tr("&Fast forward"), emulationMenu);
 784	turbo->setCheckable(true);
 785	turbo->setChecked(false);
 786	turbo->setShortcut(tr("Shift+Tab"));
 787	connect(turbo, SIGNAL(triggered(bool)), m_controller, SLOT(setTurbo(bool)));
 788	addControlledAction(emulationMenu, turbo, "fastForward");
 789
 790	QAction* rewind = new QAction(tr("Re&wind"), emulationMenu);
 791	rewind->setShortcut(tr("`"));
 792	connect(rewind, SIGNAL(triggered()), m_controller, SLOT(rewind()));
 793	m_gameActions.append(rewind);
 794	addControlledAction(emulationMenu, rewind, "rewind");
 795
 796	QAction* frameRewind = new QAction(tr("Step backwards"), emulationMenu);
 797	frameRewind->setShortcut(tr("Ctrl+B"));
 798	connect(frameRewind, &QAction::triggered, [this] () {
 799		m_controller->rewind(1);
 800	});
 801	m_gameActions.append(frameRewind);
 802	addControlledAction(emulationMenu, frameRewind, "frameRewind");
 803
 804	ConfigOption* videoSync = m_config->addOption("videoSync");
 805	videoSync->addBoolean(tr("Sync to &video"), emulationMenu);
 806	videoSync->connect([this](const QVariant& value) {
 807		m_controller->setVideoSync(value.toBool());
 808	}, this);
 809	m_config->updateOption("videoSync");
 810
 811	ConfigOption* audioSync = m_config->addOption("audioSync");
 812	audioSync->addBoolean(tr("Sync to &audio"), emulationMenu);
 813	audioSync->connect([this](const QVariant& value) {
 814		m_controller->setAudioSync(value.toBool());
 815	}, this);
 816	m_config->updateOption("audioSync");
 817
 818	emulationMenu->addSeparator();
 819
 820	QMenu* solarMenu = emulationMenu->addMenu(tr("Solar sensor"));
 821	m_shortcutController->addMenu(solarMenu);
 822	QAction* solarIncrease = new QAction(tr("Increase solar level"), solarMenu);
 823	connect(solarIncrease, SIGNAL(triggered()), m_controller, SLOT(increaseLuminanceLevel()));
 824	addControlledAction(solarMenu, solarIncrease, "increaseLuminanceLevel");
 825
 826	QAction* solarDecrease = new QAction(tr("Decrease solar level"), solarMenu);
 827	connect(solarDecrease, SIGNAL(triggered()), m_controller, SLOT(decreaseLuminanceLevel()));
 828	addControlledAction(solarMenu, solarDecrease, "decreaseLuminanceLevel");
 829
 830	QAction* maxSolar = new QAction(tr("Brightest solar level"), solarMenu);
 831	connect(maxSolar, &QAction::triggered, [this]() { m_controller->setLuminanceLevel(10); });
 832	addControlledAction(solarMenu, maxSolar, "maxLuminanceLevel");
 833
 834	QAction* minSolar = new QAction(tr("Darkest solar level"), solarMenu);
 835	connect(minSolar, &QAction::triggered, [this]() { m_controller->setLuminanceLevel(0); });
 836	addControlledAction(solarMenu, minSolar, "minLuminanceLevel");
 837
 838	solarMenu->addSeparator();
 839	for (int i = 0; i <= 10; ++i) {
 840		QAction* setSolar = new QAction(tr("Brightness %1").arg(QString::number(i)), solarMenu);
 841		connect(setSolar, &QAction::triggered, [this, i]() {
 842			m_controller->setLuminanceLevel(i);
 843		});
 844		addControlledAction(solarMenu, setSolar, QString("luminanceLevel.%1").arg(QString::number(i)));
 845	}
 846
 847	QMenu* avMenu = menubar->addMenu(tr("Audio/&Video"));
 848	m_shortcutController->addMenu(avMenu);
 849	QMenu* frameMenu = avMenu->addMenu(tr("Frame size"));
 850	m_shortcutController->addMenu(frameMenu, avMenu);
 851	for (int i = 1; i <= 6; ++i) {
 852		QAction* setSize = new QAction(tr("%1x").arg(QString::number(i)), avMenu);
 853		connect(setSize, &QAction::triggered, [this, i]() {
 854			showNormal();
 855			resizeFrame(VIDEO_HORIZONTAL_PIXELS * i, VIDEO_VERTICAL_PIXELS * i);
 856		});
 857		addControlledAction(frameMenu, setSize, QString("frame%1x").arg(QString::number(i)));
 858	}
 859	addControlledAction(frameMenu, frameMenu->addAction(tr("Fullscreen"), this, SLOT(toggleFullScreen()), QKeySequence("Ctrl+F")), "fullscreen");
 860
 861	ConfigOption* lockAspectRatio = m_config->addOption("lockAspectRatio");
 862	lockAspectRatio->addBoolean(tr("Lock aspect ratio"), avMenu);
 863	lockAspectRatio->connect([this](const QVariant& value) {
 864		m_display->lockAspectRatio(value.toBool());
 865	}, this);
 866	m_config->updateOption("lockAspectRatio");
 867
 868	ConfigOption* resampleVideo = m_config->addOption("resampleVideo");
 869	resampleVideo->addBoolean(tr("Resample video"), avMenu);
 870	resampleVideo->connect([this](const QVariant& value) {
 871		m_display->filter(value.toBool());
 872	}, this);
 873	m_config->updateOption("resampleVideo");
 874
 875	QMenu* skipMenu = avMenu->addMenu(tr("Frame&skip"));
 876	ConfigOption* skip = m_config->addOption("frameskip");
 877	skip->connect([this](const QVariant& value) {
 878		m_controller->setFrameskip(value.toInt());
 879	}, this);
 880	for (int i = 0; i <= 10; ++i) {
 881		skip->addValue(QString::number(i), i, skipMenu);
 882	}
 883	m_config->updateOption("frameskip");
 884
 885	avMenu->addSeparator();
 886
 887	QMenu* buffersMenu = avMenu->addMenu(tr("Audio buffer &size"));
 888	ConfigOption* buffers = m_config->addOption("audioBuffers");
 889	buffers->connect([this](const QVariant& value) {
 890		emit audioBufferSamplesChanged(value.toInt());
 891	}, this);
 892	buffers->addValue(tr("512"), 512, buffersMenu);
 893	buffers->addValue(tr("768"), 768, buffersMenu);
 894	buffers->addValue(tr("1024"), 1024, buffersMenu);
 895	buffers->addValue(tr("2048"), 2048, buffersMenu);
 896	buffers->addValue(tr("4096"), 4096, buffersMenu);
 897	m_config->updateOption("audioBuffers");
 898
 899	avMenu->addSeparator();
 900
 901	QMenu* target = avMenu->addMenu(tr("FPS target"));
 902	ConfigOption* fpsTargetOption = m_config->addOption("fpsTarget");
 903	fpsTargetOption->connect([this](const QVariant& value) {
 904		emit fpsTargetChanged(value.toFloat());
 905	}, this);
 906	fpsTargetOption->addValue(tr("15"), 15, target);
 907	fpsTargetOption->addValue(tr("30"), 30, target);
 908	fpsTargetOption->addValue(tr("45"), 45, target);
 909	fpsTargetOption->addValue(tr("Native (59.7)"), float(GBA_ARM7TDMI_FREQUENCY) / float(VIDEO_TOTAL_LENGTH), target);
 910	fpsTargetOption->addValue(tr("60"), 60, target);
 911	fpsTargetOption->addValue(tr("90"), 90, target);
 912	fpsTargetOption->addValue(tr("120"), 120, target);
 913	fpsTargetOption->addValue(tr("240"), 240, target);
 914	m_config->updateOption("fpsTarget");
 915
 916#if defined(USE_PNG) || defined(USE_FFMPEG) || defined(USE_MAGICK)
 917	avMenu->addSeparator();
 918#endif
 919
 920#ifdef USE_PNG
 921	QAction* screenshot = new QAction(tr("Take &screenshot"), avMenu);
 922	screenshot->setShortcut(tr("F12"));
 923	connect(screenshot, SIGNAL(triggered()), m_controller, SLOT(screenshot()));
 924	m_gameActions.append(screenshot);
 925	addControlledAction(avMenu, screenshot, "screenshot");
 926#endif
 927
 928#ifdef USE_FFMPEG
 929	QAction* recordOutput = new QAction(tr("Record output..."), avMenu);
 930	recordOutput->setShortcut(tr("F11"));
 931	connect(recordOutput, SIGNAL(triggered()), this, SLOT(openVideoWindow()));
 932	addControlledAction(avMenu, recordOutput, "recordOutput");
 933#endif
 934
 935#ifdef USE_MAGICK
 936	QAction* recordGIF = new QAction(tr("Record GIF..."), avMenu);
 937	recordGIF->setShortcut(tr("Shift+F11"));
 938	connect(recordGIF, SIGNAL(triggered()), this, SLOT(openGIFWindow()));
 939	addControlledAction(avMenu, recordGIF, "recordGIF");
 940#endif
 941
 942	avMenu->addSeparator();
 943	QMenu* videoLayers = avMenu->addMenu(tr("Video layers"));
 944
 945	for (int i = 0; i < 4; ++i) {
 946		QAction* enableBg = new QAction(tr("Background %0").arg(i), videoLayers);
 947		enableBg->setCheckable(true);
 948		enableBg->setChecked(true);
 949		connect(enableBg, &QAction::triggered, [this, i](bool enable) { m_controller->thread()->gba->video.renderer->disableBG[i] = !enable; });
 950		m_gameActions.append(enableBg);
 951		addControlledAction(videoLayers, enableBg, QString("enableBG%0").arg(i));
 952	}
 953
 954	QAction* enableObj = new QAction(tr("OBJ (sprites)"), videoLayers);
 955	enableObj->setCheckable(true);
 956	enableObj->setChecked(true);
 957	connect(enableObj, &QAction::triggered, [this](bool enable) { m_controller->thread()->gba->video.renderer->disableOBJ = !enable; });
 958	m_gameActions.append(enableObj);
 959	addControlledAction(videoLayers, enableObj, "enableOBJ");
 960
 961	QMenu* audioChannels = avMenu->addMenu(tr("Audio channels"));
 962
 963	for (int i = 0; i < 4; ++i) {
 964		QAction* enableCh = new QAction(tr("Channel %0").arg(i + 1), audioChannels);
 965		enableCh->setCheckable(true);
 966		enableCh->setChecked(true);
 967		connect(enableCh, &QAction::triggered, [this, i](bool enable) { m_controller->thread()->gba->audio.forceDisableCh[i] = !enable; });
 968		m_gameActions.append(enableCh);
 969		addControlledAction(audioChannels, enableCh, QString("enableCh%0").arg(i + 1));
 970	}
 971
 972	QAction* enableChA = new QAction(tr("Channel A"), audioChannels);
 973	enableChA->setCheckable(true);
 974	enableChA->setChecked(true);
 975	connect(enableChA, &QAction::triggered, [this, i](bool enable) { m_controller->thread()->gba->audio.forceDisableChA = !enable; });
 976	m_gameActions.append(enableChA);
 977	addControlledAction(audioChannels, enableChA, QString("enableChA"));
 978
 979	QAction* enableChB = new QAction(tr("Channel B"), audioChannels);
 980	enableChB->setCheckable(true);
 981	enableChB->setChecked(true);
 982	connect(enableChB, &QAction::triggered, [this, i](bool enable) { m_controller->thread()->gba->audio.forceDisableChB = !enable; });
 983	m_gameActions.append(enableChB);
 984	addControlledAction(audioChannels, enableChB, QString("enableChB"));
 985
 986	QMenu* toolsMenu = menubar->addMenu(tr("&Tools"));
 987	m_shortcutController->addMenu(toolsMenu);
 988	QAction* viewLogs = new QAction(tr("View &logs..."), toolsMenu);
 989	connect(viewLogs, SIGNAL(triggered()), m_logView, SLOT(show()));
 990	addControlledAction(toolsMenu, viewLogs, "viewLogs");
 991
 992	QAction* overrides = new QAction(tr("Game &overrides..."), toolsMenu);
 993	connect(overrides, SIGNAL(triggered()), this, SLOT(openOverrideWindow()));
 994	addControlledAction(toolsMenu, overrides, "overrideWindow");
 995
 996	QAction* sensors = new QAction(tr("Game &Pak sensors..."), toolsMenu);
 997	connect(sensors, SIGNAL(triggered()), this, SLOT(openSensorWindow()));
 998	addControlledAction(toolsMenu, sensors, "sensorWindow");
 999
1000	QAction* cheats = new QAction(tr("&Cheats..."), toolsMenu);
1001	connect(cheats, SIGNAL(triggered()), this, SLOT(openCheatsWindow()));
1002	addControlledAction(toolsMenu, cheats, "cheatsWindow");
1003
1004#ifdef USE_GDB_STUB
1005	QAction* gdbWindow = new QAction(tr("Start &GDB server..."), toolsMenu);
1006	connect(gdbWindow, SIGNAL(triggered()), this, SLOT(gdbOpen()));
1007	addControlledAction(toolsMenu, gdbWindow, "gdbWindow");
1008#endif
1009
1010	toolsMenu->addSeparator();
1011	addControlledAction(toolsMenu, toolsMenu->addAction(tr("Settings..."), this, SLOT(openSettingsWindow())), "settings");
1012	addControlledAction(toolsMenu, toolsMenu->addAction(tr("Edit shortcuts..."), this, SLOT(openShortcutWindow())), "shortcuts");
1013
1014	QAction* keymap = new QAction(tr("Remap keyboard..."), toolsMenu);
1015	connect(keymap, SIGNAL(triggered()), this, SLOT(openKeymapWindow()));
1016	addControlledAction(toolsMenu, keymap, "remapKeyboard");
1017
1018#ifdef BUILD_SDL
1019	QAction* gamepad = new QAction(tr("Remap gamepad..."), toolsMenu);
1020	connect(gamepad, SIGNAL(triggered()), this, SLOT(openGamepadWindow()));
1021	addControlledAction(toolsMenu, gamepad, "remapGamepad");
1022#endif
1023
1024	toolsMenu->addSeparator();
1025
1026	QAction* paletteView = new QAction(tr("View &palette..."), toolsMenu);
1027	connect(paletteView, SIGNAL(triggered()), this, SLOT(openPaletteWindow()));
1028	m_gameActions.append(paletteView);
1029	addControlledAction(toolsMenu, paletteView, "paletteWindow");
1030
1031	QAction* memoryView = new QAction(tr("View memory..."), toolsMenu);
1032	connect(memoryView, SIGNAL(triggered()), this, SLOT(openMemoryWindow()));
1033	m_gameActions.append(memoryView);
1034	addControlledAction(toolsMenu, memoryView, "memoryView");
1035
1036	ConfigOption* skipBios = m_config->addOption("skipBios");
1037	skipBios->connect([this](const QVariant& value) {
1038		m_controller->setSkipBIOS(value.toBool());
1039	}, this);
1040
1041	ConfigOption* volume = m_config->addOption("volume");
1042	volume->connect([this](const QVariant& value) {
1043		m_controller->setVolume(value.toInt());
1044	}, this);
1045
1046	ConfigOption* mute = m_config->addOption("mute");
1047	mute->connect([this](const QVariant& value) {
1048		m_controller->setMute(value.toBool());
1049	}, this);
1050
1051	ConfigOption* rewindEnable = m_config->addOption("rewindEnable");
1052	rewindEnable->connect([this](const QVariant& value) {
1053		m_controller->setRewind(value.toBool(), m_config->getOption("rewindBufferCapacity").toInt(), m_config->getOption("rewindBufferInterval").toInt());
1054	}, this);
1055
1056	ConfigOption* rewindBufferCapacity = m_config->addOption("rewindBufferCapacity");
1057	rewindBufferCapacity->connect([this](const QVariant& value) {
1058		m_controller->setRewind(m_config->getOption("rewindEnable").toInt(), value.toInt(), m_config->getOption("rewindBufferInterval").toInt());
1059	}, this);
1060
1061	ConfigOption* rewindBufferInterval = m_config->addOption("rewindBufferInterval");
1062	rewindBufferInterval->connect([this](const QVariant& value) {
1063		m_controller->setRewind(m_config->getOption("rewindEnable").toInt(), m_config->getOption("rewindBufferCapacity").toInt(), value.toInt());
1064	}, this);
1065
1066	ConfigOption* allowOpposingDirections = m_config->addOption("allowOpposingDirections");
1067	allowOpposingDirections->connect([this](const QVariant& value) {
1068		m_inputController.setAllowOpposing(value.toBool());
1069	}, this);
1070
1071	QAction* exitFullScreen = new QAction(tr("Exit fullscreen"), frameMenu);
1072	connect(exitFullScreen, SIGNAL(triggered()), this, SLOT(exitFullScreen()));
1073	exitFullScreen->setShortcut(QKeySequence("Esc"));
1074	addHiddenAction(frameMenu, exitFullScreen, "exitFullScreen");
1075
1076	foreach (QAction* action, m_gameActions) {
1077		action->setDisabled(true);
1078	}
1079}
1080
1081void Window::attachWidget(QWidget* widget) {
1082	m_screenWidget->layout()->addWidget(widget);
1083	static_cast<QStackedLayout*>(m_screenWidget->layout())->setCurrentWidget(widget);
1084}
1085
1086void Window::detachWidget(QWidget* widget) {
1087	m_screenWidget->layout()->removeWidget(widget);
1088}
1089
1090void Window::appendMRU(const QString& fname) {
1091	int index = m_mruFiles.indexOf(fname);
1092	if (index >= 0) {
1093		m_mruFiles.removeAt(index);
1094	}
1095	m_mruFiles.prepend(fname);
1096	while (m_mruFiles.size() > ConfigController::MRU_LIST_SIZE) {
1097		m_mruFiles.removeLast();
1098	}
1099	updateMRU();
1100}
1101
1102void Window::updateMRU() {
1103	if (!m_mruMenu) {
1104		return;
1105	}
1106	m_mruMenu->clear();
1107	int i = 0;
1108	for (const QString& file : m_mruFiles) {
1109		QAction* item = new QAction(file, m_mruMenu);
1110		item->setShortcut(QString("Ctrl+%1").arg(i));
1111		connect(item, &QAction::triggered, [this, file]() { m_controller->loadGame(file); });
1112		m_mruMenu->addAction(item);
1113		++i;
1114	}
1115	m_config->setMRU(m_mruFiles);
1116	m_config->write();
1117	m_mruMenu->setEnabled(i > 0);
1118}
1119
1120QAction* Window::addControlledAction(QMenu* menu, QAction* action, const QString& name) {
1121	addHiddenAction(menu, action, name);
1122	menu->addAction(action);
1123	return action;
1124}
1125
1126QAction* Window::addHiddenAction(QMenu* menu, QAction* action, const QString& name) {
1127	m_shortcutController->addAction(menu, action, name);
1128	action->setShortcutContext(Qt::WidgetShortcut);
1129	addAction(action);
1130	return action;
1131}
1132
1133WindowBackground::WindowBackground(QWidget* parent)
1134	: QLabel(parent)
1135{
1136	setLayout(new QStackedLayout());
1137	layout()->setContentsMargins(0, 0, 0, 0);
1138	setAlignment(Qt::AlignCenter);
1139}
1140
1141void WindowBackground::setSizeHint(const QSize& hint) {
1142	m_sizeHint = hint;
1143}
1144
1145QSize WindowBackground::sizeHint() const {
1146	return m_sizeHint;
1147}
1148
1149void WindowBackground::setLockAspectRatio(int width, int height) {
1150	m_aspectWidth = width;
1151	m_aspectHeight = height;
1152}
1153
1154void WindowBackground::paintEvent(QPaintEvent*) {
1155	const QPixmap* logo = pixmap();
1156	if (!logo) {
1157		return;
1158	}
1159	QPainter painter(this);
1160	painter.setRenderHint(QPainter::SmoothPixmapTransform);
1161	painter.fillRect(QRect(QPoint(), size()), Qt::black);
1162	QSize s = size();
1163	QSize ds = s;
1164	if (s.width() * m_aspectHeight > s.height() * m_aspectWidth) {
1165		ds.setWidth(s.height() * m_aspectWidth / m_aspectHeight);
1166	} else if (s.width() * m_aspectHeight < s.height() * m_aspectWidth) {
1167		ds.setHeight(s.width() * m_aspectHeight / m_aspectWidth);
1168	}
1169	QPoint origin = QPoint((s.width() - ds.width()) / 2, (s.height() - ds.height()) / 2);
1170	QRect full(origin, ds);
1171	painter.drawPixmap(full, *logo);
1172}