all repos — mgba @ 8a66ee0d5673ff5f701fd3b3bf73876da2aeefcd

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