all repos — mgba @ 481833c2052a749afe2a8f774ece5b11449e6f2a

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