all repos — mgba @ 4d5c1f98497b90e5abb79bdaf7af0c0ad5b606bf

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