all repos — mgba @ e2b964a8be5efb850368c52ee08c785eba26c6d7

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