all repos — mgba @ 57e84f0c6938a1e5797a15cce88a6565dff77ba3

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