all repos — mgba @ 5a932631bee45043aabc0eda64858164b91c171e

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