all repos — mgba @ 071fe7ff2dc0a7cc396408f6558b4ad2d430a909

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