all repos — mgba @ 51030d98fd01679834abf8d99812ac3e5fe0793e

mGBA Game Boy Advance Emulator

src/platform/qt/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 "GamepadAxisEvent.h"
 10#include "GamepadButtonEvent.h"
 11#include "InputProfile.h"
 12#include "LogController.h"
 13
 14#include <QApplication>
 15#include <QTimer>
 16#include <QWidget>
 17#ifdef BUILD_QT_MULTIMEDIA
 18#include <QCameraInfo>
 19#include <QVideoSurfaceFormat>
 20#endif
 21
 22#include <mgba/core/interface.h>
 23#include <mgba-util/configuration.h>
 24
 25using namespace QGBA;
 26
 27#ifdef BUILD_SDL
 28int InputController::s_sdlInited = 0;
 29mSDLEvents InputController::s_sdlEvents;
 30#endif
 31
 32InputController::InputController(int playerId, QWidget* topLevel, QObject* parent)
 33	: QObject(parent)
 34	, m_playerId(playerId)
 35	, m_topLevel(topLevel)
 36	, m_focusParent(topLevel)
 37{
 38	mInputMapInit(&m_inputMap, &GBAInputInfo);
 39
 40#ifdef BUILD_SDL
 41	if (s_sdlInited == 0) {
 42		mSDLInitEvents(&s_sdlEvents);
 43	}
 44	++s_sdlInited;
 45	m_sdlPlayer.bindings = &m_inputMap;
 46	mSDLInitBindingsGBA(&m_inputMap);
 47	updateJoysticks();
 48#endif
 49
 50#ifdef BUILD_SDL
 51	connect(&m_gamepadTimer, &QTimer::timeout, [this]() {
 52		testGamepad(SDL_BINDING_BUTTON);
 53		if (m_playerId == 0) {
 54			updateJoysticks();
 55		}
 56	});
 57#endif
 58	m_gamepadTimer.setInterval(50);
 59	m_gamepadTimer.start();
 60
 61#ifdef BUILD_QT_MULTIMEDIA
 62	connect(&m_videoDumper, &VideoDumper::imageAvailable, this, &InputController::setCamImage);
 63#endif
 64
 65	mInputBindKey(&m_inputMap, KEYBOARD, Qt::Key_X, GBA_KEY_A);
 66	mInputBindKey(&m_inputMap, KEYBOARD, Qt::Key_Z, GBA_KEY_B);
 67	mInputBindKey(&m_inputMap, KEYBOARD, Qt::Key_A, GBA_KEY_L);
 68	mInputBindKey(&m_inputMap, KEYBOARD, Qt::Key_S, GBA_KEY_R);
 69	mInputBindKey(&m_inputMap, KEYBOARD, Qt::Key_Return, GBA_KEY_START);
 70	mInputBindKey(&m_inputMap, KEYBOARD, Qt::Key_Backspace, GBA_KEY_SELECT);
 71	mInputBindKey(&m_inputMap, KEYBOARD, Qt::Key_Up, GBA_KEY_UP);
 72	mInputBindKey(&m_inputMap, KEYBOARD, Qt::Key_Down, GBA_KEY_DOWN);
 73	mInputBindKey(&m_inputMap, KEYBOARD, Qt::Key_Left, GBA_KEY_LEFT);
 74	mInputBindKey(&m_inputMap, KEYBOARD, Qt::Key_Right, GBA_KEY_RIGHT);
 75
 76
 77#ifdef M_CORE_GBA
 78	m_lux.p = this;
 79	m_lux.sample = [](GBALuminanceSource* context) {
 80		InputControllerLux* lux = static_cast<InputControllerLux*>(context);
 81		lux->value = 0xFF - lux->p->m_luxValue;
 82	};
 83
 84	m_lux.readLuminance = [](GBALuminanceSource* context) {
 85		InputControllerLux* lux = static_cast<InputControllerLux*>(context);
 86		return lux->value;
 87	};
 88	setLuminanceLevel(0);
 89#endif
 90
 91	m_image.p = this;
 92	m_image.startRequestImage = [](mImageSource* context, unsigned w, unsigned h, int) {
 93		InputControllerImage* image = static_cast<InputControllerImage*>(context);
 94		image->w = w;
 95		image->h = h;
 96		if (image->image.isNull()) {
 97			image->image.load(":/res/no-cam.png");
 98		}
 99#ifdef BUILD_QT_MULTIMEDIA
100		if (image->p->m_config->getQtOption("cameraDriver").toInt() == static_cast<int>(CameraDriver::QT_MULTIMEDIA)) {
101			QByteArray camera = image->p->m_config->getQtOption("camera").toByteArray();
102			if (!camera.isNull()) {
103				QMetaObject::invokeMethod(image->p, "setCamera", Q_ARG(QByteArray, camera));
104			}
105			QMetaObject::invokeMethod(image->p, "setupCam");
106		}
107#endif
108	};
109
110	m_image.stopRequestImage = [](mImageSource* context) {
111		InputControllerImage* image = static_cast<InputControllerImage*>(context);
112#ifdef BUILD_QT_MULTIMEDIA
113		QMetaObject::invokeMethod(image->p, "teardownCam");
114#endif
115	};
116
117	m_image.requestImage = [](mImageSource* context, const void** buffer, size_t* stride, mColorFormat* format) {
118		InputControllerImage* image = static_cast<InputControllerImage*>(context);
119		QSize size;
120		{
121			QMutexLocker locker(&image->mutex);
122			if (image->outOfDate) {
123				image->resizedImage = image->image.scaled(image->w, image->h, Qt::KeepAspectRatioByExpanding);
124				image->resizedImage = image->resizedImage.convertToFormat(QImage::Format_RGB16);
125				image->outOfDate = false;
126			}
127		}
128		size = image->resizedImage.size();
129		const uint16_t* bits = reinterpret_cast<const uint16_t*>(image->resizedImage.constBits());
130		if (size.width() > image->w) {
131			bits += (size.width() - image->w) / 2;
132		}
133		if (size.height() > image->h) {
134			bits += ((size.height() - image->h) / 2) * size.width();
135		}
136		*buffer = bits;
137		*stride = image->resizedImage.bytesPerLine() / sizeof(*bits);
138		*format = mCOLOR_RGB565;
139	};
140}
141
142InputController::~InputController() {
143	mInputMapDeinit(&m_inputMap);
144
145#ifdef BUILD_SDL
146	if (m_playerAttached) {
147		mSDLDetachPlayer(&s_sdlEvents, &m_sdlPlayer);
148	}
149
150	--s_sdlInited;
151	if (s_sdlInited == 0) {
152		mSDLDeinitEvents(&s_sdlEvents);
153	}
154#endif
155}
156
157void InputController::setConfiguration(ConfigController* config) {
158	m_config = config;
159	loadConfiguration(KEYBOARD);
160#ifdef BUILD_SDL
161	mSDLEventsLoadConfig(&s_sdlEvents, config->input());
162	if (!m_playerAttached) {
163		m_playerAttached = mSDLAttachPlayer(&s_sdlEvents, &m_sdlPlayer);
164	}
165	loadConfiguration(SDL_BINDING_BUTTON);
166	loadProfile(SDL_BINDING_BUTTON, profileForType(SDL_BINDING_BUTTON));
167#endif
168}
169
170void InputController::loadConfiguration(uint32_t type) {
171	mInputMapLoad(&m_inputMap, type, m_config->input());
172#ifdef BUILD_SDL
173	if (m_playerAttached) {
174		mSDLPlayerLoadConfig(&m_sdlPlayer, m_config->input());
175	}
176#endif
177}
178
179void InputController::loadProfile(uint32_t type, const QString& profile) {
180	bool loaded = mInputProfileLoad(&m_inputMap, type, m_config->input(), profile.toUtf8().constData());
181	recalibrateAxes();
182	if (!loaded) {
183		const InputProfile* ip = InputProfile::findProfile(profile);
184		if (ip) {
185			ip->apply(this);
186		}
187	}
188	emit profileLoaded(profile);
189}
190
191void InputController::saveConfiguration() {
192	saveConfiguration(KEYBOARD);
193#ifdef BUILD_SDL
194	saveConfiguration(SDL_BINDING_BUTTON);
195	saveProfile(SDL_BINDING_BUTTON, profileForType(SDL_BINDING_BUTTON));
196	if (m_playerAttached) {
197		mSDLPlayerSaveConfig(&m_sdlPlayer, m_config->input());
198	}
199#endif
200	m_config->write();
201}
202
203void InputController::saveConfiguration(uint32_t type) {
204	mInputMapSave(&m_inputMap, type, m_config->input());
205	m_config->write();
206}
207
208void InputController::saveProfile(uint32_t type, const QString& profile) {
209	mInputProfileSave(&m_inputMap, type, m_config->input(), profile.toUtf8().constData());
210	m_config->write();
211}
212
213const char* InputController::profileForType(uint32_t type) {
214	UNUSED(type);
215#ifdef BUILD_SDL
216	if (type == SDL_BINDING_BUTTON && m_sdlPlayer.joystick) {
217#if SDL_VERSION_ATLEAST(2, 0, 0)
218		return SDL_JoystickName(m_sdlPlayer.joystick->joystick);
219#else
220		return SDL_JoystickName(SDL_JoystickIndex(m_sdlPlayer.joystick->joystick));
221#endif
222	}
223#endif
224	return 0;
225}
226
227QStringList InputController::connectedGamepads(uint32_t type) const {
228	UNUSED(type);
229
230#ifdef BUILD_SDL
231	if (type == SDL_BINDING_BUTTON) {
232		QStringList pads;
233		for (size_t i = 0; i < SDL_JoystickListSize(&s_sdlEvents.joysticks); ++i) {
234			const char* name;
235#if SDL_VERSION_ATLEAST(2, 0, 0)
236			name = SDL_JoystickName(SDL_JoystickListGetPointer(&s_sdlEvents.joysticks, i)->joystick);
237#else
238			name = SDL_JoystickName(SDL_JoystickIndex(SDL_JoystickListGetPointer(&s_sdlEvents.joysticks, i)->joystick));
239#endif
240			if (name) {
241				pads.append(QString(name));
242			} else {
243				pads.append(QString());
244			}
245		}
246		return pads;
247	}
248#endif
249
250	return QStringList();
251}
252
253int InputController::gamepad(uint32_t type) const {
254#ifdef BUILD_SDL
255	if (type == SDL_BINDING_BUTTON) {
256		return m_sdlPlayer.joystick ? m_sdlPlayer.joystick->index : 0;
257	}
258#endif
259	return 0;
260}
261
262void InputController::setGamepad(uint32_t type, int index) {
263#ifdef BUILD_SDL
264	if (type == SDL_BINDING_BUTTON) {
265		mSDLPlayerChangeJoystick(&s_sdlEvents, &m_sdlPlayer, index);
266	}
267#endif
268}
269
270void InputController::setPreferredGamepad(uint32_t type, const QString& device) {
271	if (!m_config) {
272		return;
273	}
274	mInputSetPreferredDevice(m_config->input(), "gba", type, m_playerId, device.toUtf8().constData());
275}
276
277mRumble* InputController::rumble() {
278#ifdef BUILD_SDL
279#if SDL_VERSION_ATLEAST(2, 0, 0)
280	if (m_playerAttached) {
281		return &m_sdlPlayer.rumble.d;
282	}
283#endif
284#endif
285	return nullptr;
286}
287
288mRotationSource* InputController::rotationSource() {
289#ifdef BUILD_SDL
290	if (m_playerAttached) {
291		return &m_sdlPlayer.rotation.d;
292	}
293#endif
294	return nullptr;
295}
296
297void InputController::registerTiltAxisX(int axis) {
298#ifdef BUILD_SDL
299	if (m_playerAttached) {
300		m_sdlPlayer.rotation.axisX = axis;
301	}
302#endif
303}
304
305void InputController::registerTiltAxisY(int axis) {
306#ifdef BUILD_SDL
307	if (m_playerAttached) {
308		m_sdlPlayer.rotation.axisY = axis;
309	}
310#endif
311}
312
313void InputController::registerGyroAxisX(int axis) {
314#ifdef BUILD_SDL
315	if (m_playerAttached) {
316		m_sdlPlayer.rotation.gyroX = axis;
317	}
318#endif
319}
320
321void InputController::registerGyroAxisY(int axis) {
322#ifdef BUILD_SDL
323	if (m_playerAttached) {
324		m_sdlPlayer.rotation.gyroY = axis;
325	}
326#endif
327}
328
329float InputController::gyroSensitivity() const {
330#ifdef BUILD_SDL
331	if (m_playerAttached) {
332		return m_sdlPlayer.rotation.gyroSensitivity;
333	}
334#endif
335	return 0;
336}
337
338void InputController::setGyroSensitivity(float sensitivity) {
339#ifdef BUILD_SDL
340	if (m_playerAttached) {
341		m_sdlPlayer.rotation.gyroSensitivity = sensitivity;
342	}
343#endif
344}
345
346GBAKey InputController::mapKeyboard(int key) const {
347	return static_cast<GBAKey>(mInputMapKey(&m_inputMap, KEYBOARD, key));
348}
349
350void InputController::bindKey(uint32_t type, int key, GBAKey gbaKey) {
351	return mInputBindKey(&m_inputMap, type, key, gbaKey);
352}
353
354void InputController::updateJoysticks() {
355#ifdef BUILD_SDL
356	QString profile = profileForType(SDL_BINDING_BUTTON);
357	mSDLUpdateJoysticks(&s_sdlEvents, m_config->input());
358	QString newProfile = profileForType(SDL_BINDING_BUTTON);
359	if (profile != newProfile) {
360		loadProfile(SDL_BINDING_BUTTON, newProfile);
361	}
362#endif
363}
364
365int InputController::pollEvents() {
366	int activeButtons = 0;
367#ifdef BUILD_SDL
368	if (m_playerAttached && m_sdlPlayer.joystick) {
369		SDL_Joystick* joystick = m_sdlPlayer.joystick->joystick;
370		SDL_JoystickUpdate();
371		int numButtons = SDL_JoystickNumButtons(joystick);
372		int i;
373		for (i = 0; i < numButtons; ++i) {
374			GBAKey key = static_cast<GBAKey>(mInputMapKey(&m_inputMap, SDL_BINDING_BUTTON, i));
375			if (key == GBA_KEY_NONE) {
376				continue;
377			}
378			if (hasPendingEvent(key)) {
379				continue;
380			}
381			if (SDL_JoystickGetButton(joystick, i)) {
382				activeButtons |= 1 << key;
383			}
384		}
385		int numHats = SDL_JoystickNumHats(joystick);
386		for (i = 0; i < numHats; ++i) {
387			int hat = SDL_JoystickGetHat(joystick, i);
388			activeButtons |= mInputMapHat(&m_inputMap, SDL_BINDING_BUTTON, i, hat);
389		}
390
391		int numAxes = SDL_JoystickNumAxes(joystick);
392		for (i = 0; i < numAxes; ++i) {
393			int value = SDL_JoystickGetAxis(joystick, i);
394
395			enum GBAKey key = static_cast<GBAKey>(mInputMapAxis(&m_inputMap, SDL_BINDING_BUTTON, i, value));
396			if (key != GBA_KEY_NONE) {
397				activeButtons |= 1 << key;
398			}
399		}
400	}
401#endif
402	return activeButtons;
403}
404
405QSet<int> InputController::activeGamepadButtons(int type) {
406	QSet<int> activeButtons;
407#ifdef BUILD_SDL
408	if (m_playerAttached && type == SDL_BINDING_BUTTON && m_sdlPlayer.joystick) {
409		SDL_Joystick* joystick = m_sdlPlayer.joystick->joystick;
410		SDL_JoystickUpdate();
411		int numButtons = SDL_JoystickNumButtons(joystick);
412		int i;
413		for (i = 0; i < numButtons; ++i) {
414			if (SDL_JoystickGetButton(joystick, i)) {
415				activeButtons.insert(i);
416			}
417		}
418	}
419#endif
420	return activeButtons;
421}
422
423void InputController::recalibrateAxes() {
424#ifdef BUILD_SDL
425	if (m_playerAttached && m_sdlPlayer.joystick) {
426		SDL_Joystick* joystick = m_sdlPlayer.joystick->joystick;
427		SDL_JoystickUpdate();
428		int numAxes = SDL_JoystickNumAxes(joystick);
429		if (numAxes < 1) {
430			return;
431		}
432		m_deadzones.resize(numAxes);
433		int i;
434		for (i = 0; i < numAxes; ++i) {
435			m_deadzones[i] = SDL_JoystickGetAxis(joystick, i);
436		}
437	}
438#endif
439}
440
441QSet<QPair<int, GamepadAxisEvent::Direction>> InputController::activeGamepadAxes(int type) {
442	QSet<QPair<int, GamepadAxisEvent::Direction>> activeAxes;
443#ifdef BUILD_SDL
444	if (m_playerAttached && type == SDL_BINDING_BUTTON && m_sdlPlayer.joystick) {
445		SDL_Joystick* joystick = m_sdlPlayer.joystick->joystick;
446		SDL_JoystickUpdate();
447		int numAxes = SDL_JoystickNumAxes(joystick);
448		if (numAxes < 1) {
449			return activeAxes;
450		}
451		m_deadzones.resize(numAxes);
452		int i;
453		for (i = 0; i < numAxes; ++i) {
454			int32_t axis = SDL_JoystickGetAxis(joystick, i);
455			axis -= m_deadzones[i];
456			if (axis >= AXIS_THRESHOLD || axis <= -AXIS_THRESHOLD) {
457				activeAxes.insert(qMakePair(i, axis > 0 ? GamepadAxisEvent::POSITIVE : GamepadAxisEvent::NEGATIVE));
458			}
459		}
460	}
461#endif
462	return activeAxes;
463}
464
465void InputController::bindAxis(uint32_t type, int axis, GamepadAxisEvent::Direction direction, GBAKey key) {
466	const mInputAxis* old = mInputQueryAxis(&m_inputMap, type, axis);
467	mInputAxis description = { GBA_KEY_NONE, GBA_KEY_NONE, -AXIS_THRESHOLD, AXIS_THRESHOLD };
468	if (old) {
469		description = *old;
470	}
471	int deadzone = 0;
472	if (axis > 0 && m_deadzones.size() > axis) {
473		deadzone = m_deadzones[axis];
474	}
475	switch (direction) {
476	case GamepadAxisEvent::NEGATIVE:
477		description.lowDirection = key;
478
479		description.deadLow = deadzone - AXIS_THRESHOLD;
480		break;
481	case GamepadAxisEvent::POSITIVE:
482		description.highDirection = key;
483		description.deadHigh = deadzone + AXIS_THRESHOLD;
484		break;
485	default:
486		return;
487	}
488	mInputBindAxis(&m_inputMap, type, axis, &description);
489}
490
491void InputController::unbindAllAxes(uint32_t type) {
492	mInputUnbindAllAxes(&m_inputMap, type);
493}
494
495QSet<QPair<int, GamepadHatEvent::Direction>> InputController::activeGamepadHats(int type) {
496	QSet<QPair<int, GamepadHatEvent::Direction>> activeHats;
497#ifdef BUILD_SDL
498	if (m_playerAttached && type == SDL_BINDING_BUTTON && m_sdlPlayer.joystick) {
499		SDL_Joystick* joystick = m_sdlPlayer.joystick->joystick;
500		SDL_JoystickUpdate();
501		int numHats = SDL_JoystickNumHats(joystick);
502		if (numHats < 1) {
503			return activeHats;
504		}
505
506		int i;
507		for (i = 0; i < numHats; ++i) {
508			int hat = SDL_JoystickGetHat(joystick, i);
509			if (hat & GamepadHatEvent::UP) {
510				activeHats.insert(qMakePair(i, GamepadHatEvent::UP));
511			}
512			if (hat & GamepadHatEvent::RIGHT) {
513				activeHats.insert(qMakePair(i, GamepadHatEvent::RIGHT));
514			}
515			if (hat & GamepadHatEvent::DOWN) {
516				activeHats.insert(qMakePair(i, GamepadHatEvent::DOWN));
517			}
518			if (hat & GamepadHatEvent::LEFT) {
519				activeHats.insert(qMakePair(i, GamepadHatEvent::LEFT));
520			}
521		}
522	}
523#endif
524	return activeHats;
525}
526
527void InputController::bindHat(uint32_t type, int hat, GamepadHatEvent::Direction direction, GBAKey gbaKey) {
528	mInputHatBindings bindings{ -1, -1, -1, -1 };
529	mInputQueryHat(&m_inputMap, type, hat, &bindings);
530	switch (direction) {
531	case GamepadHatEvent::UP:
532		bindings.up = gbaKey;
533		break;
534	case GamepadHatEvent::RIGHT:
535		bindings.right = gbaKey;
536		break;
537	case GamepadHatEvent::DOWN:
538		bindings.down = gbaKey;
539		break;
540	case GamepadHatEvent::LEFT:
541		bindings.left = gbaKey;
542		break;
543	default:
544		return;
545	}
546	mInputBindHat(&m_inputMap, type, hat, &bindings);
547}
548
549void InputController::testGamepad(int type) {
550	auto activeAxes = activeGamepadAxes(type);
551	auto oldAxes = m_activeAxes;
552	m_activeAxes = activeAxes;
553
554	auto activeButtons = activeGamepadButtons(type);
555	auto oldButtons = m_activeButtons;
556	m_activeButtons = activeButtons;
557
558	auto activeHats = activeGamepadHats(type);
559	auto oldHats = m_activeHats;
560	m_activeHats = activeHats;
561
562	if (!QApplication::focusWidget()) {
563		return;
564	}
565
566	activeAxes.subtract(oldAxes);
567	oldAxes.subtract(m_activeAxes);
568
569	for (auto& axis : m_activeAxes) {
570		bool newlyAboveThreshold = activeAxes.contains(axis);
571		if (newlyAboveThreshold) {
572			GamepadAxisEvent* event = new GamepadAxisEvent(axis.first, axis.second, newlyAboveThreshold, type, this);
573			postPendingEvent(event->gbaKey());
574			sendGamepadEvent(event);
575			if (!event->isAccepted()) {
576				clearPendingEvent(event->gbaKey());
577			}
578		}
579	}
580	for (auto axis : oldAxes) {
581		GamepadAxisEvent* event = new GamepadAxisEvent(axis.first, axis.second, false, type, this);
582		clearPendingEvent(event->gbaKey());
583		sendGamepadEvent(event);
584	}
585
586	if (!QApplication::focusWidget()) {
587		return;
588	}
589
590	activeButtons.subtract(oldButtons);
591	oldButtons.subtract(m_activeButtons);
592
593	for (int button : activeButtons) {
594		GamepadButtonEvent* event = new GamepadButtonEvent(GamepadButtonEvent::Down(), button, type, this);
595		postPendingEvent(event->gbaKey());
596		sendGamepadEvent(event);
597		if (!event->isAccepted()) {
598			clearPendingEvent(event->gbaKey());
599		}
600	}
601	for (int button : oldButtons) {
602		GamepadButtonEvent* event = new GamepadButtonEvent(GamepadButtonEvent::Up(), button, type, this);
603		clearPendingEvent(event->gbaKey());
604		sendGamepadEvent(event);
605	}
606
607	activeHats.subtract(oldHats);
608	oldHats.subtract(m_activeHats);
609
610	for (auto& hat : activeHats) {
611		GamepadHatEvent* event = new GamepadHatEvent(GamepadHatEvent::Down(), hat.first, hat.second, type, this);
612		postPendingEvent(event->gbaKey());
613		sendGamepadEvent(event);
614		if (!event->isAccepted()) {
615			clearPendingEvent(event->gbaKey());
616		}
617	}
618	for (auto& hat : oldHats) {
619		GamepadHatEvent* event = new GamepadHatEvent(GamepadHatEvent::Up(), hat.first, hat.second, type, this);
620		clearPendingEvent(event->gbaKey());
621		sendGamepadEvent(event);
622	}
623}
624
625void InputController::sendGamepadEvent(QEvent* event) {
626	QWidget* focusWidget = nullptr;
627	if (m_focusParent) {
628		focusWidget = m_focusParent->focusWidget();
629		if (!focusWidget) {
630			focusWidget = m_focusParent;
631		}
632	} else {
633		focusWidget = QApplication::focusWidget();
634	}
635	QApplication::sendEvent(focusWidget, event);
636}
637
638void InputController::postPendingEvent(GBAKey key) {
639	m_pendingEvents.insert(key);
640}
641
642void InputController::clearPendingEvent(GBAKey key) {
643	m_pendingEvents.remove(key);
644}
645
646bool InputController::hasPendingEvent(GBAKey key) const {
647	return m_pendingEvents.contains(key);
648}
649
650void InputController::suspendScreensaver() {
651#ifdef BUILD_SDL
652#if SDL_VERSION_ATLEAST(2, 0, 0)
653	mSDLSuspendScreensaver(&s_sdlEvents);
654#endif
655#endif
656}
657
658void InputController::resumeScreensaver() {
659#ifdef BUILD_SDL
660#if SDL_VERSION_ATLEAST(2, 0, 0)
661	mSDLResumeScreensaver(&s_sdlEvents);
662#endif
663#endif
664}
665
666void InputController::setScreensaverSuspendable(bool suspendable) {
667#ifdef BUILD_SDL
668#if SDL_VERSION_ATLEAST(2, 0, 0)
669	mSDLSetScreensaverSuspendable(&s_sdlEvents, suspendable);
670#endif
671#endif
672}
673
674void InputController::stealFocus(QWidget* focus) {
675	m_focusParent = focus;
676}
677
678void InputController::releaseFocus(QWidget* focus) {
679	if (focus == m_focusParent) {
680		m_focusParent = m_topLevel;
681	}
682}
683
684void InputController::loadCamImage(const QString& path) {
685	setCamImage(QImage(path));
686}
687
688void InputController::setCamImage(const QImage& image) {
689	if (image.isNull()) {
690		return;
691	}
692	QMutexLocker locker(&m_image.mutex);
693	m_image.image = image;
694	m_image.resizedImage = QImage();
695	m_image.outOfDate = true;
696}
697
698QList<QPair<QByteArray, QString>> InputController::listCameras() const {
699	QList<QPair<QByteArray, QString>> out;
700#ifdef BUILD_QT_MULTIMEDIA
701	QList<QCameraInfo> cams = QCameraInfo::availableCameras();
702	for (const auto& cam : cams) {
703		out.append(qMakePair(cam.deviceName().toLatin1(), cam.description()));
704	}
705#endif
706	return out;
707}
708
709void InputController::increaseLuminanceLevel() {
710	setLuminanceLevel(m_luxLevel + 1);
711}
712
713void InputController::decreaseLuminanceLevel() {
714	setLuminanceLevel(m_luxLevel - 1);
715}
716
717void InputController::setLuminanceLevel(int level) {
718	int value = 0x16;
719	level = std::max(0, std::min(10, level));
720	if (level > 0) {
721		value += GBA_LUX_LEVELS[level - 1];
722	}
723	setLuminanceValue(value);
724}
725
726void InputController::setLuminanceValue(uint8_t value) {
727	m_luxValue = value;
728	value = std::max<int>(value - 0x16, 0);
729	m_luxLevel = 10;
730	for (int i = 0; i < 10; ++i) {
731		if (value < GBA_LUX_LEVELS[i]) {
732			m_luxLevel = i;
733			break;
734		}
735	}
736	emit luminanceValueChanged(m_luxValue);
737}
738
739void InputController::setupCam() {
740#ifdef BUILD_QT_MULTIMEDIA
741	if (!m_camera) {
742		m_camera = std::make_unique<QCamera>();
743		connect(m_camera.get(), &QCamera::statusChanged, this, &InputController::prepareCamSettings);
744	}
745	m_camera->setCaptureMode(QCamera::CaptureVideo);
746	m_camera->setViewfinder(&m_videoDumper);
747	m_camera->load();
748#endif
749}
750
751#ifdef BUILD_QT_MULTIMEDIA
752void InputController::prepareCamSettings(QCamera::Status status) {
753	if (status != QCamera::LoadedStatus || m_camera->state() == QCamera::ActiveState) {
754		return;
755	}
756#if (QT_VERSION >= QT_VERSION_CHECK(5, 5, 0))
757	QVideoFrame::PixelFormat format(QVideoFrame::Format_RGB32);
758	QCameraViewfinderSettings settings;
759	QSize size(1280, 720);
760	auto cameraRes = m_camera->supportedViewfinderResolutions(settings);
761	for (auto& cameraSize : cameraRes) {
762		if (cameraSize.width() < m_image.w || cameraSize.height() < m_image.h) {
763			continue;
764		}
765		if (cameraSize.width() <= size.width() && cameraSize.height() <= size.height()) {
766			size = cameraSize;
767		}
768	}
769	settings.setResolution(size);
770
771	auto cameraFormats = m_camera->supportedViewfinderPixelFormats(settings);
772	auto goodFormats = m_videoDumper.supportedPixelFormats();
773	bool goodFormatFound = false;
774	for (const auto& goodFormat : goodFormats) {
775		if (cameraFormats.contains(goodFormat)) {
776			settings.setPixelFormat(goodFormat);
777			format = goodFormat;
778			goodFormatFound = true;
779			break;
780		}
781	}
782	if (!goodFormatFound) {
783		LOG(QT, WARN) << "Could not find a valid camera format!";
784		for (const auto& format : cameraFormats) {
785			LOG(QT, WARN) << "Camera supported format: " << QString::number(format);
786		}
787	}
788	m_camera->setViewfinderSettings(settings);
789#endif
790	m_camera->start();
791}
792#endif
793
794void InputController::teardownCam() {
795#ifdef BUILD_QT_MULTIMEDIA
796	if (m_camera) {
797		m_camera->stop();
798	}
799#endif
800}
801
802void InputController::setCamera(const QByteArray& name) {
803#ifdef BUILD_QT_MULTIMEDIA
804	bool needsRestart = false;
805	if (m_camera) {
806		needsRestart = m_camera->state() == QCamera::ActiveState;
807	}
808	m_camera = std::make_unique<QCamera>(name);
809	connect(m_camera.get(), &QCamera::statusChanged, this, &InputController::prepareCamSettings, Qt::QueuedConnection);
810	if (needsRestart) {
811		setupCam();
812	}
813#endif
814}