all repos — mgba @ 5f2d704eb01b52032c602cd473de91b059293df1

mGBA Game Boy Advance Emulator

src/platform/qt/input/InputController.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 "InputController.h"
   7
   8#include "ConfigController.h"
   9#include "CoreController.h"
  10#include "GamepadAxisEvent.h"
  11#include "GamepadButtonEvent.h"
  12#include "InputItem.h"
  13#include "InputModel.h"
  14#include "InputProfile.h"
  15#include "LogController.h"
  16
  17#include <QApplication>
  18#include <QKeyEvent>
  19#include <QMenu>
  20#include <QTimer>
  21#include <QWidget>
  22#ifdef BUILD_QT_MULTIMEDIA
  23#include <QCameraInfo>
  24#include <QVideoSurfaceFormat>
  25#endif
  26
  27#include <mgba/core/interface.h>
  28#include <mgba-util/configuration.h>
  29
  30#ifdef M_CORE_GBA
  31#include <mgba/internal/gba/input.h>
  32#endif
  33#ifdef M_CORE_GB
  34#include <mgba/internal/gb/input.h>
  35#endif
  36#ifdef M_CORE_DS
  37#include <mgba/internal/ds/input.h>
  38#endif
  39#include <initializer_list>
  40
  41using namespace QGBA;
  42
  43#ifdef BUILD_SDL
  44int InputController::s_sdlInited = 0;
  45mSDLEvents InputController::s_sdlEvents;
  46#endif
  47
  48InputController::InputController(int playerId, QWidget* topLevel, QObject* parent)
  49	: QObject(parent)
  50	, m_playerId(playerId)
  51	, m_topLevel(topLevel)
  52	, m_focusParent(topLevel)
  53	, m_bindings(new QMenu(tr("Controls")))
  54	, m_autofire(new QMenu(tr("Autofire")))
  55{
  56#ifdef BUILD_SDL
  57	if (s_sdlInited == 0) {
  58		mSDLInitEvents(&s_sdlEvents);
  59	}
  60	++s_sdlInited;
  61	updateJoysticks();
  62#endif
  63
  64#ifdef BUILD_SDL
  65	connect(&m_gamepadTimer, &QTimer::timeout, [this]() {
  66		testGamepad(SDL_BINDING_BUTTON);
  67		if (m_playerId == 0) {
  68			updateJoysticks();
  69		}
  70	});
  71#endif
  72	m_gamepadTimer.setInterval(50);
  73	m_gamepadTimer.start();
  74
  75#ifdef BUILD_QT_MULTIMEDIA
  76	connect(&m_videoDumper, &VideoDumper::imageAvailable, this, &InputController::setCamImage);
  77#endif
  78
  79	static QList<QPair<QString, int>> defaultBindings({
  80		qMakePair(QLatin1String("A"), Qt::Key_Z),
  81		qMakePair(QLatin1String("B"), Qt::Key_X),
  82		qMakePair(QLatin1String("L"), Qt::Key_A),
  83		qMakePair(QLatin1String("R"), Qt::Key_S),
  84		qMakePair(QLatin1String("Start"), Qt::Key_Return),
  85		qMakePair(QLatin1String("Select"), Qt::Key_Backspace),
  86		qMakePair(QLatin1String("Up"), Qt::Key_Up),
  87		qMakePair(QLatin1String("Down"), Qt::Key_Down),
  88		qMakePair(QLatin1String("Left"), Qt::Key_Left),
  89		qMakePair(QLatin1String("Right"), Qt::Key_Right)
  90	});
  91
  92	for (auto k : defaultBindings) {
  93		addKey(k.first);
  94	}
  95	m_keyIndex.rebuild();
  96	for (auto k : defaultBindings) {
  97		bindKey(KEYBOARD, k.second, k.first);
  98	}
  99}
 100
 101void InputController::addKey(const QString& name) {
 102	if (itemForKey(name)) {
 103		return;
 104	}
 105	m_keyIndex.addItem(qMakePair([this, name]() {
 106		m_activeKeys |= 1 << keyId(name);
 107	}, [this, name]() {
 108		m_activeKeys &= ~(1 << keyId(name));
 109	}), name, QString("key%0").arg(name), m_bindings.get());
 110
 111	m_keyIndex.addItem(qMakePair([this, name]() {
 112		setAutofire(keyId(name), true);
 113	}, [this, name]() {
 114		setAutofire(keyId(name), false);
 115	}), name, QString("autofire%1").arg(name), m_autofire.get());
 116}
 117
 118void InputController::setAutofire(int key, bool enable) {
 119	if (key >= 32 || key < 0) {
 120		return;
 121	}
 122
 123	m_autofireEnabled[key] = enable;
 124	m_autofireStatus[key] = 0;
 125}
 126
 127int InputController::updateAutofire() {
 128	int active = 0;
 129	for (int k = 0; k < 32; ++k) {
 130		if (!m_autofireEnabled[k]) {
 131			continue;
 132		}
 133		++m_autofireStatus[k];
 134		if (m_autofireStatus[k]) {
 135			m_autofireStatus[k] = 0;
 136			active |= 1 << k;
 137		}
 138	}
 139	return active;
 140}
 141
 142void InputController::addPlatform(mPlatform platform, const mInputPlatformInfo* info) {
 143	m_keyInfo[platform] = info;
 144	for (size_t i = 0; i < info->nKeys; ++i) {
 145		addKey(info->keyId[i]);
 146	}
 147}
 148
 149void InputController::setPlatform(mPlatform platform) {
 150	if (m_activeKeyInfo) {
 151		mInputMapDeinit(&m_inputMap);
 152	}
 153
 154	m_sdlPlayer.bindings = &m_inputMap;
 155	m_activeKeyInfo = m_keyInfo[platform];
 156	mInputMapInit(&m_inputMap, m_activeKeyInfo);
 157
 158	loadConfiguration(KEYBOARD);
 159#ifdef BUILD_SDL
 160	mSDLInitBindingsGBA(&m_inputMap);
 161	loadConfiguration(SDL_BINDING_BUTTON);
 162#endif
 163
 164	rebuildKeyIndex();
 165	restoreModel();
 166
 167#ifdef M_CORE_GBA
 168	m_lux.p = this;
 169	m_lux.sample = [](GBALuminanceSource* context) {
 170		InputControllerLux* lux = static_cast<InputControllerLux*>(context);
 171		lux->value = 0xFF - lux->p->m_luxValue;
 172	};
 173
 174	m_lux.readLuminance = [](GBALuminanceSource* context) {
 175		InputControllerLux* lux = static_cast<InputControllerLux*>(context);
 176		return lux->value;
 177	};
 178	setLuminanceLevel(0);
 179#endif
 180
 181	m_image.p = this;
 182	m_image.startRequestImage = [](mImageSource* context, unsigned w, unsigned h, int) {
 183		InputControllerImage* image = static_cast<InputControllerImage*>(context);
 184		image->w = w;
 185		image->h = h;
 186		if (image->image.isNull()) {
 187			image->image.load(":/res/no-cam.png");
 188		}
 189#ifdef BUILD_QT_MULTIMEDIA
 190		if (image->p->m_config->getQtOption("cameraDriver").toInt() == static_cast<int>(CameraDriver::QT_MULTIMEDIA)) {
 191			QByteArray camera = image->p->m_config->getQtOption("camera").toByteArray();
 192			if (!camera.isNull()) {
 193				QMetaObject::invokeMethod(image->p, "setCamera", Q_ARG(QByteArray, camera));
 194			}
 195			QMetaObject::invokeMethod(image->p, "setupCam");
 196		}
 197#endif
 198	};
 199
 200	m_image.stopRequestImage = [](mImageSource* context) {
 201		InputControllerImage* image = static_cast<InputControllerImage*>(context);
 202#ifdef BUILD_QT_MULTIMEDIA
 203		QMetaObject::invokeMethod(image->p, "teardownCam");
 204#endif
 205	};
 206
 207	m_image.requestImage = [](mImageSource* context, const void** buffer, size_t* stride, mColorFormat* format) {
 208		InputControllerImage* image = static_cast<InputControllerImage*>(context);
 209		QSize size;
 210		{
 211			QMutexLocker locker(&image->mutex);
 212			if (image->outOfDate) {
 213				image->resizedImage = image->image.scaled(image->w, image->h, Qt::KeepAspectRatioByExpanding);
 214				image->resizedImage = image->resizedImage.convertToFormat(QImage::Format_RGB16);
 215				image->outOfDate = false;
 216			}
 217		}
 218		size = image->resizedImage.size();
 219		const uint16_t* bits = reinterpret_cast<const uint16_t*>(image->resizedImage.constBits());
 220		if (size.width() > image->w) {
 221			bits += (size.width() - image->w) / 2;
 222		}
 223		if (size.height() > image->h) {
 224			bits += ((size.height() - image->h) / 2) * size.width();
 225		}
 226		*buffer = bits;
 227		*stride = image->resizedImage.bytesPerLine() / sizeof(*bits);
 228		*format = mCOLOR_RGB565;
 229	};
 230}
 231
 232InputController::~InputController() {
 233	if (m_activeKeyInfo) {
 234		mInputMapDeinit(&m_inputMap);
 235	}
 236
 237#ifdef BUILD_SDL
 238	if (m_playerAttached) {
 239		mSDLDetachPlayer(&s_sdlEvents, &m_sdlPlayer);
 240	}
 241
 242	--s_sdlInited;
 243	if (s_sdlInited == 0) {
 244		mSDLDeinitEvents(&s_sdlEvents);
 245	}
 246#endif
 247}
 248
 249void InputController::rebuildIndex(const InputIndex* index) {
 250	m_inputIndex.rebuild(index);
 251}
 252
 253void InputController::rebuildKeyIndex(const InputIndex* index) {
 254	m_keyIndex.rebuild(index);
 255
 256	for (const InputItem* item : m_keyIndex.items()) {
 257		if (!item->name().startsWith(QLatin1String("key"))) {
 258			rebindKey(item->visibleName());
 259		}
 260	}
 261}
 262
 263void InputController::setConfiguration(ConfigController* config) {
 264	m_config = config;
 265	m_inputIndex.setConfigController(config);
 266	m_keyIndex.setConfigController(config);
 267	loadConfiguration(KEYBOARD);
 268	loadProfile(KEYBOARD, profileForType(KEYBOARD));
 269#ifdef BUILD_SDL
 270	mSDLEventsLoadConfig(&s_sdlEvents, config->input());
 271	if (!m_playerAttached) {
 272		m_playerAttached = mSDLAttachPlayer(&s_sdlEvents, &m_sdlPlayer);
 273	}
 274	loadConfiguration(SDL_BINDING_BUTTON);
 275	loadProfile(SDL_BINDING_BUTTON, profileForType(SDL_BINDING_BUTTON));
 276#endif
 277	restoreModel();
 278}
 279
 280void InputController::loadConfiguration(uint32_t type) {
 281	if (!m_activeKeyInfo) {
 282		return;
 283	}
 284	mInputMapLoad(&m_inputMap, type, m_config->input());
 285#ifdef BUILD_SDL
 286	if (m_playerAttached) {
 287		mSDLPlayerLoadConfig(&m_sdlPlayer, m_config->input());
 288	}
 289#endif
 290}
 291
 292void InputController::loadProfile(uint32_t type, const QString& profile) {
 293	const InputProfile* ip = InputProfile::findProfile(profile);
 294	if (ip) {
 295		ip->apply(this);
 296	}
 297	recalibrateAxes();
 298	emit profileLoaded(profile);
 299}
 300
 301void InputController::saveConfiguration() {
 302	saveConfiguration(KEYBOARD);
 303#ifdef BUILD_SDL
 304	saveConfiguration(SDL_BINDING_BUTTON);
 305	saveProfile(SDL_BINDING_BUTTON, profileForType(SDL_BINDING_BUTTON));
 306	if (m_playerAttached) {
 307		mSDLPlayerSaveConfig(&m_sdlPlayer, m_config->input());
 308	}
 309#endif
 310	m_inputIndex.saveConfig();
 311	m_keyIndex.saveConfig();
 312	m_config->write();
 313}
 314
 315void InputController::saveConfiguration(uint32_t type) {
 316	if (m_activeKeyInfo) {
 317		mInputMapSave(&m_inputMap, type, m_config->input());
 318	}
 319	m_config->write();
 320}
 321
 322void InputController::saveProfile(uint32_t type, const QString& profile) {
 323	if (m_activeKeyInfo) {
 324		mInputProfileSave(&m_inputMap, type, m_config->input(), profile.toUtf8().constData());
 325	}
 326	m_config->write();
 327}
 328
 329const char* InputController::profileForType(uint32_t type) {
 330	UNUSED(type);
 331#ifdef BUILD_SDL
 332	if (type == SDL_BINDING_BUTTON && m_sdlPlayer.joystick) {
 333#if SDL_VERSION_ATLEAST(2, 0, 0)
 334		return SDL_JoystickName(m_sdlPlayer.joystick->joystick);
 335#else
 336		return SDL_JoystickName(SDL_JoystickIndex(m_sdlPlayer.joystick->joystick));
 337#endif
 338	}
 339#endif
 340	return 0;
 341}
 342
 343QStringList InputController::connectedGamepads(uint32_t type) const {
 344	UNUSED(type);
 345
 346#ifdef BUILD_SDL
 347	if (type == SDL_BINDING_BUTTON) {
 348		QStringList pads;
 349		for (size_t i = 0; i < SDL_JoystickListSize(&s_sdlEvents.joysticks); ++i) {
 350			const char* name;
 351#if SDL_VERSION_ATLEAST(2, 0, 0)
 352			name = SDL_JoystickName(SDL_JoystickListGetPointer(&s_sdlEvents.joysticks, i)->joystick);
 353#else
 354			name = SDL_JoystickName(SDL_JoystickIndex(SDL_JoystickListGetPointer(&s_sdlEvents.joysticks, i)->joystick));
 355#endif
 356			if (name) {
 357				pads.append(QString(name));
 358			} else {
 359				pads.append(QString());
 360			}
 361		}
 362		return pads;
 363	}
 364#endif
 365
 366	return QStringList();
 367}
 368
 369int InputController::gamepad(uint32_t type) const {
 370#ifdef BUILD_SDL
 371	if (type == SDL_BINDING_BUTTON) {
 372		return m_sdlPlayer.joystick ? m_sdlPlayer.joystick->index : 0;
 373	}
 374#endif
 375	return 0;
 376}
 377
 378void InputController::setGamepad(uint32_t type, int index) {
 379#ifdef BUILD_SDL
 380	if (type == SDL_BINDING_BUTTON) {
 381		mSDLPlayerChangeJoystick(&s_sdlEvents, &m_sdlPlayer, index);
 382	}
 383#endif
 384}
 385
 386void InputController::setPreferredGamepad(uint32_t type, int index) {
 387	if (!m_config) {
 388		return;
 389	}
 390	char name[34] = {0};
 391	SDL_JoystickGetGUIDString(SDL_JoystickGetGUID(SDL_JoystickListGetPointer(&s_sdlEvents.joysticks, index)->joystick), name, sizeof(name));
 392	mInputSetPreferredDevice(m_config->input(), "gba", type, m_playerId, name);
 393}
 394
 395mRumble* InputController::rumble() {
 396#ifdef BUILD_SDL
 397#if SDL_VERSION_ATLEAST(2, 0, 0)
 398	if (m_playerAttached) {
 399		return &m_sdlPlayer.rumble.d;
 400	}
 401#endif
 402#endif
 403	return nullptr;
 404}
 405
 406mRotationSource* InputController::rotationSource() {
 407#ifdef BUILD_SDL
 408	if (m_playerAttached) {
 409		return &m_sdlPlayer.rotation.d;
 410	}
 411#endif
 412	return nullptr;
 413}
 414
 415void InputController::registerTiltAxisX(int axis) {
 416#ifdef BUILD_SDL
 417	if (m_playerAttached) {
 418		m_sdlPlayer.rotation.axisX = axis;
 419	}
 420#endif
 421}
 422
 423void InputController::registerTiltAxisY(int axis) {
 424#ifdef BUILD_SDL
 425	if (m_playerAttached) {
 426		m_sdlPlayer.rotation.axisY = axis;
 427	}
 428#endif
 429}
 430
 431void InputController::registerGyroAxisX(int axis) {
 432#ifdef BUILD_SDL
 433	if (m_playerAttached) {
 434		m_sdlPlayer.rotation.gyroX = axis;
 435	}
 436#endif
 437}
 438
 439void InputController::registerGyroAxisY(int axis) {
 440#ifdef BUILD_SDL
 441	if (m_playerAttached) {
 442		m_sdlPlayer.rotation.gyroY = axis;
 443	}
 444#endif
 445}
 446
 447float InputController::gyroSensitivity() const {
 448#ifdef BUILD_SDL
 449	if (m_playerAttached) {
 450		return m_sdlPlayer.rotation.gyroSensitivity;
 451	}
 452#endif
 453	return 0;
 454}
 455
 456void InputController::setGyroSensitivity(float sensitivity) {
 457#ifdef BUILD_SDL
 458	if (m_playerAttached) {
 459		m_sdlPlayer.rotation.gyroSensitivity = sensitivity;
 460	}
 461#endif
 462}
 463
 464void InputController::updateJoysticks() {
 465#ifdef BUILD_SDL
 466	QString profile = profileForType(SDL_BINDING_BUTTON);
 467	mSDLUpdateJoysticks(&s_sdlEvents, m_config->input());
 468	QString newProfile = profileForType(SDL_BINDING_BUTTON);
 469	if (profile != newProfile) {
 470		loadProfile(SDL_BINDING_BUTTON, newProfile);
 471	}
 472#endif
 473}
 474
 475const mInputMap* InputController::map() {
 476	if (!m_activeKeyInfo) {
 477		return nullptr;
 478	}
 479	return &m_inputMap;
 480}
 481
 482int InputController::pollEvents() {
 483	int activeButtons = m_activeKeys;
 484#ifdef BUILD_SDL
 485	if (m_playerAttached && m_sdlPlayer.joystick) {
 486		SDL_Joystick* joystick = m_sdlPlayer.joystick->joystick;
 487		SDL_JoystickUpdate();
 488		int numButtons = SDL_JoystickNumButtons(joystick);
 489		int i;
 490		for (i = 0; i < numButtons; ++i) {
 491			GBAKey key = static_cast<GBAKey>(mInputMapKey(&m_inputMap, SDL_BINDING_BUTTON, i));
 492			if (key == GBA_KEY_NONE) {
 493				continue;
 494			}
 495			if (hasPendingEvent(key)) {
 496				continue;
 497			}
 498			if (SDL_JoystickGetButton(joystick, i)) {
 499				activeButtons |= 1 << key;
 500			}
 501		}
 502		int numHats = SDL_JoystickNumHats(joystick);
 503		for (i = 0; i < numHats; ++i) {
 504			int hat = SDL_JoystickGetHat(joystick, i);
 505			activeButtons |= mInputMapHat(&m_inputMap, SDL_BINDING_BUTTON, i, hat);
 506		}
 507
 508		int numAxes = SDL_JoystickNumAxes(joystick);
 509		for (i = 0; i < numAxes; ++i) {
 510			int value = SDL_JoystickGetAxis(joystick, i);
 511
 512			enum GBAKey key = static_cast<GBAKey>(mInputMapAxis(&m_inputMap, SDL_BINDING_BUTTON, i, value));
 513			if (key != GBA_KEY_NONE) {
 514				activeButtons |= 1 << key;
 515			}
 516		}
 517	}
 518#endif
 519	return activeButtons;
 520}
 521
 522QSet<int> InputController::activeGamepadButtons(int type) {
 523	QSet<int> activeButtons;
 524#ifdef BUILD_SDL
 525	if (m_playerAttached && type == SDL_BINDING_BUTTON && m_sdlPlayer.joystick) {
 526		SDL_Joystick* joystick = m_sdlPlayer.joystick->joystick;
 527		SDL_JoystickUpdate();
 528		int numButtons = SDL_JoystickNumButtons(joystick);
 529		int i;
 530		for (i = 0; i < numButtons; ++i) {
 531			if (SDL_JoystickGetButton(joystick, i)) {
 532				activeButtons.insert(i);
 533			}
 534		}
 535	}
 536#endif
 537	return activeButtons;
 538}
 539
 540void InputController::recalibrateAxes() {
 541#ifdef BUILD_SDL
 542	if (m_playerAttached && m_sdlPlayer.joystick) {
 543		SDL_Joystick* joystick = m_sdlPlayer.joystick->joystick;
 544		SDL_JoystickUpdate();
 545		int numAxes = SDL_JoystickNumAxes(joystick);
 546		if (numAxes < 1) {
 547			return;
 548		}
 549		m_deadzones.resize(numAxes);
 550		int i;
 551		for (i = 0; i < numAxes; ++i) {
 552			m_deadzones[i] = SDL_JoystickGetAxis(joystick, i);
 553		}
 554	}
 555#endif
 556}
 557
 558QSet<QPair<int, GamepadAxisEvent::Direction>> InputController::activeGamepadAxes(int type) {
 559	QSet<QPair<int, GamepadAxisEvent::Direction>> activeAxes;
 560#ifdef BUILD_SDL
 561	if (m_playerAttached && type == SDL_BINDING_BUTTON && m_sdlPlayer.joystick) {
 562		SDL_Joystick* joystick = m_sdlPlayer.joystick->joystick;
 563		SDL_JoystickUpdate();
 564		int numAxes = SDL_JoystickNumAxes(joystick);
 565		if (numAxes < 1) {
 566			return activeAxes;
 567		}
 568		m_deadzones.resize(numAxes);
 569		int i;
 570		for (i = 0; i < numAxes; ++i) {
 571			int32_t axis = SDL_JoystickGetAxis(joystick, i);
 572			axis -= m_deadzones[i];
 573			if (axis >= AXIS_THRESHOLD || axis <= -AXIS_THRESHOLD) {
 574				activeAxes.insert(qMakePair(i, axis > 0 ? GamepadAxisEvent::POSITIVE : GamepadAxisEvent::NEGATIVE));
 575			}
 576		}
 577	}
 578#endif
 579	return activeAxes;
 580}
 581
 582void InputController::bindKey(uint32_t type, int key, const QString& keyName) {
 583	InputItem* item = itemForKey(keyName);
 584	if (type != KEYBOARD) {
 585		item->setButton(key);
 586	} else {
 587		item->setShortcut(key);
 588	}
 589	if (m_activeKeyInfo) {
 590		int coreKey = keyId(keyName);
 591		mInputBindKey(&m_inputMap, type, key, coreKey);
 592	}
 593}
 594
 595void InputController::bindAxis(uint32_t type, int axis, GamepadAxisEvent::Direction direction, const QString& key) {
 596	InputItem* item = itemForKey(key);
 597	item->setAxis(axis, direction);
 598	
 599	if (!m_activeKeyInfo) {
 600		return;
 601	}
 602
 603	const mInputAxis* old = mInputQueryAxis(&m_inputMap, type, axis);
 604	mInputAxis description = { GBA_KEY_NONE, GBA_KEY_NONE, -AXIS_THRESHOLD, AXIS_THRESHOLD };
 605	if (old) {
 606		description = *old;
 607	}
 608	int deadzone = 0;
 609	if (axis > 0 && m_deadzones.size() > axis) {
 610		deadzone = m_deadzones[axis];
 611	}
 612	switch (direction) {
 613	case GamepadAxisEvent::NEGATIVE:
 614		description.lowDirection = keyId(key);
 615
 616		description.deadLow = deadzone - AXIS_THRESHOLD;
 617		break;
 618	case GamepadAxisEvent::POSITIVE:
 619		description.highDirection = keyId(key);
 620		description.deadHigh = deadzone + AXIS_THRESHOLD;
 621		break;
 622	default:
 623		return;
 624	}
 625	mInputBindAxis(&m_inputMap, type, axis, &description);
 626}
 627
 628QSet<QPair<int, GamepadHatEvent::Direction>> InputController::activeGamepadHats(int type) {
 629	QSet<QPair<int, GamepadHatEvent::Direction>> activeHats;
 630#ifdef BUILD_SDL
 631	if (m_playerAttached && type == SDL_BINDING_BUTTON && m_sdlPlayer.joystick) {
 632		SDL_Joystick* joystick = m_sdlPlayer.joystick->joystick;
 633		SDL_JoystickUpdate();
 634		int numHats = SDL_JoystickNumHats(joystick);
 635		if (numHats < 1) {
 636			return activeHats;
 637		}
 638
 639		int i;
 640		for (i = 0; i < numHats; ++i) {
 641			int hat = SDL_JoystickGetHat(joystick, i);
 642			if (hat & GamepadHatEvent::UP) {
 643				activeHats.insert(qMakePair(i, GamepadHatEvent::UP));
 644			}
 645			if (hat & GamepadHatEvent::RIGHT) {
 646				activeHats.insert(qMakePair(i, GamepadHatEvent::RIGHT));
 647			}
 648			if (hat & GamepadHatEvent::DOWN) {
 649				activeHats.insert(qMakePair(i, GamepadHatEvent::DOWN));
 650			}
 651			if (hat & GamepadHatEvent::LEFT) {
 652				activeHats.insert(qMakePair(i, GamepadHatEvent::LEFT));
 653			}
 654		}
 655	}
 656#endif
 657	return activeHats;
 658}
 659
 660void InputController::bindHat(uint32_t type, int hat, GamepadHatEvent::Direction direction, const QString& key) {
 661	if (!m_activeKeyInfo) {
 662		return;
 663	}
 664
 665	mInputHatBindings bindings{ -1, -1, -1, -1 };
 666	mInputQueryHat(&m_inputMap, type, hat, &bindings);
 667	switch (direction) {
 668	case GamepadHatEvent::UP:
 669		bindings.up = keyId(key);
 670		break;
 671	case GamepadHatEvent::RIGHT:
 672		bindings.right = keyId(key);
 673		break;
 674	case GamepadHatEvent::DOWN:
 675		bindings.down = keyId(key);
 676		break;
 677	case GamepadHatEvent::LEFT:
 678		bindings.left = keyId(key);
 679		break;
 680	default:
 681		return;
 682	}
 683	mInputBindHat(&m_inputMap, type, hat, &bindings);
 684}
 685
 686void InputController::testGamepad(int type) {
 687	auto activeAxes = activeGamepadAxes(type);
 688	auto oldAxes = m_activeAxes;
 689	m_activeAxes = activeAxes;
 690
 691	auto activeButtons = activeGamepadButtons(type);
 692	auto oldButtons = m_activeButtons;
 693	m_activeButtons = activeButtons;
 694
 695	auto activeHats = activeGamepadHats(type);
 696	auto oldHats = m_activeHats;
 697	m_activeHats = activeHats;
 698
 699	if (!QApplication::focusWidget()) {
 700		return;
 701	}
 702
 703	activeAxes.subtract(oldAxes);
 704	oldAxes.subtract(m_activeAxes);
 705
 706	for (auto& axis : m_activeAxes) {
 707		bool newlyAboveThreshold = activeAxes.contains(axis);
 708		if (newlyAboveThreshold) {
 709			GamepadAxisEvent* event = new GamepadAxisEvent(axis.first, axis.second, newlyAboveThreshold, type, this);
 710			postPendingEvent(event->gbaKey());
 711			sendGamepadEvent(event);
 712			if (!event->isAccepted()) {
 713				clearPendingEvent(event->gbaKey());
 714			}
 715		}
 716	}
 717	for (auto axis : oldAxes) {
 718		GamepadAxisEvent* event = new GamepadAxisEvent(axis.first, axis.second, false, type, this);
 719		clearPendingEvent(event->gbaKey());
 720		sendGamepadEvent(event);
 721	}
 722
 723	if (!QApplication::focusWidget()) {
 724		return;
 725	}
 726
 727	activeButtons.subtract(oldButtons);
 728	oldButtons.subtract(m_activeButtons);
 729
 730	for (int button : activeButtons) {
 731		GamepadButtonEvent* event = new GamepadButtonEvent(GamepadButtonEvent::Down(), button, type, this);
 732		postPendingEvent(event->gbaKey());
 733		sendGamepadEvent(event);
 734		if (!event->isAccepted()) {
 735			clearPendingEvent(event->gbaKey());
 736		}
 737	}
 738	for (int button : oldButtons) {
 739		GamepadButtonEvent* event = new GamepadButtonEvent(GamepadButtonEvent::Up(), button, type, this);
 740		clearPendingEvent(event->gbaKey());
 741		sendGamepadEvent(event);
 742	}
 743
 744	activeHats.subtract(oldHats);
 745	oldHats.subtract(m_activeHats);
 746
 747	for (auto& hat : activeHats) {
 748		GamepadHatEvent* event = new GamepadHatEvent(GamepadHatEvent::Down(), hat.first, hat.second, type, this);
 749		postPendingEvent(event->gbaKey());
 750		sendGamepadEvent(event);
 751		if (!event->isAccepted()) {
 752			clearPendingEvent(event->gbaKey());
 753		}
 754	}
 755	for (auto& hat : oldHats) {
 756		GamepadHatEvent* event = new GamepadHatEvent(GamepadHatEvent::Up(), hat.first, hat.second, type, this);
 757		clearPendingEvent(event->gbaKey());
 758		sendGamepadEvent(event);
 759	}
 760}
 761
 762void InputController::sendGamepadEvent(QEvent* event) {
 763	QWidget* focusWidget = nullptr;
 764	if (m_focusParent) {
 765		focusWidget = m_focusParent->focusWidget();
 766		if (!focusWidget) {
 767			focusWidget = m_focusParent;
 768		}
 769	} else {
 770		focusWidget = QApplication::focusWidget();
 771	}
 772	QApplication::sendEvent(focusWidget, event);
 773}
 774
 775void InputController::postPendingEvent(int key) {
 776	m_pendingEvents.insert(key);
 777}
 778
 779void InputController::clearPendingEvent(int key) {
 780	m_pendingEvents.remove(key);
 781}
 782
 783bool InputController::hasPendingEvent(int key) const {
 784	return m_pendingEvents.contains(key);
 785}
 786
 787void InputController::suspendScreensaver() {
 788#ifdef BUILD_SDL
 789#if SDL_VERSION_ATLEAST(2, 0, 0)
 790	mSDLSuspendScreensaver(&s_sdlEvents);
 791#endif
 792#endif
 793}
 794
 795void InputController::resumeScreensaver() {
 796#ifdef BUILD_SDL
 797#if SDL_VERSION_ATLEAST(2, 0, 0)
 798	mSDLResumeScreensaver(&s_sdlEvents);
 799#endif
 800#endif
 801}
 802
 803void InputController::setScreensaverSuspendable(bool suspendable) {
 804#ifdef BUILD_SDL
 805#if SDL_VERSION_ATLEAST(2, 0, 0)
 806	mSDLSetScreensaverSuspendable(&s_sdlEvents, suspendable);
 807#endif
 808#endif
 809}
 810
 811void InputController::stealFocus(QWidget* focus) {
 812	m_focusParent = focus;
 813}
 814
 815void InputController::releaseFocus(QWidget* focus) {
 816	if (focus == m_focusParent) {
 817		m_focusParent = m_topLevel;
 818	}
 819}
 820
 821bool InputController::eventFilter(QObject*, QEvent* event) {
 822	event->ignore();
 823	if (event->type() == QEvent::KeyPress || event->type() == QEvent::KeyRelease) {
 824		QKeyEvent* keyEvent = static_cast<QKeyEvent*>(event);
 825		int key = keyEvent->key();
 826		if (!InputIndex::isModifierKey(key)) {
 827			key |= (keyEvent->modifiers() & ~Qt::KeypadModifier);
 828		} else {
 829			key = InputIndex::toModifierKey(key | (keyEvent->modifiers() & ~Qt::KeypadModifier));
 830		}
 831
 832		if (keyEvent->isAutoRepeat()) {
 833			event->accept();
 834			return true;
 835		}
 836
 837		event->ignore();
 838		InputItem* item = m_inputIndex.itemForShortcut(key);
 839		if (item) {
 840			item->trigger(event->type() == QEvent::KeyPress);
 841			event->accept();
 842		}
 843		item = m_keyIndex.itemForShortcut(key);
 844		if (item) {
 845			item->trigger(event->type() == QEvent::KeyPress);
 846			event->accept();
 847		}
 848	}
 849
 850
 851	if (event->type() == GamepadButtonEvent::Down() || event->type() == GamepadButtonEvent::Up()) {
 852		GamepadButtonEvent* gbe = static_cast<GamepadButtonEvent*>(event);
 853		InputItem* item = m_inputIndex.itemForButton(gbe->value());
 854		if (item) {
 855			item->trigger(event->type() == GamepadButtonEvent::Down());
 856			event->accept();
 857		}
 858		item = m_keyIndex.itemForButton(gbe->value());
 859		if (item) {
 860			item->trigger(event->type() == GamepadButtonEvent::Down());
 861			event->accept();
 862		}
 863	}
 864	if (event->type() == GamepadAxisEvent::Type()) {
 865		GamepadAxisEvent* gae = static_cast<GamepadAxisEvent*>(event);
 866		InputItem* item = m_inputIndex.itemForAxis(gae->axis(), gae->direction());
 867		if (item) {
 868			item->trigger(event->type() == gae->isNew());
 869			event->accept();
 870		}
 871		item = m_keyIndex.itemForAxis(gae->axis(), gae->direction());
 872		if (item) {
 873			item->trigger(event->type() == gae->isNew());
 874			event->accept();
 875		}
 876	}
 877	return event->isAccepted();
 878}
 879
 880InputItem* InputController::itemForKey(const QString& key) {
 881	return m_keyIndex.itemAt(QString("key%0").arg(key));
 882}
 883
 884int InputController::keyId(const QString& key) {
 885	for (int i = 0; i < m_activeKeyInfo->nKeys; ++i) {
 886		if (m_activeKeyInfo->keyId[i] == key) {
 887			return i;
 888		}
 889	}
 890	return -1;
 891}
 892
 893void InputController::restoreModel() {
 894	if (!m_activeKeyInfo) {
 895		return;
 896	}
 897	int nKeys = m_inputMap.info->nKeys;
 898	for (int i = 0; i < nKeys; ++i) {
 899		const QString& keyName = m_inputMap.info->keyId[i];
 900		InputItem* item = itemForKey(keyName);
 901		if (item) {
 902			int key = mInputQueryBinding(&m_inputMap, KEYBOARD, i);
 903			if (key >= 0) {
 904				item->setShortcut(key);
 905			} else {
 906				item->clearShortcut();
 907			}
 908#ifdef BUILD_SDL
 909			key = mInputQueryBinding(&m_inputMap, SDL_BINDING_BUTTON, i);
 910			if (key >= 0) {
 911				item->setButton(key);
 912			} else {
 913				item->clearButton();
 914			}
 915#endif
 916		}
 917	}
 918#ifdef BUILD_SDL
 919	mInputEnumerateAxes(&m_inputMap, SDL_BINDING_BUTTON, [](int axis, const struct mInputAxis* description, void* user) {
 920		InputController* controller = static_cast<InputController*>(user);
 921		InputItem* item;
 922		const mInputPlatformInfo* inputMap = controller->m_inputMap.info;
 923		if (description->highDirection >= 0 && description->highDirection < controller->m_inputMap.info->nKeys) {
 924			int id = description->lowDirection;
 925			if (id >= 0 && id < inputMap->nKeys) {
 926				item = controller->itemForKey(inputMap->keyId[id]);
 927				if (item) {
 928					item->setAxis(axis, GamepadAxisEvent::POSITIVE);
 929				}
 930			}
 931		}
 932		if (description->lowDirection >= 0 && description->lowDirection < controller->m_inputMap.info->nKeys) {
 933			int id = description->highDirection;
 934			if (id >= 0 && id < inputMap->nKeys) {
 935				item = controller->itemForKey(inputMap->keyId[id]);
 936				if (item) {
 937					item->setAxis(axis, GamepadAxisEvent::NEGATIVE);
 938				}
 939			}
 940		}
 941	}, this);
 942#endif
 943	rebuildKeyIndex();
 944}
 945
 946void InputController::rebindKey(const QString& key) {
 947	InputItem* item = itemForKey(key);
 948	bindKey(KEYBOARD, item->shortcut(), key);
 949#ifdef BUILD_SDL
 950	bindKey(SDL_BINDING_BUTTON, item->button(), key);
 951	bindAxis(SDL_BINDING_BUTTON, item->axis(), item->direction(), key);
 952#endif
 953}
 954
 955void InputController::loadCamImage(const QString& path) {
 956	setCamImage(QImage(path));
 957}
 958
 959void InputController::setCamImage(const QImage& image) {
 960	if (image.isNull()) {
 961		return;
 962	}
 963	QMutexLocker locker(&m_image.mutex);
 964	m_image.image = image;
 965	m_image.resizedImage = QImage();
 966	m_image.outOfDate = true;
 967}
 968
 969QList<QPair<QByteArray, QString>> InputController::listCameras() const {
 970	QList<QPair<QByteArray, QString>> out;
 971#ifdef BUILD_QT_MULTIMEDIA
 972	QList<QCameraInfo> cams = QCameraInfo::availableCameras();
 973	for (const auto& cam : cams) {
 974		out.append(qMakePair(cam.deviceName().toLatin1(), cam.description()));
 975	}
 976#endif
 977	return out;
 978}
 979
 980void InputController::increaseLuminanceLevel() {
 981	setLuminanceLevel(m_luxLevel + 1);
 982}
 983
 984void InputController::decreaseLuminanceLevel() {
 985	setLuminanceLevel(m_luxLevel - 1);
 986}
 987
 988void InputController::setLuminanceLevel(int level) {
 989	int value = 0x16;
 990	level = std::max(0, std::min(10, level));
 991	if (level > 0) {
 992		value += GBA_LUX_LEVELS[level - 1];
 993	}
 994	setLuminanceValue(value);
 995}
 996
 997void InputController::setLuminanceValue(uint8_t value) {
 998	m_luxValue = value;
 999	value = std::max<int>(value - 0x16, 0);
1000	m_luxLevel = 10;
1001	for (int i = 0; i < 10; ++i) {
1002		if (value < GBA_LUX_LEVELS[i]) {
1003			m_luxLevel = i;
1004			break;
1005		}
1006	}
1007	emit luminanceValueChanged(m_luxValue);
1008}
1009
1010void InputController::setupCam() {
1011#ifdef BUILD_QT_MULTIMEDIA
1012	if (!m_camera) {
1013		m_camera = std::make_unique<QCamera>();
1014		connect(m_camera.get(), &QCamera::statusChanged, this, &InputController::prepareCamSettings, Qt::QueuedConnection);
1015	}
1016	m_camera->setCaptureMode(QCamera::CaptureVideo);
1017	m_camera->setViewfinder(&m_videoDumper);
1018	m_camera->load();
1019#endif
1020}
1021
1022#ifdef BUILD_QT_MULTIMEDIA
1023void InputController::prepareCamSettings(QCamera::Status status) {
1024	if (status != QCamera::LoadedStatus || m_camera->state() == QCamera::ActiveState) {
1025		return;
1026	}
1027#if (QT_VERSION >= QT_VERSION_CHECK(5, 5, 0))
1028	QVideoFrame::PixelFormat format(QVideoFrame::Format_RGB32);
1029	QCameraViewfinderSettings settings;
1030	QSize size(1280, 720);
1031	auto cameraRes = m_camera->supportedViewfinderResolutions(settings);
1032	for (auto& cameraSize : cameraRes) {
1033		if (cameraSize.width() < m_image.w || cameraSize.height() < m_image.h) {
1034			continue;
1035		}
1036		if (cameraSize.width() <= size.width() && cameraSize.height() <= size.height()) {
1037			size = cameraSize;
1038		}
1039	}
1040	settings.setResolution(size);
1041
1042	auto cameraFormats = m_camera->supportedViewfinderPixelFormats(settings);
1043	auto goodFormats = m_videoDumper.supportedPixelFormats();
1044	bool goodFormatFound = false;
1045	for (const auto& goodFormat : goodFormats) {
1046		if (cameraFormats.contains(goodFormat)) {
1047			settings.setPixelFormat(goodFormat);
1048			format = goodFormat;
1049			goodFormatFound = true;
1050			break;
1051		}
1052	}
1053	if (!goodFormatFound) {
1054		LOG(QT, WARN) << "Could not find a valid camera format!";
1055		for (const auto& format : cameraFormats) {
1056			LOG(QT, WARN) << "Camera supported format: " << QString::number(format);
1057		}
1058	}
1059	m_camera->setViewfinderSettings(settings);
1060#endif
1061	m_camera->start();
1062}
1063#endif
1064
1065void InputController::teardownCam() {
1066#ifdef BUILD_QT_MULTIMEDIA
1067	if (m_camera) {
1068		m_camera->stop();
1069	}
1070#endif
1071}
1072
1073void InputController::setCamera(const QByteArray& name) {
1074#ifdef BUILD_QT_MULTIMEDIA
1075	bool needsRestart = false;
1076	if (m_camera) {
1077		needsRestart = m_camera->state() == QCamera::ActiveState;
1078	}
1079	m_camera = std::make_unique<QCamera>(name);
1080	connect(m_camera.get(), &QCamera::statusChanged, this, &InputController::prepareCamSettings, Qt::QueuedConnection);
1081	if (needsRestart) {
1082		setupCam();
1083	}
1084#endif
1085}