all repos — mgba @ 3c9433b74ca1203003481b4f142010b240599375

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::recordFrame() {
 565	m_frameList.append(QDateTime::currentDateTime());
 566	while (m_frameList.count() > FRAME_LIST_SIZE) {
 567		m_frameList.removeFirst();
 568	}
 569}
 570
 571void Window::showFPS() {
 572	if (m_frameList.isEmpty()) {
 573		updateTitle();
 574		return;
 575	}
 576	qint64 interval = m_frameList.first().msecsTo(m_frameList.last());
 577	float fps = (m_frameList.count() - 1) * 10000.f / interval;
 578	fps = round(fps) / 10.f;
 579	updateTitle(fps);
 580}
 581
 582void Window::updateTitle(float fps) {
 583	QString title;
 584
 585	m_controller->threadInterrupt();
 586	if (m_controller->isLoaded()) {
 587		char gameTitle[13] = { '\0' };
 588		GBAGetGameTitle(m_controller->thread()->gba, gameTitle);
 589
 590		title = (gameTitle);
 591	}
 592	MultiplayerController* multiplayer = m_controller->multiplayerController();
 593	if (multiplayer && multiplayer->attached() > 1) {
 594		title += tr(" -  Player %1 of %2").arg(m_playerId + 1).arg(multiplayer->attached());
 595	}
 596	m_controller->threadContinue();
 597	if (title.isNull()) {
 598		setWindowTitle(tr("%1 - %2").arg(projectName).arg(projectVersion));
 599	} else if (isnan(fps)) {
 600		setWindowTitle(tr("%1 - %2 - %3").arg(projectName).arg(title).arg(projectVersion));
 601	} else {
 602		setWindowTitle(tr("%1 - %2 (%3 fps) - %4").arg(projectName).arg(title).arg(fps).arg(projectVersion));
 603	}
 604}
 605
 606void Window::openStateWindow(LoadSave ls) {
 607	if (m_stateWindow) {
 608		return;
 609	}
 610	bool wasPaused = m_controller->isPaused();
 611	m_stateWindow = new LoadSaveState(m_controller);
 612	connect(this, SIGNAL(shutdown()), m_stateWindow, SLOT(close()));
 613	connect(m_controller, SIGNAL(gameStopped(GBAThread*)), m_stateWindow, SLOT(close()));
 614	connect(m_stateWindow, &LoadSaveState::closed, [this]() {
 615		m_screenWidget->layout()->removeWidget(m_stateWindow);
 616		m_stateWindow = nullptr;
 617		QMetaObject::invokeMethod(this, "setFocus", Qt::QueuedConnection);
 618	});
 619	if (!wasPaused) {
 620		m_controller->setPaused(true);
 621		connect(m_stateWindow, &LoadSaveState::closed, [this]() { m_controller->setPaused(false); });
 622	}
 623	m_stateWindow->setAttribute(Qt::WA_DeleteOnClose);
 624	m_stateWindow->setMode(ls);
 625	attachWidget(m_stateWindow);
 626}
 627
 628void Window::setupMenu(QMenuBar* menubar) {
 629	menubar->clear();
 630	QMenu* fileMenu = menubar->addMenu(tr("&File"));
 631	m_shortcutController->addMenu(fileMenu);
 632	installEventFilter(m_shortcutController);
 633	addControlledAction(fileMenu, fileMenu->addAction(tr("Load &ROM..."), this, SLOT(selectROM()), QKeySequence::Open),
 634	                    "loadROM");
 635	addControlledAction(fileMenu, fileMenu->addAction(tr("Load &BIOS..."), this, SLOT(selectBIOS())), "loadBIOS");
 636	addControlledAction(fileMenu, fileMenu->addAction(tr("Load &patch..."), this, SLOT(selectPatch())), "loadPatch");
 637	addControlledAction(fileMenu, fileMenu->addAction(tr("Boot BIOS"), m_controller, SLOT(bootBIOS())), "bootBIOS");
 638
 639	addControlledAction(fileMenu, fileMenu->addAction(tr("Replace ROM..."), this, SLOT(replaceROM())), "replaceROM");
 640
 641	m_mruMenu = fileMenu->addMenu(tr("Recent"));
 642
 643	fileMenu->addSeparator();
 644
 645	QAction* loadState = new QAction(tr("&Load state"), fileMenu);
 646	loadState->setShortcut(tr("F10"));
 647	connect(loadState, &QAction::triggered, [this]() { this->openStateWindow(LoadSave::LOAD); });
 648	m_gameActions.append(loadState);
 649	addControlledAction(fileMenu, loadState, "loadState");
 650
 651	QAction* saveState = new QAction(tr("&Save state"), fileMenu);
 652	saveState->setShortcut(tr("Shift+F10"));
 653	connect(saveState, &QAction::triggered, [this]() { this->openStateWindow(LoadSave::SAVE); });
 654	m_gameActions.append(saveState);
 655	addControlledAction(fileMenu, saveState, "saveState");
 656
 657	QMenu* quickLoadMenu = fileMenu->addMenu(tr("Quick load"));
 658	QMenu* quickSaveMenu = fileMenu->addMenu(tr("Quick save"));
 659	m_shortcutController->addMenu(quickLoadMenu);
 660	m_shortcutController->addMenu(quickSaveMenu);
 661
 662	QAction* quickLoad = new QAction(tr("Load recent"), quickLoadMenu);
 663	connect(quickLoad, SIGNAL(triggered()), m_controller, SLOT(loadState()));
 664	m_gameActions.append(quickLoad);
 665	addControlledAction(quickLoadMenu, quickLoad, "quickLoad");
 666
 667	QAction* quickSave = new QAction(tr("Save recent"), quickSaveMenu);
 668	connect(quickSave, SIGNAL(triggered()), m_controller, SLOT(saveState()));
 669	m_gameActions.append(quickSave);
 670	addControlledAction(quickSaveMenu, quickSave, "quickSave");
 671
 672	quickLoadMenu->addSeparator();
 673	quickSaveMenu->addSeparator();
 674
 675	int i;
 676	for (i = 1; i < 10; ++i) {
 677		quickLoad = new QAction(tr("State &%1").arg(i), quickLoadMenu);
 678		quickLoad->setShortcut(tr("F%1").arg(i));
 679		connect(quickLoad, &QAction::triggered, [this, i]() { m_controller->loadState(i); });
 680		m_gameActions.append(quickLoad);
 681		addControlledAction(quickLoadMenu, quickLoad, QString("quickLoad.%1").arg(i));
 682
 683		quickSave = new QAction(tr("State &%1").arg(i), quickSaveMenu);
 684		quickSave->setShortcut(tr("Shift+F%1").arg(i));
 685		connect(quickSave, &QAction::triggered, [this, i]() { m_controller->saveState(i); });
 686		m_gameActions.append(quickSave);
 687		addControlledAction(quickSaveMenu, quickSave, QString("quickSave.%1").arg(i));
 688	}
 689
 690	fileMenu->addSeparator();
 691	QAction* importShark = new QAction(tr("Import GameShark Save"), fileMenu);
 692	connect(importShark, SIGNAL(triggered()), this, SLOT(importSharkport()));
 693	m_gameActions.append(importShark);
 694	addControlledAction(fileMenu, importShark, "importShark");
 695
 696	QAction* exportShark = new QAction(tr("Export GameShark Save"), fileMenu);
 697	connect(exportShark, SIGNAL(triggered()), this, SLOT(exportSharkport()));
 698	m_gameActions.append(exportShark);
 699	addControlledAction(fileMenu, exportShark, "exportShark");
 700
 701	fileMenu->addSeparator();
 702	QAction* multiWindow = new QAction(tr("New multiplayer window"), fileMenu);
 703	connect(multiWindow, &QAction::triggered, [this]() {
 704		GBAApp::app()->newWindow();
 705	});
 706	addControlledAction(fileMenu, multiWindow, "multiWindow");
 707
 708#ifndef Q_OS_MAC
 709	addControlledAction(fileMenu, fileMenu->addAction(tr("E&xit"), this, SLOT(close()), QKeySequence::Quit), "quit");
 710#endif
 711
 712	QMenu* emulationMenu = menubar->addMenu(tr("&Emulation"));
 713	m_shortcutController->addMenu(emulationMenu);
 714	QAction* reset = new QAction(tr("&Reset"), emulationMenu);
 715	reset->setShortcut(tr("Ctrl+R"));
 716	connect(reset, SIGNAL(triggered()), m_controller, SLOT(reset()));
 717	m_gameActions.append(reset);
 718	addControlledAction(emulationMenu, reset, "reset");
 719
 720	QAction* shutdown = new QAction(tr("Sh&utdown"), emulationMenu);
 721	connect(shutdown, SIGNAL(triggered()), m_controller, SLOT(closeGame()));
 722	m_gameActions.append(shutdown);
 723	addControlledAction(emulationMenu, shutdown, "shutdown");
 724
 725	QAction* yank = new QAction(tr("Yank game pak"), emulationMenu);
 726	connect(yank, SIGNAL(triggered()), m_controller, SLOT(yankPak()));
 727	m_gameActions.append(yank);
 728	addControlledAction(emulationMenu, yank, "yank");
 729	emulationMenu->addSeparator();
 730
 731	QAction* pause = new QAction(tr("&Pause"), emulationMenu);
 732	pause->setChecked(false);
 733	pause->setCheckable(true);
 734	pause->setShortcut(tr("Ctrl+P"));
 735	connect(pause, SIGNAL(triggered(bool)), m_controller, SLOT(setPaused(bool)));
 736	connect(m_controller, &GameController::gamePaused, [this, pause]() {
 737		pause->setChecked(true);
 738
 739		QImage currentImage(reinterpret_cast<const uchar*>(m_controller->drawContext()), VIDEO_HORIZONTAL_PIXELS,
 740		                    VIDEO_VERTICAL_PIXELS, 1024, QImage::Format_RGB32);
 741		QPixmap pixmap;
 742		pixmap.convertFromImage(currentImage.rgbSwapped());
 743		m_screenWidget->setPixmap(pixmap);
 744		m_screenWidget->setLockAspectRatio(3, 2);
 745	});
 746	connect(m_controller, &GameController::gameUnpaused, [pause]() { pause->setChecked(false); });
 747	m_gameActions.append(pause);
 748	addControlledAction(emulationMenu, pause, "pause");
 749
 750	QAction* frameAdvance = new QAction(tr("&Next frame"), emulationMenu);
 751	frameAdvance->setShortcut(tr("Ctrl+N"));
 752	connect(frameAdvance, SIGNAL(triggered()), m_controller, SLOT(frameAdvance()));
 753	m_gameActions.append(frameAdvance);
 754	addControlledAction(emulationMenu, frameAdvance, "frameAdvance");
 755
 756	emulationMenu->addSeparator();
 757
 758	m_shortcutController->addFunctions(emulationMenu, [this]() {
 759		m_controller->setTurbo(true, false);
 760	}, [this]() {
 761		m_controller->setTurbo(false, false);
 762	}, QKeySequence(Qt::Key_Tab), tr("Fast forward (held)"), "holdFastForward");
 763
 764	QAction* turbo = new QAction(tr("&Fast forward"), emulationMenu);
 765	turbo->setCheckable(true);
 766	turbo->setChecked(false);
 767	turbo->setShortcut(tr("Shift+Tab"));
 768	connect(turbo, SIGNAL(triggered(bool)), m_controller, SLOT(setTurbo(bool)));
 769	addControlledAction(emulationMenu, turbo, "fastForward");
 770
 771	QMenu* ffspeedMenu = emulationMenu->addMenu(tr("Fast forward speed"));
 772	ConfigOption* ffspeed = m_config->addOption("fastForwardRatio");
 773	ffspeed->connect([this](const QVariant& value) {
 774		m_controller->setTurboSpeed(value.toFloat());
 775	}, this);
 776	ffspeed->addValue(tr("Unbounded"), -1.0f, ffspeedMenu);
 777	ffspeed->setValue(QVariant(-1.0f));
 778	ffspeedMenu->addSeparator();
 779	for (i = 2; i < 11; ++i) {
 780		ffspeed->addValue(tr("%0x").arg(i), i, ffspeedMenu);
 781	}
 782	m_config->updateOption("fastForwardRatio");
 783
 784	m_shortcutController->addFunctions(emulationMenu, [this]() {
 785		m_controller->startRewinding();
 786	}, [this]() {
 787		m_controller->stopRewinding();
 788	}, QKeySequence("~"), tr("Rewind (held)"), "holdRewind");
 789
 790	QAction* rewind = new QAction(tr("Re&wind"), emulationMenu);
 791	rewind->setShortcut(tr("`"));
 792	connect(rewind, SIGNAL(triggered()), m_controller, SLOT(rewind()));
 793	m_gameActions.append(rewind);
 794	addControlledAction(emulationMenu, rewind, "rewind");
 795
 796	QAction* frameRewind = new QAction(tr("Step backwards"), emulationMenu);
 797	frameRewind->setShortcut(tr("Ctrl+B"));
 798	connect(frameRewind, &QAction::triggered, [this] () {
 799		m_controller->rewind(1);
 800	});
 801	m_gameActions.append(frameRewind);
 802	addControlledAction(emulationMenu, frameRewind, "frameRewind");
 803
 804	ConfigOption* videoSync = m_config->addOption("videoSync");
 805	videoSync->addBoolean(tr("Sync to &video"), emulationMenu);
 806	videoSync->connect([this](const QVariant& value) {
 807		m_controller->setVideoSync(value.toBool());
 808	}, this);
 809	m_config->updateOption("videoSync");
 810
 811	ConfigOption* audioSync = m_config->addOption("audioSync");
 812	audioSync->addBoolean(tr("Sync to &audio"), emulationMenu);
 813	audioSync->connect([this](const QVariant& value) {
 814		m_controller->setAudioSync(value.toBool());
 815	}, this);
 816	m_config->updateOption("audioSync");
 817
 818	emulationMenu->addSeparator();
 819
 820	QMenu* solarMenu = emulationMenu->addMenu(tr("Solar sensor"));
 821	m_shortcutController->addMenu(solarMenu);
 822	QAction* solarIncrease = new QAction(tr("Increase solar level"), solarMenu);
 823	connect(solarIncrease, SIGNAL(triggered()), m_controller, SLOT(increaseLuminanceLevel()));
 824	addControlledAction(solarMenu, solarIncrease, "increaseLuminanceLevel");
 825
 826	QAction* solarDecrease = new QAction(tr("Decrease solar level"), solarMenu);
 827	connect(solarDecrease, SIGNAL(triggered()), m_controller, SLOT(decreaseLuminanceLevel()));
 828	addControlledAction(solarMenu, solarDecrease, "decreaseLuminanceLevel");
 829
 830	QAction* maxSolar = new QAction(tr("Brightest solar level"), solarMenu);
 831	connect(maxSolar, &QAction::triggered, [this]() { m_controller->setLuminanceLevel(10); });
 832	addControlledAction(solarMenu, maxSolar, "maxLuminanceLevel");
 833
 834	QAction* minSolar = new QAction(tr("Darkest solar level"), solarMenu);
 835	connect(minSolar, &QAction::triggered, [this]() { m_controller->setLuminanceLevel(0); });
 836	addControlledAction(solarMenu, minSolar, "minLuminanceLevel");
 837
 838	solarMenu->addSeparator();
 839	for (int i = 0; i <= 10; ++i) {
 840		QAction* setSolar = new QAction(tr("Brightness %1").arg(QString::number(i)), solarMenu);
 841		connect(setSolar, &QAction::triggered, [this, i]() {
 842			m_controller->setLuminanceLevel(i);
 843		});
 844		addControlledAction(solarMenu, setSolar, QString("luminanceLevel.%1").arg(QString::number(i)));
 845	}
 846
 847	QMenu* avMenu = menubar->addMenu(tr("Audio/&Video"));
 848	m_shortcutController->addMenu(avMenu);
 849	QMenu* frameMenu = avMenu->addMenu(tr("Frame size"));
 850	m_shortcutController->addMenu(frameMenu, avMenu);
 851	for (int i = 1; i <= 6; ++i) {
 852		QAction* setSize = new QAction(tr("%1x").arg(QString::number(i)), avMenu);
 853		connect(setSize, &QAction::triggered, [this, i]() {
 854			showNormal();
 855			resizeFrame(VIDEO_HORIZONTAL_PIXELS * i, VIDEO_VERTICAL_PIXELS * i);
 856		});
 857		addControlledAction(frameMenu, setSize, QString("frame%1x").arg(QString::number(i)));
 858	}
 859	QKeySequence fullscreenKeys;
 860#ifdef Q_OS_WIN
 861	fullscreenKeys = QKeySequence("Alt+Return");
 862#else
 863	fullscreenKeys = QKeySequence("Ctrl+F");
 864#endif
 865	addControlledAction(frameMenu, frameMenu->addAction(tr("Toggle fullscreen"), this, SLOT(toggleFullScreen()), fullscreenKeys), "fullscreen");
 866
 867	ConfigOption* lockAspectRatio = m_config->addOption("lockAspectRatio");
 868	lockAspectRatio->addBoolean(tr("Lock aspect ratio"), avMenu);
 869	lockAspectRatio->connect([this](const QVariant& value) {
 870		m_display->lockAspectRatio(value.toBool());
 871	}, this);
 872	m_config->updateOption("lockAspectRatio");
 873
 874	ConfigOption* resampleVideo = m_config->addOption("resampleVideo");
 875	resampleVideo->addBoolean(tr("Resample video"), avMenu);
 876	resampleVideo->connect([this](const QVariant& value) {
 877		m_display->filter(value.toBool());
 878	}, this);
 879	m_config->updateOption("resampleVideo");
 880
 881	QMenu* skipMenu = avMenu->addMenu(tr("Frame&skip"));
 882	ConfigOption* skip = m_config->addOption("frameskip");
 883	skip->connect([this](const QVariant& value) {
 884		m_controller->setFrameskip(value.toInt());
 885	}, this);
 886	for (int i = 0; i <= 10; ++i) {
 887		skip->addValue(QString::number(i), i, skipMenu);
 888	}
 889	m_config->updateOption("frameskip");
 890
 891	avMenu->addSeparator();
 892
 893	QMenu* buffersMenu = avMenu->addMenu(tr("Audio buffer &size"));
 894	ConfigOption* buffers = m_config->addOption("audioBuffers");
 895	buffers->connect([this](const QVariant& value) {
 896		emit audioBufferSamplesChanged(value.toInt());
 897	}, this);
 898	buffers->addValue(tr("512"), 512, buffersMenu);
 899	buffers->addValue(tr("768"), 768, buffersMenu);
 900	buffers->addValue(tr("1024"), 1024, buffersMenu);
 901	buffers->addValue(tr("2048"), 2048, buffersMenu);
 902	buffers->addValue(tr("4096"), 4096, buffersMenu);
 903	m_config->updateOption("audioBuffers");
 904
 905	avMenu->addSeparator();
 906
 907	QMenu* target = avMenu->addMenu(tr("FPS target"));
 908	ConfigOption* fpsTargetOption = m_config->addOption("fpsTarget");
 909	fpsTargetOption->connect([this](const QVariant& value) {
 910		emit fpsTargetChanged(value.toFloat());
 911	}, this);
 912	fpsTargetOption->addValue(tr("15"), 15, target);
 913	fpsTargetOption->addValue(tr("30"), 30, target);
 914	fpsTargetOption->addValue(tr("45"), 45, target);
 915	fpsTargetOption->addValue(tr("Native (59.7)"), float(GBA_ARM7TDMI_FREQUENCY) / float(VIDEO_TOTAL_LENGTH), target);
 916	fpsTargetOption->addValue(tr("60"), 60, target);
 917	fpsTargetOption->addValue(tr("90"), 90, target);
 918	fpsTargetOption->addValue(tr("120"), 120, target);
 919	fpsTargetOption->addValue(tr("240"), 240, target);
 920	m_config->updateOption("fpsTarget");
 921
 922#if defined(USE_PNG) || defined(USE_FFMPEG) || defined(USE_MAGICK)
 923	avMenu->addSeparator();
 924#endif
 925
 926#ifdef USE_PNG
 927	QAction* screenshot = new QAction(tr("Take &screenshot"), avMenu);
 928	screenshot->setShortcut(tr("F12"));
 929	connect(screenshot, SIGNAL(triggered()), m_controller, SLOT(screenshot()));
 930	m_gameActions.append(screenshot);
 931	addControlledAction(avMenu, screenshot, "screenshot");
 932#endif
 933
 934#ifdef USE_FFMPEG
 935	QAction* recordOutput = new QAction(tr("Record output..."), avMenu);
 936	recordOutput->setShortcut(tr("F11"));
 937	connect(recordOutput, SIGNAL(triggered()), this, SLOT(openVideoWindow()));
 938	addControlledAction(avMenu, recordOutput, "recordOutput");
 939#endif
 940
 941#ifdef USE_MAGICK
 942	QAction* recordGIF = new QAction(tr("Record GIF..."), avMenu);
 943	recordGIF->setShortcut(tr("Shift+F11"));
 944	connect(recordGIF, SIGNAL(triggered()), this, SLOT(openGIFWindow()));
 945	addControlledAction(avMenu, recordGIF, "recordGIF");
 946#endif
 947
 948	avMenu->addSeparator();
 949	QMenu* videoLayers = avMenu->addMenu(tr("Video layers"));
 950
 951	for (int i = 0; i < 4; ++i) {
 952		QAction* enableBg = new QAction(tr("Background %0").arg(i), videoLayers);
 953		enableBg->setCheckable(true);
 954		enableBg->setChecked(true);
 955		connect(enableBg, &QAction::triggered, [this, i](bool enable) { m_controller->thread()->gba->video.renderer->disableBG[i] = !enable; });
 956		m_gameActions.append(enableBg);
 957		addControlledAction(videoLayers, enableBg, QString("enableBG%0").arg(i));
 958	}
 959
 960	QAction* enableObj = new QAction(tr("OBJ (sprites)"), videoLayers);
 961	enableObj->setCheckable(true);
 962	enableObj->setChecked(true);
 963	connect(enableObj, &QAction::triggered, [this](bool enable) { m_controller->thread()->gba->video.renderer->disableOBJ = !enable; });
 964	m_gameActions.append(enableObj);
 965	addControlledAction(videoLayers, enableObj, "enableOBJ");
 966
 967	QMenu* audioChannels = avMenu->addMenu(tr("Audio channels"));
 968
 969	for (int i = 0; i < 4; ++i) {
 970		QAction* enableCh = new QAction(tr("Channel %0").arg(i + 1), audioChannels);
 971		enableCh->setCheckable(true);
 972		enableCh->setChecked(true);
 973		connect(enableCh, &QAction::triggered, [this, i](bool enable) { m_controller->thread()->gba->audio.forceDisableCh[i] = !enable; });
 974		m_gameActions.append(enableCh);
 975		addControlledAction(audioChannels, enableCh, QString("enableCh%0").arg(i + 1));
 976	}
 977
 978	QAction* enableChA = new QAction(tr("Channel A"), audioChannels);
 979	enableChA->setCheckable(true);
 980	enableChA->setChecked(true);
 981	connect(enableChA, &QAction::triggered, [this, i](bool enable) { m_controller->thread()->gba->audio.forceDisableChA = !enable; });
 982	m_gameActions.append(enableChA);
 983	addControlledAction(audioChannels, enableChA, QString("enableChA"));
 984
 985	QAction* enableChB = new QAction(tr("Channel B"), audioChannels);
 986	enableChB->setCheckable(true);
 987	enableChB->setChecked(true);
 988	connect(enableChB, &QAction::triggered, [this, i](bool enable) { m_controller->thread()->gba->audio.forceDisableChB = !enable; });
 989	m_gameActions.append(enableChB);
 990	addControlledAction(audioChannels, enableChB, QString("enableChB"));
 991
 992	QMenu* toolsMenu = menubar->addMenu(tr("&Tools"));
 993	m_shortcutController->addMenu(toolsMenu);
 994	QAction* viewLogs = new QAction(tr("View &logs..."), toolsMenu);
 995	connect(viewLogs, SIGNAL(triggered()), m_logView, SLOT(show()));
 996	addControlledAction(toolsMenu, viewLogs, "viewLogs");
 997
 998	QAction* overrides = new QAction(tr("Game &overrides..."), toolsMenu);
 999	connect(overrides, SIGNAL(triggered()), this, SLOT(openOverrideWindow()));
1000	addControlledAction(toolsMenu, overrides, "overrideWindow");
1001
1002	QAction* sensors = new QAction(tr("Game &Pak sensors..."), toolsMenu);
1003	connect(sensors, SIGNAL(triggered()), this, SLOT(openSensorWindow()));
1004	addControlledAction(toolsMenu, sensors, "sensorWindow");
1005
1006	QAction* cheats = new QAction(tr("&Cheats..."), toolsMenu);
1007	connect(cheats, SIGNAL(triggered()), this, SLOT(openCheatsWindow()));
1008	addControlledAction(toolsMenu, cheats, "cheatsWindow");
1009
1010#ifdef USE_GDB_STUB
1011	QAction* gdbWindow = new QAction(tr("Start &GDB server..."), toolsMenu);
1012	connect(gdbWindow, SIGNAL(triggered()), this, SLOT(gdbOpen()));
1013	addControlledAction(toolsMenu, gdbWindow, "gdbWindow");
1014#endif
1015
1016	toolsMenu->addSeparator();
1017	addControlledAction(toolsMenu, toolsMenu->addAction(tr("Settings..."), this, SLOT(openSettingsWindow())),
1018	                    "settings");
1019	addControlledAction(toolsMenu, toolsMenu->addAction(tr("Edit shortcuts..."), this, SLOT(openShortcutWindow())),
1020	                    "shortcuts");
1021
1022	QAction* keymap = new QAction(tr("Remap keyboard..."), toolsMenu);
1023	connect(keymap, SIGNAL(triggered()), this, SLOT(openKeymapWindow()));
1024	addControlledAction(toolsMenu, keymap, "remapKeyboard");
1025
1026#ifdef BUILD_SDL
1027	QAction* gamepad = new QAction(tr("Remap gamepad..."), toolsMenu);
1028	connect(gamepad, SIGNAL(triggered()), this, SLOT(openGamepadWindow()));
1029	addControlledAction(toolsMenu, gamepad, "remapGamepad");
1030#endif
1031
1032	toolsMenu->addSeparator();
1033
1034	QAction* paletteView = new QAction(tr("View &palette..."), toolsMenu);
1035	connect(paletteView, SIGNAL(triggered()), this, SLOT(openPaletteWindow()));
1036	m_gameActions.append(paletteView);
1037	addControlledAction(toolsMenu, paletteView, "paletteWindow");
1038
1039	QAction* memoryView = new QAction(tr("View memory..."), toolsMenu);
1040	connect(memoryView, SIGNAL(triggered()), this, SLOT(openMemoryWindow()));
1041	m_gameActions.append(memoryView);
1042	addControlledAction(toolsMenu, memoryView, "memoryView");
1043
1044	ConfigOption* skipBios = m_config->addOption("skipBios");
1045	skipBios->connect([this](const QVariant& value) {
1046		m_controller->setSkipBIOS(value.toBool());
1047	}, this);
1048
1049	ConfigOption* volume = m_config->addOption("volume");
1050	volume->connect([this](const QVariant& value) {
1051		m_controller->setVolume(value.toInt());
1052	}, this);
1053
1054	ConfigOption* mute = m_config->addOption("mute");
1055	mute->connect([this](const QVariant& value) {
1056		m_controller->setMute(value.toBool());
1057	}, this);
1058
1059	ConfigOption* rewindEnable = m_config->addOption("rewindEnable");
1060	rewindEnable->connect([this](const QVariant& value) {
1061		m_controller->setRewind(value.toBool(), m_config->getOption("rewindBufferCapacity").toInt(), m_config->getOption("rewindBufferInterval").toInt());
1062	}, this);
1063
1064	ConfigOption* rewindBufferCapacity = m_config->addOption("rewindBufferCapacity");
1065	rewindBufferCapacity->connect([this](const QVariant& value) {
1066		m_controller->setRewind(m_config->getOption("rewindEnable").toInt(), value.toInt(), m_config->getOption("rewindBufferInterval").toInt());
1067	}, this);
1068
1069	ConfigOption* rewindBufferInterval = m_config->addOption("rewindBufferInterval");
1070	rewindBufferInterval->connect([this](const QVariant& value) {
1071		m_controller->setRewind(m_config->getOption("rewindEnable").toInt(), m_config->getOption("rewindBufferCapacity").toInt(), value.toInt());
1072	}, this);
1073
1074	ConfigOption* allowOpposingDirections = m_config->addOption("allowOpposingDirections");
1075	allowOpposingDirections->connect([this](const QVariant& value) {
1076		m_inputController.setAllowOpposing(value.toBool());
1077	}, this);
1078
1079	QAction* exitFullScreen = new QAction(tr("Exit fullscreen"), frameMenu);
1080	connect(exitFullScreen, SIGNAL(triggered()), this, SLOT(exitFullScreen()));
1081	exitFullScreen->setShortcut(QKeySequence("Esc"));
1082	addHiddenAction(frameMenu, exitFullScreen, "exitFullScreen");
1083
1084	foreach (QAction* action, m_gameActions) {
1085		action->setDisabled(true);
1086	}
1087}
1088
1089void Window::attachWidget(QWidget* widget) {
1090	m_screenWidget->layout()->addWidget(widget);
1091	static_cast<QStackedLayout*>(m_screenWidget->layout())->setCurrentWidget(widget);
1092}
1093
1094void Window::detachWidget(QWidget* widget) {
1095	m_screenWidget->layout()->removeWidget(widget);
1096}
1097
1098void Window::appendMRU(const QString& fname) {
1099	int index = m_mruFiles.indexOf(fname);
1100	if (index >= 0) {
1101		m_mruFiles.removeAt(index);
1102	}
1103	m_mruFiles.prepend(fname);
1104	while (m_mruFiles.size() > ConfigController::MRU_LIST_SIZE) {
1105		m_mruFiles.removeLast();
1106	}
1107	updateMRU();
1108}
1109
1110void Window::updateMRU() {
1111	if (!m_mruMenu) {
1112		return;
1113	}
1114	m_mruMenu->clear();
1115	int i = 0;
1116	for (const QString& file : m_mruFiles) {
1117		QAction* item = new QAction(file, m_mruMenu);
1118		item->setShortcut(QString("Ctrl+%1").arg(i));
1119		connect(item, &QAction::triggered, [this, file]() { m_controller->loadGame(file); });
1120		m_mruMenu->addAction(item);
1121		++i;
1122	}
1123	m_config->setMRU(m_mruFiles);
1124	m_config->write();
1125	m_mruMenu->setEnabled(i > 0);
1126}
1127
1128QAction* Window::addControlledAction(QMenu* menu, QAction* action, const QString& name) {
1129	addHiddenAction(menu, action, name);
1130	menu->addAction(action);
1131	return action;
1132}
1133
1134QAction* Window::addHiddenAction(QMenu* menu, QAction* action, const QString& name) {
1135	m_shortcutController->addAction(menu, action, name);
1136	action->setShortcutContext(Qt::WidgetShortcut);
1137	addAction(action);
1138	return action;
1139}
1140
1141WindowBackground::WindowBackground(QWidget* parent)
1142	: QLabel(parent)
1143{
1144	setLayout(new QStackedLayout());
1145	layout()->setContentsMargins(0, 0, 0, 0);
1146	setAlignment(Qt::AlignCenter);
1147}
1148
1149void WindowBackground::setSizeHint(const QSize& hint) {
1150	m_sizeHint = hint;
1151}
1152
1153QSize WindowBackground::sizeHint() const {
1154	return m_sizeHint;
1155}
1156
1157void WindowBackground::setLockAspectRatio(int width, int height) {
1158	m_aspectWidth = width;
1159	m_aspectHeight = height;
1160}
1161
1162void WindowBackground::paintEvent(QPaintEvent*) {
1163	const QPixmap* logo = pixmap();
1164	if (!logo) {
1165		return;
1166	}
1167	QPainter painter(this);
1168	painter.setRenderHint(QPainter::SmoothPixmapTransform);
1169	painter.fillRect(QRect(QPoint(), size()), Qt::black);
1170	QSize s = size();
1171	QSize ds = s;
1172	if (s.width() * m_aspectHeight > s.height() * m_aspectWidth) {
1173		ds.setWidth(s.height() * m_aspectWidth / m_aspectHeight);
1174	} else if (s.width() * m_aspectHeight < s.height() * m_aspectWidth) {
1175		ds.setHeight(s.width() * m_aspectHeight / m_aspectWidth);
1176	}
1177	QPoint origin = QPoint((s.width() - ds.width()) / 2, (s.height() - ds.height()) / 2);
1178	QRect full(origin, ds);
1179	painter.drawPixmap(full, *logo);
1180}