all repos — mgba @ a767ae2333490b6736616a1524442e5e96addb5d

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