all repos — mgba @ 1f156921732db400cfbb4a0ff3f8efc0faf5dd1e

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, const QString& device) {
 387	if (!m_config) {
 388		return;
 389	}
 390	mInputSetPreferredDevice(m_config->input(), "gba", type, m_playerId, device.toUtf8().constData());
 391}
 392
 393mRumble* InputController::rumble() {
 394#ifdef BUILD_SDL
 395#if SDL_VERSION_ATLEAST(2, 0, 0)
 396	if (m_playerAttached) {
 397		return &m_sdlPlayer.rumble.d;
 398	}
 399#endif
 400#endif
 401	return nullptr;
 402}
 403
 404mRotationSource* InputController::rotationSource() {
 405#ifdef BUILD_SDL
 406	if (m_playerAttached) {
 407		return &m_sdlPlayer.rotation.d;
 408	}
 409#endif
 410	return nullptr;
 411}
 412
 413void InputController::registerTiltAxisX(int axis) {
 414#ifdef BUILD_SDL
 415	if (m_playerAttached) {
 416		m_sdlPlayer.rotation.axisX = axis;
 417	}
 418#endif
 419}
 420
 421void InputController::registerTiltAxisY(int axis) {
 422#ifdef BUILD_SDL
 423	if (m_playerAttached) {
 424		m_sdlPlayer.rotation.axisY = axis;
 425	}
 426#endif
 427}
 428
 429void InputController::registerGyroAxisX(int axis) {
 430#ifdef BUILD_SDL
 431	if (m_playerAttached) {
 432		m_sdlPlayer.rotation.gyroX = axis;
 433	}
 434#endif
 435}
 436
 437void InputController::registerGyroAxisY(int axis) {
 438#ifdef BUILD_SDL
 439	if (m_playerAttached) {
 440		m_sdlPlayer.rotation.gyroY = axis;
 441	}
 442#endif
 443}
 444
 445float InputController::gyroSensitivity() const {
 446#ifdef BUILD_SDL
 447	if (m_playerAttached) {
 448		return m_sdlPlayer.rotation.gyroSensitivity;
 449	}
 450#endif
 451	return 0;
 452}
 453
 454void InputController::setGyroSensitivity(float sensitivity) {
 455#ifdef BUILD_SDL
 456	if (m_playerAttached) {
 457		m_sdlPlayer.rotation.gyroSensitivity = sensitivity;
 458	}
 459#endif
 460}
 461
 462void InputController::updateJoysticks() {
 463#ifdef BUILD_SDL
 464	QString profile = profileForType(SDL_BINDING_BUTTON);
 465	mSDLUpdateJoysticks(&s_sdlEvents, m_config->input());
 466	QString newProfile = profileForType(SDL_BINDING_BUTTON);
 467	if (profile != newProfile) {
 468		loadProfile(SDL_BINDING_BUTTON, newProfile);
 469	}
 470#endif
 471}
 472
 473const mInputMap* InputController::map() {
 474	if (!m_activeKeyInfo) {
 475		return nullptr;
 476	}
 477	return &m_inputMap;
 478}
 479
 480int InputController::pollEvents() {
 481	int activeButtons = m_activeKeys;
 482#ifdef BUILD_SDL
 483	if (m_playerAttached && m_sdlPlayer.joystick) {
 484		SDL_Joystick* joystick = m_sdlPlayer.joystick->joystick;
 485		SDL_JoystickUpdate();
 486		int numButtons = SDL_JoystickNumButtons(joystick);
 487		int i;
 488		for (i = 0; i < numButtons; ++i) {
 489			GBAKey key = static_cast<GBAKey>(mInputMapKey(&m_inputMap, SDL_BINDING_BUTTON, i));
 490			if (key == GBA_KEY_NONE) {
 491				continue;
 492			}
 493			if (hasPendingEvent(key)) {
 494				continue;
 495			}
 496			if (SDL_JoystickGetButton(joystick, i)) {
 497				activeButtons |= 1 << key;
 498			}
 499		}
 500		int numHats = SDL_JoystickNumHats(joystick);
 501		for (i = 0; i < numHats; ++i) {
 502			int hat = SDL_JoystickGetHat(joystick, i);
 503			activeButtons |= mInputMapHat(&m_inputMap, SDL_BINDING_BUTTON, i, hat);
 504		}
 505
 506		int numAxes = SDL_JoystickNumAxes(joystick);
 507		for (i = 0; i < numAxes; ++i) {
 508			int value = SDL_JoystickGetAxis(joystick, i);
 509
 510			enum GBAKey key = static_cast<GBAKey>(mInputMapAxis(&m_inputMap, SDL_BINDING_BUTTON, i, value));
 511			if (key != GBA_KEY_NONE) {
 512				activeButtons |= 1 << key;
 513			}
 514		}
 515	}
 516#endif
 517	return activeButtons;
 518}
 519
 520QSet<int> InputController::activeGamepadButtons(int type) {
 521	QSet<int> activeButtons;
 522#ifdef BUILD_SDL
 523	if (m_playerAttached && type == SDL_BINDING_BUTTON && m_sdlPlayer.joystick) {
 524		SDL_Joystick* joystick = m_sdlPlayer.joystick->joystick;
 525		SDL_JoystickUpdate();
 526		int numButtons = SDL_JoystickNumButtons(joystick);
 527		int i;
 528		for (i = 0; i < numButtons; ++i) {
 529			if (SDL_JoystickGetButton(joystick, i)) {
 530				activeButtons.insert(i);
 531			}
 532		}
 533	}
 534#endif
 535	return activeButtons;
 536}
 537
 538void InputController::recalibrateAxes() {
 539#ifdef BUILD_SDL
 540	if (m_playerAttached && m_sdlPlayer.joystick) {
 541		SDL_Joystick* joystick = m_sdlPlayer.joystick->joystick;
 542		SDL_JoystickUpdate();
 543		int numAxes = SDL_JoystickNumAxes(joystick);
 544		if (numAxes < 1) {
 545			return;
 546		}
 547		m_deadzones.resize(numAxes);
 548		int i;
 549		for (i = 0; i < numAxes; ++i) {
 550			m_deadzones[i] = SDL_JoystickGetAxis(joystick, i);
 551		}
 552	}
 553#endif
 554}
 555
 556QSet<QPair<int, GamepadAxisEvent::Direction>> InputController::activeGamepadAxes(int type) {
 557	QSet<QPair<int, GamepadAxisEvent::Direction>> activeAxes;
 558#ifdef BUILD_SDL
 559	if (m_playerAttached && type == SDL_BINDING_BUTTON && m_sdlPlayer.joystick) {
 560		SDL_Joystick* joystick = m_sdlPlayer.joystick->joystick;
 561		SDL_JoystickUpdate();
 562		int numAxes = SDL_JoystickNumAxes(joystick);
 563		if (numAxes < 1) {
 564			return activeAxes;
 565		}
 566		m_deadzones.resize(numAxes);
 567		int i;
 568		for (i = 0; i < numAxes; ++i) {
 569			int32_t axis = SDL_JoystickGetAxis(joystick, i);
 570			axis -= m_deadzones[i];
 571			if (axis >= AXIS_THRESHOLD || axis <= -AXIS_THRESHOLD) {
 572				activeAxes.insert(qMakePair(i, axis > 0 ? GamepadAxisEvent::POSITIVE : GamepadAxisEvent::NEGATIVE));
 573			}
 574		}
 575	}
 576#endif
 577	return activeAxes;
 578}
 579
 580void InputController::bindKey(uint32_t type, int key, const QString& keyName) {
 581	InputItem* item = itemForKey(keyName);
 582	if (type != KEYBOARD) {
 583		item->setButton(key);
 584	} else {
 585		item->setShortcut(key);
 586	}
 587	if (m_activeKeyInfo) {
 588		int coreKey = keyId(keyName);
 589		mInputBindKey(&m_inputMap, type, key, coreKey);
 590	}
 591}
 592
 593void InputController::bindAxis(uint32_t type, int axis, GamepadAxisEvent::Direction direction, const QString& key) {
 594	InputItem* item = itemForKey(key);
 595	item->setAxis(axis, direction);
 596	
 597	if (!m_activeKeyInfo) {
 598		return;
 599	}
 600
 601	const mInputAxis* old = mInputQueryAxis(&m_inputMap, type, axis);
 602	mInputAxis description = { GBA_KEY_NONE, GBA_KEY_NONE, -AXIS_THRESHOLD, AXIS_THRESHOLD };
 603	if (old) {
 604		description = *old;
 605	}
 606	int deadzone = 0;
 607	if (axis > 0 && m_deadzones.size() > axis) {
 608		deadzone = m_deadzones[axis];
 609	}
 610	switch (direction) {
 611	case GamepadAxisEvent::NEGATIVE:
 612		description.lowDirection = keyId(key);
 613
 614		description.deadLow = deadzone - AXIS_THRESHOLD;
 615		break;
 616	case GamepadAxisEvent::POSITIVE:
 617		description.highDirection = keyId(key);
 618		description.deadHigh = deadzone + AXIS_THRESHOLD;
 619		break;
 620	default:
 621		return;
 622	}
 623	mInputBindAxis(&m_inputMap, type, axis, &description);
 624}
 625
 626QSet<QPair<int, GamepadHatEvent::Direction>> InputController::activeGamepadHats(int type) {
 627	QSet<QPair<int, GamepadHatEvent::Direction>> activeHats;
 628#ifdef BUILD_SDL
 629	if (m_playerAttached && type == SDL_BINDING_BUTTON && m_sdlPlayer.joystick) {
 630		SDL_Joystick* joystick = m_sdlPlayer.joystick->joystick;
 631		SDL_JoystickUpdate();
 632		int numHats = SDL_JoystickNumHats(joystick);
 633		if (numHats < 1) {
 634			return activeHats;
 635		}
 636
 637		int i;
 638		for (i = 0; i < numHats; ++i) {
 639			int hat = SDL_JoystickGetHat(joystick, i);
 640			if (hat & GamepadHatEvent::UP) {
 641				activeHats.insert(qMakePair(i, GamepadHatEvent::UP));
 642			}
 643			if (hat & GamepadHatEvent::RIGHT) {
 644				activeHats.insert(qMakePair(i, GamepadHatEvent::RIGHT));
 645			}
 646			if (hat & GamepadHatEvent::DOWN) {
 647				activeHats.insert(qMakePair(i, GamepadHatEvent::DOWN));
 648			}
 649			if (hat & GamepadHatEvent::LEFT) {
 650				activeHats.insert(qMakePair(i, GamepadHatEvent::LEFT));
 651			}
 652		}
 653	}
 654#endif
 655	return activeHats;
 656}
 657
 658void InputController::bindHat(uint32_t type, int hat, GamepadHatEvent::Direction direction, const QString& key) {
 659	if (!m_activeKeyInfo) {
 660		return;
 661	}
 662
 663	mInputHatBindings bindings{ -1, -1, -1, -1 };
 664	mInputQueryHat(&m_inputMap, type, hat, &bindings);
 665	switch (direction) {
 666	case GamepadHatEvent::UP:
 667		bindings.up = keyId(key);
 668		break;
 669	case GamepadHatEvent::RIGHT:
 670		bindings.right = keyId(key);
 671		break;
 672	case GamepadHatEvent::DOWN:
 673		bindings.down = keyId(key);
 674		break;
 675	case GamepadHatEvent::LEFT:
 676		bindings.left = keyId(key);
 677		break;
 678	default:
 679		return;
 680	}
 681	mInputBindHat(&m_inputMap, type, hat, &bindings);
 682}
 683
 684void InputController::testGamepad(int type) {
 685	auto activeAxes = activeGamepadAxes(type);
 686	auto oldAxes = m_activeAxes;
 687	m_activeAxes = activeAxes;
 688
 689	auto activeButtons = activeGamepadButtons(type);
 690	auto oldButtons = m_activeButtons;
 691	m_activeButtons = activeButtons;
 692
 693	auto activeHats = activeGamepadHats(type);
 694	auto oldHats = m_activeHats;
 695	m_activeHats = activeHats;
 696
 697	if (!QApplication::focusWidget()) {
 698		return;
 699	}
 700
 701	activeAxes.subtract(oldAxes);
 702	oldAxes.subtract(m_activeAxes);
 703
 704	for (auto& axis : m_activeAxes) {
 705		bool newlyAboveThreshold = activeAxes.contains(axis);
 706		if (newlyAboveThreshold) {
 707			GamepadAxisEvent* event = new GamepadAxisEvent(axis.first, axis.second, newlyAboveThreshold, type, this);
 708			postPendingEvent(event->gbaKey());
 709			sendGamepadEvent(event);
 710			if (!event->isAccepted()) {
 711				clearPendingEvent(event->gbaKey());
 712			}
 713		}
 714	}
 715	for (auto axis : oldAxes) {
 716		GamepadAxisEvent* event = new GamepadAxisEvent(axis.first, axis.second, false, type, this);
 717		clearPendingEvent(event->gbaKey());
 718		sendGamepadEvent(event);
 719	}
 720
 721	if (!QApplication::focusWidget()) {
 722		return;
 723	}
 724
 725	activeButtons.subtract(oldButtons);
 726	oldButtons.subtract(m_activeButtons);
 727
 728	for (int button : activeButtons) {
 729		GamepadButtonEvent* event = new GamepadButtonEvent(GamepadButtonEvent::Down(), button, type, this);
 730		postPendingEvent(event->gbaKey());
 731		sendGamepadEvent(event);
 732		if (!event->isAccepted()) {
 733			clearPendingEvent(event->gbaKey());
 734		}
 735	}
 736	for (int button : oldButtons) {
 737		GamepadButtonEvent* event = new GamepadButtonEvent(GamepadButtonEvent::Up(), button, type, this);
 738		clearPendingEvent(event->gbaKey());
 739		sendGamepadEvent(event);
 740	}
 741
 742	activeHats.subtract(oldHats);
 743	oldHats.subtract(m_activeHats);
 744
 745	for (auto& hat : activeHats) {
 746		GamepadHatEvent* event = new GamepadHatEvent(GamepadHatEvent::Down(), hat.first, hat.second, type, this);
 747		postPendingEvent(event->gbaKey());
 748		sendGamepadEvent(event);
 749		if (!event->isAccepted()) {
 750			clearPendingEvent(event->gbaKey());
 751		}
 752	}
 753	for (auto& hat : oldHats) {
 754		GamepadHatEvent* event = new GamepadHatEvent(GamepadHatEvent::Up(), hat.first, hat.second, type, this);
 755		clearPendingEvent(event->gbaKey());
 756		sendGamepadEvent(event);
 757	}
 758}
 759
 760void InputController::sendGamepadEvent(QEvent* event) {
 761	QWidget* focusWidget = nullptr;
 762	if (m_focusParent) {
 763		focusWidget = m_focusParent->focusWidget();
 764		if (!focusWidget) {
 765			focusWidget = m_focusParent;
 766		}
 767	} else {
 768		focusWidget = QApplication::focusWidget();
 769	}
 770	QApplication::sendEvent(focusWidget, event);
 771}
 772
 773void InputController::postPendingEvent(int key) {
 774	m_pendingEvents.insert(key);
 775}
 776
 777void InputController::clearPendingEvent(int key) {
 778	m_pendingEvents.remove(key);
 779}
 780
 781bool InputController::hasPendingEvent(int key) const {
 782	return m_pendingEvents.contains(key);
 783}
 784
 785void InputController::suspendScreensaver() {
 786#ifdef BUILD_SDL
 787#if SDL_VERSION_ATLEAST(2, 0, 0)
 788	mSDLSuspendScreensaver(&s_sdlEvents);
 789#endif
 790#endif
 791}
 792
 793void InputController::resumeScreensaver() {
 794#ifdef BUILD_SDL
 795#if SDL_VERSION_ATLEAST(2, 0, 0)
 796	mSDLResumeScreensaver(&s_sdlEvents);
 797#endif
 798#endif
 799}
 800
 801void InputController::setScreensaverSuspendable(bool suspendable) {
 802#ifdef BUILD_SDL
 803#if SDL_VERSION_ATLEAST(2, 0, 0)
 804	mSDLSetScreensaverSuspendable(&s_sdlEvents, suspendable);
 805#endif
 806#endif
 807}
 808
 809void InputController::stealFocus(QWidget* focus) {
 810	m_focusParent = focus;
 811}
 812
 813void InputController::releaseFocus(QWidget* focus) {
 814	if (focus == m_focusParent) {
 815		m_focusParent = m_topLevel;
 816	}
 817}
 818
 819bool InputController::eventFilter(QObject*, QEvent* event) {
 820	event->ignore();
 821	if (event->type() == QEvent::KeyPress || event->type() == QEvent::KeyRelease) {
 822		QKeyEvent* keyEvent = static_cast<QKeyEvent*>(event);
 823		int key = keyEvent->key();
 824		if (!InputIndex::isModifierKey(key)) {
 825			key |= (keyEvent->modifiers() & ~Qt::KeypadModifier);
 826		} else {
 827			key = InputIndex::toModifierKey(key | (keyEvent->modifiers() & ~Qt::KeypadModifier));
 828		}
 829
 830		if (keyEvent->isAutoRepeat()) {
 831			event->accept();
 832			return true;
 833		}
 834
 835		event->ignore();
 836		InputItem* item = m_inputIndex.itemForShortcut(key);
 837		if (item) {
 838			item->trigger(event->type() == QEvent::KeyPress);
 839			event->accept();
 840		}
 841		item = m_keyIndex.itemForShortcut(key);
 842		if (item) {
 843			item->trigger(event->type() == QEvent::KeyPress);
 844			event->accept();
 845		}
 846	}
 847
 848
 849	if (event->type() == GamepadButtonEvent::Down() || event->type() == GamepadButtonEvent::Up()) {
 850		GamepadButtonEvent* gbe = static_cast<GamepadButtonEvent*>(event);
 851		InputItem* item = m_inputIndex.itemForButton(gbe->value());
 852		if (item) {
 853			item->trigger(event->type() == GamepadButtonEvent::Down());
 854			event->accept();
 855		}
 856		item = m_keyIndex.itemForButton(gbe->value());
 857		if (item) {
 858			item->trigger(event->type() == GamepadButtonEvent::Down());
 859			event->accept();
 860		}
 861	}
 862	if (event->type() == GamepadAxisEvent::Type()) {
 863		GamepadAxisEvent* gae = static_cast<GamepadAxisEvent*>(event);
 864		InputItem* item = m_inputIndex.itemForAxis(gae->axis(), gae->direction());
 865		if (item) {
 866			item->trigger(event->type() == gae->isNew());
 867			event->accept();
 868		}
 869		item = m_keyIndex.itemForAxis(gae->axis(), gae->direction());
 870		if (item) {
 871			item->trigger(event->type() == gae->isNew());
 872			event->accept();
 873		}
 874	}
 875	return event->isAccepted();
 876}
 877
 878InputItem* InputController::itemForKey(const QString& key) {
 879	return m_keyIndex.itemAt(QString("key%0").arg(key));
 880}
 881
 882int InputController::keyId(const QString& key) {
 883	for (int i = 0; i < m_activeKeyInfo->nKeys; ++i) {
 884		if (m_activeKeyInfo->keyId[i] == key) {
 885			return i;
 886		}
 887	}
 888	return -1;
 889}
 890
 891void InputController::restoreModel() {
 892	if (!m_activeKeyInfo) {
 893		return;
 894	}
 895	int nKeys = m_inputMap.info->nKeys;
 896	for (int i = 0; i < nKeys; ++i) {
 897		const QString& keyName = m_inputMap.info->keyId[i];
 898		InputItem* item = itemForKey(keyName);
 899		if (item) {
 900			int key = mInputQueryBinding(&m_inputMap, KEYBOARD, i);
 901			if (key >= 0) {
 902				item->setShortcut(key);
 903			} else {
 904				item->clearShortcut();
 905			}
 906#ifdef BUILD_SDL
 907			key = mInputQueryBinding(&m_inputMap, SDL_BINDING_BUTTON, i);
 908			if (key >= 0) {
 909				item->setButton(key);
 910			} else {
 911				item->clearButton();
 912			}
 913#endif
 914		}
 915	}
 916#ifdef BUILD_SDL
 917	mInputEnumerateAxes(&m_inputMap, SDL_BINDING_BUTTON, [](int axis, const struct mInputAxis* description, void* user) {
 918		InputController* controller = static_cast<InputController*>(user);
 919		InputItem* item;
 920		const mInputPlatformInfo* inputMap = controller->m_inputMap.info;
 921		if (description->highDirection >= 0 && description->highDirection < controller->m_inputMap.info->nKeys) {
 922			int id = description->lowDirection;
 923			if (id >= 0 && id < inputMap->nKeys) {
 924				item = controller->itemForKey(inputMap->keyId[id]);
 925				if (item) {
 926					item->setAxis(axis, GamepadAxisEvent::POSITIVE);
 927				}
 928			}
 929		}
 930		if (description->lowDirection >= 0 && description->lowDirection < controller->m_inputMap.info->nKeys) {
 931			int id = description->highDirection;
 932			if (id >= 0 && id < inputMap->nKeys) {
 933				item = controller->itemForKey(inputMap->keyId[id]);
 934				if (item) {
 935					item->setAxis(axis, GamepadAxisEvent::NEGATIVE);
 936				}
 937			}
 938		}
 939	}, this);
 940#endif
 941	rebuildKeyIndex();
 942}
 943
 944void InputController::rebindKey(const QString& key) {
 945	InputItem* item = itemForKey(key);
 946	bindKey(KEYBOARD, item->shortcut(), key);
 947#ifdef BUILD_SDL
 948	bindKey(SDL_BINDING_BUTTON, item->button(), key);
 949	bindAxis(SDL_BINDING_BUTTON, item->axis(), item->direction(), key);
 950#endif
 951}
 952
 953void InputController::loadCamImage(const QString& path) {
 954	setCamImage(QImage(path));
 955}
 956
 957void InputController::setCamImage(const QImage& image) {
 958	if (image.isNull()) {
 959		return;
 960	}
 961	QMutexLocker locker(&m_image.mutex);
 962	m_image.image = image;
 963	m_image.resizedImage = QImage();
 964	m_image.outOfDate = true;
 965}
 966
 967QList<QPair<QByteArray, QString>> InputController::listCameras() const {
 968	QList<QPair<QByteArray, QString>> out;
 969#ifdef BUILD_QT_MULTIMEDIA
 970	QList<QCameraInfo> cams = QCameraInfo::availableCameras();
 971	for (const auto& cam : cams) {
 972		out.append(qMakePair(cam.deviceName().toLatin1(), cam.description()));
 973	}
 974#endif
 975	return out;
 976}
 977
 978void InputController::increaseLuminanceLevel() {
 979	setLuminanceLevel(m_luxLevel + 1);
 980}
 981
 982void InputController::decreaseLuminanceLevel() {
 983	setLuminanceLevel(m_luxLevel - 1);
 984}
 985
 986void InputController::setLuminanceLevel(int level) {
 987	int value = 0x16;
 988	level = std::max(0, std::min(10, level));
 989	if (level > 0) {
 990		value += GBA_LUX_LEVELS[level - 1];
 991	}
 992	setLuminanceValue(value);
 993}
 994
 995void InputController::setLuminanceValue(uint8_t value) {
 996	m_luxValue = value;
 997	value = std::max<int>(value - 0x16, 0);
 998	m_luxLevel = 10;
 999	for (int i = 0; i < 10; ++i) {
1000		if (value < GBA_LUX_LEVELS[i]) {
1001			m_luxLevel = i;
1002			break;
1003		}
1004	}
1005	emit luminanceValueChanged(m_luxValue);
1006}
1007
1008void InputController::setupCam() {
1009#ifdef BUILD_QT_MULTIMEDIA
1010	if (!m_camera) {
1011		m_camera = std::make_unique<QCamera>();
1012		connect(m_camera.get(), &QCamera::statusChanged, this, &InputController::prepareCamSettings, Qt::QueuedConnection);
1013	}
1014	m_camera->setCaptureMode(QCamera::CaptureVideo);
1015	m_camera->setViewfinder(&m_videoDumper);
1016	m_camera->load();
1017#endif
1018}
1019
1020#ifdef BUILD_QT_MULTIMEDIA
1021void InputController::prepareCamSettings(QCamera::Status status) {
1022	if (status != QCamera::LoadedStatus || m_camera->state() == QCamera::ActiveState) {
1023		return;
1024	}
1025#if (QT_VERSION >= QT_VERSION_CHECK(5, 5, 0))
1026	QVideoFrame::PixelFormat format(QVideoFrame::Format_RGB32);
1027	QCameraViewfinderSettings settings;
1028	QSize size(1280, 720);
1029	auto cameraRes = m_camera->supportedViewfinderResolutions(settings);
1030	for (auto& cameraSize : cameraRes) {
1031		if (cameraSize.width() < m_image.w || cameraSize.height() < m_image.h) {
1032			continue;
1033		}
1034		if (cameraSize.width() <= size.width() && cameraSize.height() <= size.height()) {
1035			size = cameraSize;
1036		}
1037	}
1038	settings.setResolution(size);
1039
1040	auto cameraFormats = m_camera->supportedViewfinderPixelFormats(settings);
1041	auto goodFormats = m_videoDumper.supportedPixelFormats();
1042	bool goodFormatFound = false;
1043	for (const auto& goodFormat : goodFormats) {
1044		if (cameraFormats.contains(goodFormat)) {
1045			settings.setPixelFormat(goodFormat);
1046			format = goodFormat;
1047			goodFormatFound = true;
1048			break;
1049		}
1050	}
1051	if (!goodFormatFound) {
1052		LOG(QT, WARN) << "Could not find a valid camera format!";
1053		for (const auto& format : cameraFormats) {
1054			LOG(QT, WARN) << "Camera supported format: " << QString::number(format);
1055		}
1056	}
1057	m_camera->setViewfinderSettings(settings);
1058#endif
1059	m_camera->start();
1060}
1061#endif
1062
1063void InputController::teardownCam() {
1064#ifdef BUILD_QT_MULTIMEDIA
1065	if (m_camera) {
1066		m_camera->stop();
1067	}
1068#endif
1069}
1070
1071void InputController::setCamera(const QByteArray& name) {
1072#ifdef BUILD_QT_MULTIMEDIA
1073	bool needsRestart = false;
1074	if (m_camera) {
1075		needsRestart = m_camera->state() == QCamera::ActiveState;
1076	}
1077	m_camera = std::make_unique<QCamera>(name);
1078	connect(m_camera.get(), &QCamera::statusChanged, this, &InputController::prepareCamSettings, Qt::QueuedConnection);
1079	if (needsRestart) {
1080		setupCam();
1081	}
1082#endif
1083}