all repos — mgba @ 9911484aee8778d4c1f1eab597d5cd8625ba9848

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