all repos — mgba @ 4036294593e5ea8e56ea68d926b072f4a5a2fb57

mGBA Game Boy Advance Emulator

src/platform/qt/Window.cpp (view raw)

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