all repos — mgba @ e112e8671512c3ab716a343bb28e361e21db7b28

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(const uint32_t*, GBAThread*)), m_display, SLOT(startDrawing(const uint32_t*, 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::openKeymapWindow() {
 259	GBAKeyEditor* keyEditor = new GBAKeyEditor(&m_inputController, InputController::KEYBOARD);
 260	openView(keyEditor);
 261}
 262
 263void Window::openSettingsWindow() {
 264	SettingsView* settingsWindow = new SettingsView(m_config);
 265	connect(settingsWindow, SIGNAL(biosLoaded(const QString&)), m_controller, SLOT(loadBIOS(const QString&)));
 266	connect(settingsWindow, SIGNAL(audioDriverChanged()), m_controller, SLOT(reloadAudioDriver()));
 267	openView(settingsWindow);
 268}
 269
 270void Window::openShortcutWindow() {
 271	ShortcutView* shortcutView = new ShortcutView();
 272	shortcutView->setController(m_shortcutController);
 273	openView(shortcutView);
 274}
 275
 276void Window::openOverrideWindow() {
 277	OverrideView* overrideWindow = new OverrideView(m_controller, m_config);
 278	openView(overrideWindow);
 279}
 280
 281void Window::openSensorWindow() {
 282	SensorView* sensorWindow = new SensorView(m_controller);
 283	openView(sensorWindow);
 284}
 285
 286void Window::openCheatsWindow() {
 287	CheatsView* cheatsWindow = new CheatsView(m_controller);
 288	openView(cheatsWindow);
 289}
 290
 291void Window::openPaletteWindow() {
 292	PaletteView* paletteWindow = new PaletteView(m_controller);
 293	openView(paletteWindow);
 294}
 295
 296#ifdef BUILD_SDL
 297void Window::openGamepadWindow() {
 298	const char* profile = m_inputController.profileForType(SDL_BINDING_BUTTON);
 299	GBAKeyEditor* keyEditor = new GBAKeyEditor(&m_inputController, SDL_BINDING_BUTTON, profile);
 300	openView(keyEditor);
 301}
 302#endif
 303
 304#ifdef USE_FFMPEG
 305void Window::openVideoWindow() {
 306	if (!m_videoView) {
 307		m_videoView = new VideoView();
 308		connect(m_videoView, SIGNAL(recordingStarted(GBAAVStream*)), m_controller, SLOT(setAVStream(GBAAVStream*)));
 309		connect(m_videoView, SIGNAL(recordingStopped()), m_controller, SLOT(clearAVStream()), Qt::DirectConnection);
 310		connect(m_controller, SIGNAL(gameStopped(GBAThread*)), m_videoView, SLOT(stopRecording()));
 311		connect(m_controller, SIGNAL(gameStopped(GBAThread*)), m_videoView, SLOT(close()));
 312		connect(this, SIGNAL(shutdown()), m_videoView, SLOT(close()));
 313	}
 314	m_videoView->show();
 315}
 316#endif
 317
 318#ifdef USE_MAGICK
 319void Window::openGIFWindow() {
 320	if (!m_gifView) {
 321		m_gifView = new GIFView();
 322		connect(m_gifView, SIGNAL(recordingStarted(GBAAVStream*)), m_controller, SLOT(setAVStream(GBAAVStream*)));
 323		connect(m_gifView, SIGNAL(recordingStopped()), m_controller, SLOT(clearAVStream()), Qt::DirectConnection);
 324		connect(m_controller, SIGNAL(gameStopped(GBAThread*)), m_gifView, SLOT(stopRecording()));
 325		connect(m_controller, SIGNAL(gameStopped(GBAThread*)), m_gifView, SLOT(close()));
 326		connect(this, SIGNAL(shutdown()), m_gifView, SLOT(close()));
 327	}
 328	m_gifView->show();
 329}
 330#endif
 331
 332#ifdef USE_GDB_STUB
 333void Window::gdbOpen() {
 334	if (!m_gdbController) {
 335		m_gdbController = new GDBController(m_controller, this);
 336	}
 337	GDBWindow* window = new GDBWindow(m_gdbController);
 338	connect(this, SIGNAL(shutdown()), window, SLOT(close()));
 339	window->setAttribute(Qt::WA_DeleteOnClose);
 340	window->show();
 341}
 342#endif
 343
 344void Window::keyPressEvent(QKeyEvent* event) {
 345	if (event->isAutoRepeat()) {
 346		QWidget::keyPressEvent(event);
 347		return;
 348	}
 349	GBAKey key = m_inputController.mapKeyboard(event->key());
 350	if (key == GBA_KEY_NONE) {
 351		QWidget::keyPressEvent(event);
 352		return;
 353	}
 354	m_controller->keyPressed(key);
 355	event->accept();
 356}
 357
 358void Window::keyReleaseEvent(QKeyEvent* event) {
 359	if (event->isAutoRepeat()) {
 360		QWidget::keyReleaseEvent(event);
 361		return;
 362	}
 363	GBAKey key = m_inputController.mapKeyboard(event->key());
 364	if (key == GBA_KEY_NONE) {
 365		QWidget::keyPressEvent(event);
 366		return;
 367	}
 368	m_controller->keyReleased(key);
 369	event->accept();
 370}
 371
 372void Window::resizeEvent(QResizeEvent*) {
 373	m_config->setOption("height", m_screenWidget->height());
 374	m_config->setOption("width", m_screenWidget->width());
 375	m_config->setOption("fullscreen", isFullScreen());
 376}
 377
 378void Window::closeEvent(QCloseEvent* event) {
 379	emit shutdown();
 380	m_config->setQtOption("windowPos", pos());
 381	QMainWindow::closeEvent(event);
 382}
 383
 384void Window::focusOutEvent(QFocusEvent*) {
 385	m_controller->setTurbo(false, false);
 386	m_controller->clearKeys();
 387}
 388
 389void Window::dragEnterEvent(QDragEnterEvent* event) {
 390	if (event->mimeData()->hasFormat("text/uri-list")) {
 391		event->acceptProposedAction();
 392	}
 393}
 394
 395void Window::dropEvent(QDropEvent* event) {
 396	QString uris = event->mimeData()->data("text/uri-list");
 397	uris = uris.trimmed();
 398	if (uris.contains("\n")) {
 399		// Only one file please
 400		return;
 401	}
 402	QUrl url(uris);
 403	if (!url.isLocalFile()) {
 404		// No remote loading
 405		return;
 406	}
 407	event->accept();
 408	m_controller->loadGame(url.path());
 409}
 410
 411void Window::mouseDoubleClickEvent(QMouseEvent* event) {
 412	if (event->button() != Qt::LeftButton) {
 413		return;
 414	}
 415	toggleFullScreen();
 416}
 417
 418void Window::enterFullScreen() {
 419	if (isFullScreen()) {
 420		return;
 421	}
 422	showFullScreen();
 423#ifndef Q_OS_MAC
 424	if (m_controller->isLoaded() && !m_controller->isPaused()) {
 425		menuBar()->hide();
 426	}
 427#endif
 428}
 429
 430void Window::exitFullScreen() {
 431	if (!isFullScreen()) {
 432		return;
 433	}
 434	showNormal();
 435	menuBar()->show();
 436}
 437
 438void Window::toggleFullScreen() {
 439	if (isFullScreen()) {
 440		exitFullScreen();
 441	} else {
 442		enterFullScreen();
 443	}
 444}
 445
 446void Window::gameStarted(GBAThread* context) {
 447	char title[13] = { '\0' };
 448	MutexLock(&context->stateMutex);
 449	if (context->state < THREAD_EXITING) {
 450		emit startDrawing(m_controller->drawContext(), context);
 451		GBAGetGameTitle(context->gba, title);
 452	} else {
 453		MutexUnlock(&context->stateMutex);
 454		return;
 455	}
 456	MutexUnlock(&context->stateMutex);
 457	foreach (QAction* action, m_gameActions) {
 458		action->setDisabled(false);
 459	}
 460	appendMRU(context->fname);
 461	setWindowTitle(tr(PROJECT_NAME " - %1").arg(title));
 462	attachWidget(m_display);
 463
 464#ifndef Q_OS_MAC
 465	if(isFullScreen()) {
 466		menuBar()->hide();
 467	}
 468#endif
 469
 470	m_hitUnimplementedBiosCall = false;
 471	m_fpsTimer.start();
 472}
 473
 474void Window::gameStopped() {
 475	foreach (QAction* action, m_gameActions) {
 476		action->setDisabled(true);
 477	}
 478	setWindowTitle(tr(PROJECT_NAME));
 479	detachWidget(m_display);
 480	m_screenWidget->setLockAspectRatio(m_logo.width(), m_logo.height());
 481	m_screenWidget->setPixmap(m_logo);
 482
 483	m_fpsTimer.stop();
 484}
 485
 486void Window::gameCrashed(const QString& errorMessage) {
 487	QMessageBox* crash = new QMessageBox(QMessageBox::Critical, tr("Crash"),
 488		tr("The game has crashed with the following error:\n\n%1").arg(errorMessage),
 489		QMessageBox::Ok, this,  Qt::Sheet);
 490	crash->setAttribute(Qt::WA_DeleteOnClose);
 491	crash->show();
 492}
 493
 494void Window::gameFailed() {
 495	QMessageBox* fail = new QMessageBox(QMessageBox::Warning, tr("Couldn't Load"),
 496		tr("Could not load game. Are you sure it's in the correct format?"),
 497		QMessageBox::Ok, this,  Qt::Sheet);
 498	fail->setAttribute(Qt::WA_DeleteOnClose);
 499	fail->show();
 500}
 501
 502void Window::unimplementedBiosCall(int call) {
 503	if (m_hitUnimplementedBiosCall) {
 504		return;
 505	}
 506	m_hitUnimplementedBiosCall = true;
 507
 508	QMessageBox* fail = new QMessageBox(QMessageBox::Warning, tr("Unimplemented BIOS call"),
 509		tr("This game uses a BIOS call that is not implemented. Please use the official BIOS for best experience."),
 510		QMessageBox::Ok, this,  Qt::Sheet);
 511	fail->setAttribute(Qt::WA_DeleteOnClose);
 512	fail->show();
 513}
 514
 515void Window::recordFrame() {
 516	m_frameList.append(QDateTime::currentDateTime());
 517	while (m_frameList.count() > FRAME_LIST_SIZE) {
 518		m_frameList.removeFirst();
 519	}
 520}
 521
 522void Window::showFPS() {
 523	char gameTitle[13] = { '\0' };
 524	GBAGetGameTitle(m_controller->thread()->gba, gameTitle);
 525
 526	QString title(gameTitle);
 527	std::shared_ptr<MultiplayerController> multiplayer = m_controller->multiplayerController();
 528	if (multiplayer && multiplayer->attached() > 1) {
 529		title += tr(" -  Player %1 of %2").arg(m_playerId + 1).arg(multiplayer->attached());
 530	}
 531	if (m_frameList.isEmpty()) {
 532		setWindowTitle(tr(PROJECT_NAME " - %1").arg(title));
 533		return;
 534	}
 535	qint64 interval = m_frameList.first().msecsTo(m_frameList.last());
 536	float fps = (m_frameList.count() - 1) * 10000.f / interval;
 537	fps = round(fps) / 10.f;
 538	setWindowTitle(tr(PROJECT_NAME " - %1 (%2 fps)").arg(title).arg(fps));
 539}
 540
 541void Window::openStateWindow(LoadSave ls) {
 542	if (m_stateWindow) {
 543		return;
 544	}
 545	bool wasPaused = m_controller->isPaused();
 546	m_stateWindow = new LoadSaveState(m_controller);
 547	connect(this, SIGNAL(shutdown()), m_stateWindow, SLOT(close()));
 548	connect(m_controller, SIGNAL(gameStopped(GBAThread*)), m_stateWindow, SLOT(close()));
 549	connect(m_stateWindow, &LoadSaveState::closed, [this]() {
 550		m_screenWidget->layout()->removeWidget(m_stateWindow);
 551		m_stateWindow = nullptr;
 552		QMetaObject::invokeMethod(this, "setFocus", Qt::QueuedConnection);
 553	});
 554	if (!wasPaused) {
 555		m_controller->setPaused(true);
 556		connect(m_stateWindow, &LoadSaveState::closed, [this]() { m_controller->setPaused(false); });
 557	}
 558	m_stateWindow->setAttribute(Qt::WA_DeleteOnClose);
 559	m_stateWindow->setMode(ls);
 560	attachWidget(m_stateWindow);
 561}
 562
 563void Window::setupMenu(QMenuBar* menubar) {
 564	menubar->clear();
 565	QMenu* fileMenu = menubar->addMenu(tr("&File"));
 566	m_shortcutController->addMenu(fileMenu);
 567	installEventFilter(m_shortcutController);
 568	addControlledAction(fileMenu, fileMenu->addAction(tr("Load &ROM..."), this, SLOT(selectROM()), QKeySequence::Open), "loadROM");
 569	addControlledAction(fileMenu, fileMenu->addAction(tr("Load &BIOS..."), this, SLOT(selectBIOS())), "loadBIOS");
 570	addControlledAction(fileMenu, fileMenu->addAction(tr("Load &patch..."), this, SLOT(selectPatch())), "loadPatch");
 571
 572	m_mruMenu = fileMenu->addMenu(tr("Recent"));
 573
 574	fileMenu->addSeparator();
 575
 576	QAction* loadState = new QAction(tr("&Load state"), fileMenu);
 577	loadState->setShortcut(tr("F10"));
 578	connect(loadState, &QAction::triggered, [this]() { this->openStateWindow(LoadSave::LOAD); });
 579	m_gameActions.append(loadState);
 580	addControlledAction(fileMenu, loadState, "loadState");
 581
 582	QAction* saveState = new QAction(tr("&Save state"), fileMenu);
 583	saveState->setShortcut(tr("Shift+F10"));
 584	connect(saveState, &QAction::triggered, [this]() { this->openStateWindow(LoadSave::SAVE); });
 585	m_gameActions.append(saveState);
 586	addControlledAction(fileMenu, saveState, "saveState");
 587
 588	QMenu* quickLoadMenu = fileMenu->addMenu(tr("Quick load"));
 589	QMenu* quickSaveMenu = fileMenu->addMenu(tr("Quick save"));
 590	m_shortcutController->addMenu(quickLoadMenu);
 591	m_shortcutController->addMenu(quickSaveMenu);
 592	int i;
 593	for (i = 1; i < 10; ++i) {
 594		QAction* quickLoad = new QAction(tr("State &%1").arg(i), quickLoadMenu);
 595		quickLoad->setShortcut(tr("F%1").arg(i));
 596		connect(quickLoad, &QAction::triggered, [this, i]() { m_controller->loadState(i); });
 597		m_gameActions.append(quickLoad);
 598		addControlledAction(quickLoadMenu, quickLoad, QString("quickLoad.%1").arg(i));
 599
 600		QAction* quickSave = new QAction(tr("State &%1").arg(i), quickSaveMenu);
 601		quickSave->setShortcut(tr("Shift+F%1").arg(i));
 602		connect(quickSave, &QAction::triggered, [this, i]() { m_controller->saveState(i); });
 603		m_gameActions.append(quickSave);
 604		addControlledAction(quickSaveMenu, quickSave, QString("quickSave.%1").arg(i));
 605	}
 606
 607	fileMenu->addSeparator();
 608	QAction* multiWindow = new QAction(tr("New multiplayer window"), fileMenu);
 609	connect(multiWindow, &QAction::triggered, [this]() {
 610		std::shared_ptr<MultiplayerController> multiplayer = m_controller->multiplayerController();
 611		if (!multiplayer) {
 612			multiplayer = std::make_shared<MultiplayerController>();
 613			m_controller->setMultiplayerController(multiplayer);
 614		}
 615		Window* w2 = new Window(m_config, multiplayer->attached());
 616		w2->setAttribute(Qt::WA_DeleteOnClose);
 617		w2->loadConfig();
 618		w2->controller()->setMultiplayerController(multiplayer);
 619		w2->show();
 620	});
 621	addControlledAction(fileMenu, multiWindow, "multiWindow");
 622
 623#ifndef Q_OS_MAC
 624	addControlledAction(fileMenu, fileMenu->addAction(tr("E&xit"), this, SLOT(close()), QKeySequence::Quit), "quit");
 625#endif
 626
 627	QMenu* emulationMenu = menubar->addMenu(tr("&Emulation"));
 628	m_shortcutController->addMenu(emulationMenu);
 629	QAction* reset = new QAction(tr("&Reset"), emulationMenu);
 630	reset->setShortcut(tr("Ctrl+R"));
 631	connect(reset, SIGNAL(triggered()), m_controller, SLOT(reset()));
 632	m_gameActions.append(reset);
 633	addControlledAction(emulationMenu, reset, "reset");
 634
 635	QAction* shutdown = new QAction(tr("Sh&utdown"), emulationMenu);
 636	connect(shutdown, SIGNAL(triggered()), m_controller, SLOT(closeGame()));
 637	m_gameActions.append(shutdown);
 638	addControlledAction(emulationMenu, shutdown, "shutdown");
 639	emulationMenu->addSeparator();
 640
 641	QAction* pause = new QAction(tr("&Pause"), emulationMenu);
 642	pause->setChecked(false);
 643	pause->setCheckable(true);
 644	pause->setShortcut(tr("Ctrl+P"));
 645	connect(pause, SIGNAL(triggered(bool)), m_controller, SLOT(setPaused(bool)));
 646	connect(m_controller, &GameController::gamePaused, [this, pause]() {
 647		pause->setChecked(true);
 648
 649		QImage currentImage(reinterpret_cast<const uchar*>(m_controller->drawContext()), VIDEO_HORIZONTAL_PIXELS, VIDEO_VERTICAL_PIXELS, 1024, QImage::Format_RGB32);
 650		QPixmap pixmap;
 651		pixmap.convertFromImage(currentImage.rgbSwapped());
 652		m_screenWidget->setPixmap(pixmap);
 653		m_screenWidget->setLockAspectRatio(3, 2);
 654	});
 655	connect(m_controller, &GameController::gameUnpaused, [pause]() { pause->setChecked(false); });
 656	m_gameActions.append(pause);
 657	addControlledAction(emulationMenu, pause, "pause");
 658
 659	QAction* frameAdvance = new QAction(tr("&Next frame"), emulationMenu);
 660	frameAdvance->setShortcut(tr("Ctrl+N"));
 661	connect(frameAdvance, SIGNAL(triggered()), m_controller, SLOT(frameAdvance()));
 662	m_gameActions.append(frameAdvance);
 663	addControlledAction(emulationMenu, frameAdvance, "frameAdvance");
 664
 665	emulationMenu->addSeparator();
 666
 667	QAction* turbo = new QAction(tr("&Fast forward"), emulationMenu);
 668	turbo->setCheckable(true);
 669	turbo->setChecked(false);
 670	turbo->setShortcut(tr("Shift+Tab"));
 671	connect(turbo, SIGNAL(triggered(bool)), m_controller, SLOT(setTurbo(bool)));
 672	addControlledAction(emulationMenu, turbo, "fastForward");
 673
 674	QAction* rewind = new QAction(tr("Re&wind"), emulationMenu);
 675	rewind->setShortcut(tr("`"));
 676	connect(rewind, SIGNAL(triggered()), m_controller, SLOT(rewind()));
 677	m_gameActions.append(rewind);
 678	addControlledAction(emulationMenu, rewind, "rewind");
 679
 680	ConfigOption* videoSync = m_config->addOption("videoSync");
 681	videoSync->addBoolean(tr("Sync to &video"), emulationMenu);
 682	videoSync->connect([this](const QVariant& value) {
 683		m_controller->setVideoSync(value.toBool());
 684	}, this);
 685	m_config->updateOption("videoSync");
 686
 687	ConfigOption* audioSync = m_config->addOption("audioSync");
 688	audioSync->addBoolean(tr("Sync to &audio"), emulationMenu);
 689	audioSync->connect([this](const QVariant& value) {
 690		m_controller->setAudioSync(value.toBool());
 691	}, this);
 692	m_config->updateOption("audioSync");
 693
 694	emulationMenu->addSeparator();
 695
 696	QMenu* solarMenu = emulationMenu->addMenu(tr("Solar sensor"));
 697	m_shortcutController->addMenu(solarMenu);
 698	QAction* solarIncrease = new QAction(tr("Increase solar level"), solarMenu);
 699	connect(solarIncrease, SIGNAL(triggered()), m_controller, SLOT(increaseLuminanceLevel()));
 700	addControlledAction(solarMenu, solarIncrease, "increaseLuminanceLevel");
 701
 702	QAction* solarDecrease = new QAction(tr("Decrease solar level"), solarMenu);
 703	connect(solarDecrease, SIGNAL(triggered()), m_controller, SLOT(decreaseLuminanceLevel()));
 704	addControlledAction(solarMenu, solarDecrease, "decreaseLuminanceLevel");
 705
 706	QAction* maxSolar = new QAction(tr("Brightest solar level"), solarMenu);
 707	connect(maxSolar, &QAction::triggered, [this]() { m_controller->setLuminanceLevel(10); });
 708	addControlledAction(solarMenu, maxSolar, "maxLuminanceLevel");
 709
 710	QAction* minSolar = new QAction(tr("Darkest solar level"), solarMenu);
 711	connect(minSolar, &QAction::triggered, [this]() { m_controller->setLuminanceLevel(0); });
 712	addControlledAction(solarMenu, minSolar, "minLuminanceLevel");
 713
 714	QMenu* avMenu = menubar->addMenu(tr("Audio/&Video"));
 715	m_shortcutController->addMenu(avMenu);
 716	QMenu* frameMenu = avMenu->addMenu(tr("Frame size"));
 717	m_shortcutController->addMenu(frameMenu, avMenu);
 718	for (int i = 1; i <= 6; ++i) {
 719		QAction* setSize = new QAction(tr("%1x").arg(QString::number(i)), avMenu);
 720		connect(setSize, &QAction::triggered, [this, i]() {
 721			showNormal();
 722			resizeFrame(VIDEO_HORIZONTAL_PIXELS * i, VIDEO_VERTICAL_PIXELS * i);
 723		});
 724		addControlledAction(frameMenu, setSize, QString("frame%1x").arg(QString::number(i)));
 725	}
 726	addControlledAction(frameMenu, frameMenu->addAction(tr("Fullscreen"), this, SLOT(toggleFullScreen()), QKeySequence("Ctrl+F")), "fullscreen");
 727
 728	ConfigOption* lockAspectRatio = m_config->addOption("lockAspectRatio");
 729	lockAspectRatio->addBoolean(tr("Lock aspect ratio"), avMenu);
 730	lockAspectRatio->connect([this](const QVariant& value) {
 731		m_display->lockAspectRatio(value.toBool());
 732	}, this);
 733	m_config->updateOption("lockAspectRatio");
 734
 735	ConfigOption* resampleVideo = m_config->addOption("resampleVideo");
 736	resampleVideo->addBoolean(tr("Resample video"), avMenu);
 737	resampleVideo->connect([this](const QVariant& value) {
 738		m_display->filter(value.toBool());
 739	}, this);
 740	m_config->updateOption("resampleVideo");
 741
 742	QMenu* skipMenu = avMenu->addMenu(tr("Frame&skip"));
 743	ConfigOption* skip = m_config->addOption("frameskip");
 744	skip->connect([this](const QVariant& value) {
 745		m_controller->setFrameskip(value.toInt());
 746	}, this);
 747	for (int i = 0; i <= 10; ++i) {
 748		skip->addValue(QString::number(i), i, skipMenu);
 749	}
 750	m_config->updateOption("frameskip");
 751
 752	avMenu->addSeparator();
 753
 754	QMenu* buffersMenu = avMenu->addMenu(tr("Audio buffer &size"));
 755	ConfigOption* buffers = m_config->addOption("audioBuffers");
 756	buffers->connect([this](const QVariant& value) {
 757		emit audioBufferSamplesChanged(value.toInt());
 758	}, this);
 759	buffers->addValue(tr("512"), 512, buffersMenu);
 760	buffers->addValue(tr("768"), 768, buffersMenu);
 761	buffers->addValue(tr("1024"), 1024, buffersMenu);
 762	buffers->addValue(tr("2048"), 2048, buffersMenu);
 763	buffers->addValue(tr("4096"), 4096, buffersMenu);
 764	m_config->updateOption("audioBuffers");
 765
 766	avMenu->addSeparator();
 767
 768	QMenu* target = avMenu->addMenu(tr("FPS target"));
 769	ConfigOption* fpsTargetOption = m_config->addOption("fpsTarget");
 770	fpsTargetOption->connect([this](const QVariant& value) {
 771		emit fpsTargetChanged(value.toInt());
 772	}, this);
 773	fpsTargetOption->addValue(tr("15"), 15, target);
 774	fpsTargetOption->addValue(tr("30"), 30, target);
 775	fpsTargetOption->addValue(tr("45"), 45, target);
 776	fpsTargetOption->addValue(tr("60"), 60, target);
 777	fpsTargetOption->addValue(tr("90"), 90, target);
 778	fpsTargetOption->addValue(tr("120"), 120, target);
 779	fpsTargetOption->addValue(tr("240"), 240, target);
 780	m_config->updateOption("fpsTarget");
 781
 782#if defined(USE_PNG) || defined(USE_FFMPEG) || defined(USE_MAGICK)
 783	avMenu->addSeparator();
 784#endif
 785
 786#ifdef USE_PNG
 787	QAction* screenshot = new QAction(tr("Take &screenshot"), avMenu);
 788	screenshot->setShortcut(tr("F12"));
 789	connect(screenshot, SIGNAL(triggered()), m_controller, SLOT(screenshot()));
 790	m_gameActions.append(screenshot);
 791	addControlledAction(avMenu, screenshot, "screenshot");
 792#endif
 793
 794#ifdef USE_FFMPEG
 795	QAction* recordOutput = new QAction(tr("Record output..."), avMenu);
 796	recordOutput->setShortcut(tr("F11"));
 797	connect(recordOutput, SIGNAL(triggered()), this, SLOT(openVideoWindow()));
 798	addControlledAction(avMenu, recordOutput, "recordOutput");
 799#endif
 800
 801#ifdef USE_MAGICK
 802	QAction* recordGIF = new QAction(tr("Record GIF..."), avMenu);
 803	recordGIF->setShortcut(tr("Shift+F11"));
 804	connect(recordGIF, SIGNAL(triggered()), this, SLOT(openGIFWindow()));
 805	addControlledAction(avMenu, recordGIF, "recordGIF");
 806#endif
 807
 808	avMenu->addSeparator();
 809	QMenu* videoLayers = avMenu->addMenu(tr("Video layers"));
 810
 811	for (int i = 0; i < 4; ++i) {
 812		QAction* enableBg = new QAction(tr("Background %0").arg(i), videoLayers);
 813		enableBg->setCheckable(true);
 814		enableBg->setChecked(true);
 815		connect(enableBg, &QAction::triggered, [this, i](bool enable) { m_controller->thread()->gba->video.renderer->disableBG[i] = !enable; });
 816		m_gameActions.append(enableBg);
 817		addControlledAction(videoLayers, enableBg, QString("enableBG%0").arg(i));
 818	}
 819
 820	QAction* enableObj = new QAction(tr("OBJ (sprites)"), videoLayers);
 821	enableObj->setCheckable(true);
 822	enableObj->setChecked(true);
 823	connect(enableObj, &QAction::triggered, [this](bool enable) { m_controller->thread()->gba->video.renderer->disableOBJ = !enable; });
 824	m_gameActions.append(enableObj);
 825	addControlledAction(videoLayers, enableObj, "enableOBJ");
 826
 827	QMenu* audioChannels = avMenu->addMenu(tr("Audio channels"));
 828
 829	for (int i = 0; i < 4; ++i) {
 830		QAction* enableCh = new QAction(tr("Channel %0").arg(i + 1), audioChannels);
 831		enableCh->setCheckable(true);
 832		enableCh->setChecked(true);
 833		connect(enableCh, &QAction::triggered, [this, i](bool enable) { m_controller->thread()->gba->audio.forceDisableCh[i] = !enable; });
 834		m_gameActions.append(enableCh);
 835		addControlledAction(audioChannels, enableCh, QString("enableCh%0").arg(i + 1));
 836	}
 837
 838	QAction* enableChA = new QAction(tr("Channel A"), audioChannels);
 839	enableChA->setCheckable(true);
 840	enableChA->setChecked(true);
 841	connect(enableChA, &QAction::triggered, [this, i](bool enable) { m_controller->thread()->gba->audio.forceDisableChA = !enable; });
 842	m_gameActions.append(enableChA);
 843	addControlledAction(audioChannels, enableChA, QString("enableChA"));
 844
 845	QAction* enableChB = new QAction(tr("Channel B"), audioChannels);
 846	enableChB->setCheckable(true);
 847	enableChB->setChecked(true);
 848	connect(enableChB, &QAction::triggered, [this, i](bool enable) { m_controller->thread()->gba->audio.forceDisableChB = !enable; });
 849	m_gameActions.append(enableChB);
 850	addControlledAction(audioChannels, enableChB, QString("enableChB"));
 851
 852	QMenu* toolsMenu = menubar->addMenu(tr("&Tools"));
 853	m_shortcutController->addMenu(toolsMenu);
 854	QAction* viewLogs = new QAction(tr("View &logs..."), toolsMenu);
 855	connect(viewLogs, SIGNAL(triggered()), m_logView, SLOT(show()));
 856	addControlledAction(toolsMenu, viewLogs, "viewLogs");
 857
 858	QAction* overrides = new QAction(tr("Game &overrides..."), toolsMenu);
 859	connect(overrides, SIGNAL(triggered()), this, SLOT(openOverrideWindow()));
 860	addControlledAction(toolsMenu, overrides, "overrideWindow");
 861
 862	QAction* sensors = new QAction(tr("Game &Pak sensors..."), toolsMenu);
 863	connect(sensors, SIGNAL(triggered()), this, SLOT(openSensorWindow()));
 864	addControlledAction(toolsMenu, sensors, "sensorWindow");
 865
 866	QAction* cheats = new QAction(tr("&Cheats..."), toolsMenu);
 867	connect(cheats, SIGNAL(triggered()), this, SLOT(openCheatsWindow()));
 868	addControlledAction(toolsMenu, cheats, "cheatsWindow");
 869
 870#ifdef USE_GDB_STUB
 871	QAction* gdbWindow = new QAction(tr("Start &GDB server..."), toolsMenu);
 872	connect(gdbWindow, SIGNAL(triggered()), this, SLOT(gdbOpen()));
 873	addControlledAction(toolsMenu, gdbWindow, "gdbWindow");
 874#endif
 875
 876	toolsMenu->addSeparator();
 877	addControlledAction(toolsMenu, toolsMenu->addAction(tr("Settings..."), this, SLOT(openSettingsWindow())), "settings");
 878	addControlledAction(toolsMenu, toolsMenu->addAction(tr("Edit shortcuts..."), this, SLOT(openShortcutWindow())), "shortcuts");
 879
 880	QAction* keymap = new QAction(tr("Remap keyboard..."), toolsMenu);
 881	connect(keymap, SIGNAL(triggered()), this, SLOT(openKeymapWindow()));
 882	addControlledAction(toolsMenu, keymap, "remapKeyboard");
 883
 884#ifdef BUILD_SDL
 885	QAction* gamepad = new QAction(tr("Remap gamepad..."), toolsMenu);
 886	connect(gamepad, SIGNAL(triggered()), this, SLOT(openGamepadWindow()));
 887	addControlledAction(toolsMenu, gamepad, "remapGamepad");
 888#endif
 889
 890	toolsMenu->addSeparator();
 891
 892	QAction* paletteView = new QAction(tr("View &palette..."), toolsMenu);
 893	connect(paletteView, SIGNAL(triggered()), this, SLOT(openPaletteWindow()));
 894	m_gameActions.append(paletteView);
 895	addControlledAction(toolsMenu, paletteView, "paletteWindow");
 896
 897	ConfigOption* skipBios = m_config->addOption("skipBios");
 898	skipBios->connect([this](const QVariant& value) {
 899		m_controller->setSkipBIOS(value.toBool());
 900	}, this);
 901
 902	ConfigOption* volume = m_config->addOption("volume");
 903	volume->connect([this](const QVariant& value) {
 904		m_controller->setVolume(value.toInt());
 905	}, this);
 906
 907	ConfigOption* mute = m_config->addOption("mute");
 908	mute->connect([this](const QVariant& value) {
 909		m_controller->setMute(value.toBool());
 910	}, this);
 911
 912	ConfigOption* rewindEnable = m_config->addOption("rewindEnable");
 913	rewindEnable->connect([this](const QVariant& value) {
 914		m_controller->setRewind(value.toBool(), m_config->getOption("rewindBufferCapacity").toInt(), m_config->getOption("rewindBufferInterval").toInt());
 915	}, this);
 916
 917	ConfigOption* rewindBufferCapacity = m_config->addOption("rewindBufferCapacity");
 918	rewindBufferCapacity->connect([this](const QVariant& value) {
 919		m_controller->setRewind(m_config->getOption("rewindEnable").toInt(), value.toInt(), m_config->getOption("rewindBufferInterval").toInt());
 920	}, this);
 921
 922	ConfigOption* rewindBufferInterval = m_config->addOption("rewindBufferInterval");
 923	rewindBufferInterval->connect([this](const QVariant& value) {
 924		m_controller->setRewind(m_config->getOption("rewindEnable").toInt(), m_config->getOption("rewindBufferCapacity").toInt(), value.toInt());
 925	}, this);
 926
 927	ConfigOption* allowOpposingDirections = m_config->addOption("allowOpposingDirections");
 928	allowOpposingDirections->connect([this](const QVariant& value) {
 929		m_inputController.setAllowOpposing(value.toBool());
 930	}, this);
 931
 932	QMenu* other = new QMenu(tr("Other"), this);
 933	m_shortcutController->addMenu(other);
 934	m_shortcutController->addFunctions(other, [this]() {
 935		m_controller->setTurbo(true, false);
 936	}, [this]() {
 937		m_controller->setTurbo(false, false);
 938	}, QKeySequence(Qt::Key_Tab), tr("Fast Forward (held)"), "holdFastForward");
 939
 940	addControlledAction(other, other->addAction(tr("Exit fullscreen"), this, SLOT(exitFullScreen()), QKeySequence("Esc")), "exitFullScreen");
 941
 942	foreach (QAction* action, m_gameActions) {
 943		action->setDisabled(true);
 944	}
 945}
 946
 947void Window::attachWidget(QWidget* widget) {
 948	m_screenWidget->layout()->addWidget(widget);
 949	static_cast<QStackedLayout*>(m_screenWidget->layout())->setCurrentWidget(widget);
 950}
 951
 952void Window::detachWidget(QWidget* widget) {
 953	m_screenWidget->layout()->removeWidget(widget);
 954}
 955
 956void Window::appendMRU(const QString& fname) {
 957	int index = m_mruFiles.indexOf(fname);
 958	if (index >= 0) {
 959		m_mruFiles.removeAt(index);
 960	}
 961	m_mruFiles.prepend(fname);
 962	while (m_mruFiles.size() > ConfigController::MRU_LIST_SIZE) {
 963		m_mruFiles.removeLast();
 964	}
 965	updateMRU();
 966}
 967
 968void Window::updateMRU() {
 969	if (!m_mruMenu) {
 970		return;
 971	}
 972	m_mruMenu->clear();
 973	int i = 0;
 974	for (const QString& file : m_mruFiles) {
 975		QAction* item = new QAction(file, m_mruMenu);
 976		item->setShortcut(QString("Ctrl+%1").arg(i));
 977		connect(item, &QAction::triggered, [this, file]() { m_controller->loadGame(file); });
 978		m_mruMenu->addAction(item);
 979		++i;
 980	}
 981	m_config->setMRU(m_mruFiles);
 982	m_config->write();
 983	m_mruMenu->setEnabled(i > 0);
 984}
 985
 986QAction* Window::addControlledAction(QMenu* menu, QAction* action, const QString& name) {
 987	m_shortcutController->addAction(menu, action, name);
 988	menu->addAction(action);
 989	action->setShortcutContext(Qt::WidgetShortcut);
 990	addAction(action);
 991	return action;
 992}
 993
 994WindowBackground::WindowBackground(QWidget* parent)
 995	: QLabel(parent)
 996{
 997	setLayout(new QStackedLayout());
 998	layout()->setContentsMargins(0, 0, 0, 0);
 999	setAlignment(Qt::AlignCenter);
1000}
1001
1002void WindowBackground::setSizeHint(const QSize& hint) {
1003	m_sizeHint = hint;
1004}
1005
1006QSize WindowBackground::sizeHint() const {
1007	return m_sizeHint;
1008}
1009
1010void WindowBackground::setLockAspectRatio(int width, int height) {
1011	m_aspectWidth = width;
1012	m_aspectHeight = height;
1013}
1014
1015void WindowBackground::paintEvent(QPaintEvent*) {
1016	const QPixmap* logo = pixmap();
1017	if (!logo) {
1018		return;
1019	}
1020	QPainter painter(this);
1021	painter.setRenderHint(QPainter::SmoothPixmapTransform);
1022	painter.fillRect(QRect(QPoint(), size()), Qt::black);
1023	QSize s = size();
1024	QSize ds = s;
1025	if (s.width() * m_aspectHeight > s.height() * m_aspectWidth) {
1026		ds.setWidth(s.height() * m_aspectWidth / m_aspectHeight);
1027	} else if (s.width() * m_aspectHeight < s.height() * m_aspectWidth) {
1028		ds.setHeight(s.width() * m_aspectHeight / m_aspectWidth);
1029	}
1030	QPoint origin = QPoint((s.width() - ds.width()) / 2, (s.height() - ds.height()) / 2);
1031	QRect full(origin, ds);
1032	painter.drawPixmap(full, *logo);
1033}