all repos — mgba @ 0378fa229d817abe2128e920e7091e53e1e0919f

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