1 /*
2 * Copyright (C) 2019 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #include "Macros.h"
18
19 #include "InputDevice.h"
20
21 #include <algorithm>
22
23 #include <android/sysprop/InputProperties.sysprop.h>
24 #include <ftl/flags.h>
25
26 #include "CursorInputMapper.h"
27 #include "ExternalStylusInputMapper.h"
28 #include "InputReaderContext.h"
29 #include "JoystickInputMapper.h"
30 #include "KeyboardInputMapper.h"
31 #include "MultiTouchInputMapper.h"
32 #include "PeripheralController.h"
33 #include "RotaryEncoderInputMapper.h"
34 #include "SensorInputMapper.h"
35 #include "SingleTouchInputMapper.h"
36 #include "SwitchInputMapper.h"
37 #include "TouchpadInputMapper.h"
38 #include "VibratorInputMapper.h"
39
40 namespace android {
41
InputDevice(InputReaderContext * context,int32_t id,int32_t generation,const InputDeviceIdentifier & identifier)42 InputDevice::InputDevice(InputReaderContext* context, int32_t id, int32_t generation,
43 const InputDeviceIdentifier& identifier)
44 : mContext(context),
45 mId(id),
46 mGeneration(generation),
47 mControllerNumber(0),
48 mIdentifier(identifier),
49 mClasses(0),
50 mSources(0),
51 mIsWaking(false),
52 mIsExternal(false),
53 mHasMic(false),
54 mDropUntilNextSync(false) {}
55
~InputDevice()56 InputDevice::~InputDevice() {}
57
isEnabled()58 bool InputDevice::isEnabled() {
59 if (!hasEventHubDevices()) {
60 return false;
61 }
62 // An input device composed of sub devices can be individually enabled or disabled.
63 // If any of the sub device is enabled then the input device is considered as enabled.
64 bool enabled = false;
65 for_each_subdevice([&enabled](auto& context) { enabled |= context.isDeviceEnabled(); });
66 return enabled;
67 }
68
updateEnableState(nsecs_t when,const InputReaderConfiguration & readerConfig,bool forceEnable)69 std::list<NotifyArgs> InputDevice::updateEnableState(nsecs_t when,
70 const InputReaderConfiguration& readerConfig,
71 bool forceEnable) {
72 bool enable = forceEnable;
73 if (!forceEnable) {
74 // If the device was explicitly disabled by the user, it would be present in the
75 // "disabledDevices" list. This device should be disabled.
76 enable = readerConfig.disabledDevices.find(mId) == readerConfig.disabledDevices.end();
77
78 // If a device is associated with a specific display but there is no
79 // associated DisplayViewport, don't enable the device.
80 if (enable && (mAssociatedDisplayPort || mAssociatedDisplayUniqueIdByPort) &&
81 !mAssociatedViewport) {
82 const std::string desc = mAssociatedDisplayPort
83 ? "port " + std::to_string(*mAssociatedDisplayPort)
84 : "uniqueId " + *mAssociatedDisplayUniqueIdByPort;
85 ALOGW("Cannot enable input device %s because it is associated "
86 "with %s, but the corresponding viewport is not found",
87 getName().c_str(), desc.c_str());
88 enable = false;
89 }
90 }
91
92 std::list<NotifyArgs> out;
93 if (isEnabled() == enable) {
94 return out;
95 }
96
97 // When resetting some devices, the driver needs to be queried to ensure that a proper reset is
98 // performed. The querying must happen when the device is enabled, so we reset after enabling
99 // but before disabling the device. See MultiTouchMotionAccumulator::reset for more information.
100 if (enable) {
101 for_each_subdevice([](auto& context) { context.enableDevice(); });
102 out += reset(when);
103 } else {
104 out += reset(when);
105 for_each_subdevice([](auto& context) { context.disableDevice(); });
106 }
107 // Must change generation to flag this device as changed
108 bumpGeneration();
109 return out;
110 }
111
dump(std::string & dump,const std::string & eventHubDevStr)112 void InputDevice::dump(std::string& dump, const std::string& eventHubDevStr) {
113 InputDeviceInfo deviceInfo = getDeviceInfo();
114
115 dump += StringPrintf(INDENT "Device %d: %s\n", deviceInfo.getId(),
116 deviceInfo.getDisplayName().c_str());
117 dump += StringPrintf(INDENT "%s", eventHubDevStr.c_str());
118 dump += StringPrintf(INDENT2 "Generation: %d\n", mGeneration);
119 dump += StringPrintf(INDENT2 "IsExternal: %s\n", toString(mIsExternal));
120 dump += StringPrintf(INDENT2 "IsWaking: %s\n", toString(mIsWaking));
121 dump += StringPrintf(INDENT2 "AssociatedDisplayPort: ");
122 if (mAssociatedDisplayPort) {
123 dump += StringPrintf("%" PRIu8 "\n", *mAssociatedDisplayPort);
124 } else {
125 dump += "<none>\n";
126 }
127 dump += StringPrintf(INDENT2 "AssociatedDisplayUniqueIdByPort: ");
128 if (mAssociatedDisplayUniqueIdByPort) {
129 dump += StringPrintf("%s\n", mAssociatedDisplayUniqueIdByPort->c_str());
130 } else {
131 dump += "<none>\n";
132 }
133 dump += StringPrintf(INDENT2 "AssociatedDisplayUniqueIdByDescriptor: ");
134 if (mAssociatedDisplayUniqueIdByDescriptor) {
135 dump += StringPrintf("%s\n", mAssociatedDisplayUniqueIdByDescriptor->c_str());
136 } else {
137 dump += "<none>\n";
138 }
139 dump += StringPrintf(INDENT2 "HasMic: %s\n", toString(mHasMic));
140 dump += StringPrintf(INDENT2 "Sources: %s\n",
141 inputEventSourceToString(deviceInfo.getSources()).c_str());
142 dump += StringPrintf(INDENT2 "KeyboardType: %d\n", deviceInfo.getKeyboardType());
143 dump += StringPrintf(INDENT2 "ControllerNum: %d\n", deviceInfo.getControllerNumber());
144
145 const std::vector<InputDeviceInfo::MotionRange>& ranges = deviceInfo.getMotionRanges();
146 if (!ranges.empty()) {
147 dump += INDENT2 "Motion Ranges:\n";
148 for (size_t i = 0; i < ranges.size(); i++) {
149 const InputDeviceInfo::MotionRange& range = ranges[i];
150 const char* label = InputEventLookup::getAxisLabel(range.axis);
151 char name[32];
152 if (label) {
153 strncpy(name, label, sizeof(name));
154 name[sizeof(name) - 1] = '\0';
155 } else {
156 snprintf(name, sizeof(name), "%d", range.axis);
157 }
158 dump += StringPrintf(INDENT3
159 "%s: source=%s, "
160 "min=%0.3f, max=%0.3f, flat=%0.3f, fuzz=%0.3f, resolution=%0.3f\n",
161 name, inputEventSourceToString(range.source).c_str(), range.min,
162 range.max, range.flat, range.fuzz, range.resolution);
163 }
164 }
165
166 for_each_mapper([&dump](InputMapper& mapper) { mapper.dump(dump); });
167 if (mController) {
168 mController->dump(dump);
169 }
170 }
171
addEmptyEventHubDevice(int32_t eventHubId)172 void InputDevice::addEmptyEventHubDevice(int32_t eventHubId) {
173 if (mDevices.find(eventHubId) != mDevices.end()) {
174 return;
175 }
176 std::unique_ptr<InputDeviceContext> contextPtr(new InputDeviceContext(*this, eventHubId));
177 std::vector<std::unique_ptr<InputMapper>> mappers;
178
179 mDevices.insert({eventHubId, std::make_pair(std::move(contextPtr), std::move(mappers))});
180 }
181
addEventHubDevice(nsecs_t when,int32_t eventHubId,const InputReaderConfiguration & readerConfig)182 [[nodiscard]] std::list<NotifyArgs> InputDevice::addEventHubDevice(
183 nsecs_t when, int32_t eventHubId, const InputReaderConfiguration& readerConfig) {
184 if (mDevices.find(eventHubId) != mDevices.end()) {
185 return {};
186 }
187
188 // Add an empty device configure and keep it enabled to allow mapper population with correct
189 // configuration/context,
190 // Note: we need to ensure device is kept enabled till mappers are configured
191 // TODO: b/281852638 refactor tests to remove this flag and reliance on the empty device
192 addEmptyEventHubDevice(eventHubId);
193 std::list<NotifyArgs> out = configureInternal(when, readerConfig, {}, /*forceEnable=*/true);
194
195 DevicePair& devicePair = mDevices[eventHubId];
196 devicePair.second = createMappers(*devicePair.first, readerConfig);
197
198 // Must change generation to flag this device as changed
199 bumpGeneration();
200 return out;
201 }
202
removeEventHubDevice(int32_t eventHubId)203 void InputDevice::removeEventHubDevice(int32_t eventHubId) {
204 if (mController != nullptr && mController->getEventHubId() == eventHubId) {
205 // Delete mController, since the corresponding eventhub device is going away
206 mController = nullptr;
207 }
208 mDevices.erase(eventHubId);
209 }
210
configure(nsecs_t when,const InputReaderConfiguration & readerConfig,ConfigurationChanges changes)211 std::list<NotifyArgs> InputDevice::configure(nsecs_t when,
212 const InputReaderConfiguration& readerConfig,
213 ConfigurationChanges changes) {
214 return configureInternal(when, readerConfig, changes);
215 }
configureInternal(nsecs_t when,const InputReaderConfiguration & readerConfig,ConfigurationChanges changes,bool forceEnable)216 std::list<NotifyArgs> InputDevice::configureInternal(nsecs_t when,
217 const InputReaderConfiguration& readerConfig,
218 ConfigurationChanges changes,
219 bool forceEnable) {
220 std::list<NotifyArgs> out;
221 mSources = 0;
222 mClasses = ftl::Flags<InputDeviceClass>(0);
223 mControllerNumber = 0;
224
225 for_each_subdevice([this](InputDeviceContext& context) {
226 mClasses |= context.getDeviceClasses();
227 int32_t controllerNumber = context.getDeviceControllerNumber();
228 if (controllerNumber > 0) {
229 if (mControllerNumber && mControllerNumber != controllerNumber) {
230 ALOGW("InputDevice::configure(): composite device contains multiple unique "
231 "controller numbers");
232 }
233 mControllerNumber = controllerNumber;
234 }
235 });
236
237 mIsExternal = mClasses.test(InputDeviceClass::EXTERNAL);
238 mHasMic = mClasses.test(InputDeviceClass::MIC);
239
240 // Update keyboard type
241 if (mClasses.test(InputDeviceClass::KEYBOARD)) {
242 mContext->getKeyboardClassifier().notifyKeyboardChanged(mId, mIdentifier, mClasses.get());
243 mKeyboardType = mContext->getKeyboardClassifier().getKeyboardType(mId);
244 }
245
246 using Change = InputReaderConfiguration::Change;
247
248 if (!changes.any() || !isIgnored()) {
249 // Full configuration should happen the first time configure is called
250 // and when the device type is changed. Changing a device type can
251 // affect various other parameters so should result in a
252 // reconfiguration.
253 if (!changes.any() || changes.test(Change::DEVICE_TYPE)) {
254 mConfiguration.clear();
255 for_each_subdevice([this](InputDeviceContext& context) {
256 std::optional<PropertyMap> configuration =
257 getEventHub()->getConfiguration(context.getEventHubId());
258 if (configuration) {
259 mConfiguration.addAll(&(*configuration));
260 }
261 });
262
263 mAssociatedDeviceType =
264 getValueByKey(readerConfig.deviceTypeAssociations, mIdentifier.location);
265 mIsWaking = mConfiguration.getBool("device.wake").value_or(false);
266 mShouldSmoothScroll = mConfiguration.getBool("device.viewBehavior_smoothScroll");
267 }
268
269 if (!changes.any() || changes.test(Change::DEVICE_ALIAS)) {
270 if (!(mClasses.test(InputDeviceClass::VIRTUAL))) {
271 std::string alias = mContext->getPolicy()->getDeviceAlias(mIdentifier);
272 if (mAlias != alias) {
273 mAlias = alias;
274 bumpGeneration();
275 }
276 }
277 }
278
279 if (!changes.any() || changes.test(Change::DISPLAY_INFO)) {
280 const auto oldAssociatedDisplayId = getAssociatedDisplayId();
281
282 // In most situations, no port or name will be specified.
283 mAssociatedDisplayPort = std::nullopt;
284 mAssociatedDisplayUniqueIdByPort = std::nullopt;
285 mAssociatedViewport = std::nullopt;
286 // Find the display port that corresponds to the current input device descriptor
287 const std::string& inputDeviceDescriptor = mIdentifier.descriptor;
288 if (!inputDeviceDescriptor.empty()) {
289 const std::unordered_map<std::string, uint8_t>& ports =
290 readerConfig.inputPortToDisplayPortAssociations;
291 const auto& displayPort = ports.find(inputDeviceDescriptor);
292 if (displayPort != ports.end()) {
293 mAssociatedDisplayPort = std::make_optional(displayPort->second);
294 } else {
295 const std::unordered_map<std::string, std::string>&
296 displayUniqueIdsByDescriptor =
297 readerConfig.inputDeviceDescriptorToDisplayUniqueIdAssociations;
298 const auto& displayUniqueIdByDescriptor =
299 displayUniqueIdsByDescriptor.find(inputDeviceDescriptor);
300 if (displayUniqueIdByDescriptor != displayUniqueIdsByDescriptor.end()) {
301 mAssociatedDisplayUniqueIdByDescriptor =
302 displayUniqueIdByDescriptor->second;
303 }
304 }
305 }
306 // Find the display port that corresponds to the current input port.
307 const std::string& inputPort = mIdentifier.location;
308 if (!inputPort.empty()) {
309 const std::unordered_map<std::string, uint8_t>& ports =
310 readerConfig.inputPortToDisplayPortAssociations;
311 const auto& displayPort = ports.find(inputPort);
312 if (displayPort != ports.end()) {
313 mAssociatedDisplayPort = std::make_optional(displayPort->second);
314 } else {
315 const std::unordered_map<std::string, std::string>& displayUniqueIdsByPort =
316 readerConfig.inputPortToDisplayUniqueIdAssociations;
317 const auto& displayUniqueIdByPort = displayUniqueIdsByPort.find(inputPort);
318 if (displayUniqueIdByPort != displayUniqueIdsByPort.end()) {
319 mAssociatedDisplayUniqueIdByPort = displayUniqueIdByPort->second;
320 }
321 }
322 }
323
324 // If it is associated with a specific display, then find the corresponding viewport
325 // which will be used to enable/disable the device.
326 if (mAssociatedDisplayPort) {
327 mAssociatedViewport =
328 readerConfig.getDisplayViewportByPort(*mAssociatedDisplayPort);
329 if (!mAssociatedViewport) {
330 ALOGW("Input device %s should be associated with display on port %" PRIu8 ", "
331 "but the corresponding viewport is not found.",
332 getName().c_str(), *mAssociatedDisplayPort);
333 }
334 } else if (mAssociatedDisplayUniqueIdByDescriptor != std::nullopt) {
335 mAssociatedViewport = readerConfig.getDisplayViewportByUniqueId(
336 *mAssociatedDisplayUniqueIdByDescriptor);
337 if (!mAssociatedViewport) {
338 ALOGW("Input device %s should be associated with display %s but the "
339 "corresponding viewport cannot be found",
340 getName().c_str(), mAssociatedDisplayUniqueIdByDescriptor->c_str());
341 }
342 } else if (mAssociatedDisplayUniqueIdByPort != std::nullopt) {
343 mAssociatedViewport = readerConfig.getDisplayViewportByUniqueId(
344 *mAssociatedDisplayUniqueIdByPort);
345 if (!mAssociatedViewport) {
346 ALOGW("Input device %s should be associated with display %s but the "
347 "corresponding viewport cannot be found",
348 getName().c_str(), mAssociatedDisplayUniqueIdByPort->c_str());
349 }
350 }
351
352 if (getAssociatedDisplayId() != oldAssociatedDisplayId) {
353 bumpGeneration();
354 }
355 }
356
357 for_each_mapper([this, when, &readerConfig, changes, &out](InputMapper& mapper) {
358 out += mapper.reconfigure(when, readerConfig, changes);
359 mSources |= mapper.getSources();
360 });
361
362 if (!changes.any() || changes.test(Change::ENABLED_STATE) ||
363 changes.test(Change::DISPLAY_INFO)) {
364 // Whether a device is enabled can depend on the display association,
365 // so update the enabled state when there is a change in display info.
366 out += updateEnableState(when, readerConfig, forceEnable);
367 }
368 }
369 return out;
370 }
371
reset(nsecs_t when)372 std::list<NotifyArgs> InputDevice::reset(nsecs_t when) {
373 std::list<NotifyArgs> out;
374 for_each_mapper([&](InputMapper& mapper) { out += mapper.reset(when); });
375
376 mContext->updateGlobalMetaState();
377
378 out.push_back(notifyReset(when));
379 return out;
380 }
381
process(const RawEvent * rawEvents,size_t count)382 std::list<NotifyArgs> InputDevice::process(const RawEvent* rawEvents, size_t count) {
383 // Process all of the events in order for each mapper.
384 // We cannot simply ask each mapper to process them in bulk because mappers may
385 // have side-effects that must be interleaved. For example, joystick movement events and
386 // gamepad button presses are handled by different mappers but they should be dispatched
387 // in the order received.
388 std::list<NotifyArgs> out;
389 for (const RawEvent* rawEvent = rawEvents; count != 0; rawEvent++) {
390 if (debugRawEvents()) {
391 const auto [type, code, value] =
392 InputEventLookup::getLinuxEvdevLabel(rawEvent->type, rawEvent->code,
393 rawEvent->value);
394 ALOGD("Input event: eventHubDevice=%d type=%s code=%s value=%s when=%" PRId64,
395 rawEvent->deviceId, type.c_str(), code.c_str(), value.c_str(), rawEvent->when);
396 }
397
398 if (mDropUntilNextSync) {
399 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
400 out += reset(rawEvent->when);
401 mDropUntilNextSync = false;
402 ALOGD_IF(debugRawEvents(), "Recovered from input event buffer overrun.");
403 } else {
404 ALOGD_IF(debugRawEvents(),
405 "Dropped input event while waiting for next input sync.");
406 }
407 } else if (rawEvent->type == EV_SYN && rawEvent->code == SYN_DROPPED) {
408 ALOGI("Detected input event buffer overrun for device %s.", getName().c_str());
409 mDropUntilNextSync = true;
410 } else {
411 for_each_mapper_in_subdevice(rawEvent->deviceId, [&](InputMapper& mapper) {
412 out += mapper.process(*rawEvent);
413 });
414 }
415 --count;
416 }
417 postProcess(out);
418 return out;
419 }
420
postProcess(std::list<NotifyArgs> & args) const421 void InputDevice::postProcess(std::list<NotifyArgs>& args) const {
422 if (mIsWaking) {
423 // Update policy flags to request wake for the `NotifyArgs` that come from waking devices.
424 for (auto& arg : args) {
425 if (const auto notifyMotionArgs = std::get_if<NotifyMotionArgs>(&arg)) {
426 notifyMotionArgs->policyFlags |= POLICY_FLAG_WAKE;
427 } else if (const auto notifySwitchArgs = std::get_if<NotifySwitchArgs>(&arg)) {
428 notifySwitchArgs->policyFlags |= POLICY_FLAG_WAKE;
429 } else if (const auto notifyKeyArgs = std::get_if<NotifyKeyArgs>(&arg)) {
430 notifyKeyArgs->policyFlags |= POLICY_FLAG_WAKE;
431 }
432 }
433 }
434 }
435
timeoutExpired(nsecs_t when)436 std::list<NotifyArgs> InputDevice::timeoutExpired(nsecs_t when) {
437 std::list<NotifyArgs> out;
438 for_each_mapper([&](InputMapper& mapper) { out += mapper.timeoutExpired(when); });
439 return out;
440 }
441
updateExternalStylusState(const StylusState & state)442 std::list<NotifyArgs> InputDevice::updateExternalStylusState(const StylusState& state) {
443 std::list<NotifyArgs> out;
444 for_each_mapper([&](InputMapper& mapper) { out += mapper.updateExternalStylusState(state); });
445 return out;
446 }
447
getDeviceInfo()448 InputDeviceInfo InputDevice::getDeviceInfo() {
449 InputDeviceInfo outDeviceInfo;
450 outDeviceInfo.initialize(mId, mGeneration, mControllerNumber, mIdentifier, mAlias, mIsExternal,
451 mHasMic,
452 getAssociatedDisplayId().value_or(ui::LogicalDisplayId::INVALID),
453 {mShouldSmoothScroll}, isEnabled());
454 outDeviceInfo.setKeyboardType(static_cast<int32_t>(mKeyboardType));
455
456 for_each_mapper(
457 [&outDeviceInfo](InputMapper& mapper) { mapper.populateDeviceInfo(outDeviceInfo); });
458
459 if (mController) {
460 mController->populateDeviceInfo(&outDeviceInfo);
461 }
462 return outDeviceInfo;
463 }
464
getKeyCodeState(uint32_t sourceMask,int32_t keyCode)465 int32_t InputDevice::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
466 return getState(sourceMask, keyCode, &InputMapper::getKeyCodeState);
467 }
468
getScanCodeState(uint32_t sourceMask,int32_t scanCode)469 int32_t InputDevice::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
470 return getState(sourceMask, scanCode, &InputMapper::getScanCodeState);
471 }
472
getSwitchState(uint32_t sourceMask,int32_t switchCode)473 int32_t InputDevice::getSwitchState(uint32_t sourceMask, int32_t switchCode) {
474 return getState(sourceMask, switchCode, &InputMapper::getSwitchState);
475 }
476
getState(uint32_t sourceMask,int32_t code,GetStateFunc getStateFunc)477 int32_t InputDevice::getState(uint32_t sourceMask, int32_t code, GetStateFunc getStateFunc) {
478 int32_t result = AKEY_STATE_UNKNOWN;
479 for (auto& deviceEntry : mDevices) {
480 auto& devicePair = deviceEntry.second;
481 auto& mappers = devicePair.second;
482 for (auto& mapperPtr : mappers) {
483 InputMapper& mapper = *mapperPtr;
484 if (sourcesMatchMask(mapper.getSources(), sourceMask)) {
485 // If any mapper reports AKEY_STATE_DOWN or AKEY_STATE_VIRTUAL, return that
486 // value. Otherwise, return AKEY_STATE_UP as long as one mapper reports it.
487 int32_t currentResult = (mapper.*getStateFunc)(sourceMask, code);
488 if (currentResult >= AKEY_STATE_DOWN) {
489 return currentResult;
490 } else if (currentResult == AKEY_STATE_UP) {
491 result = currentResult;
492 }
493 }
494 }
495 }
496 return result;
497 }
498
createMappers(InputDeviceContext & contextPtr,const InputReaderConfiguration & readerConfig)499 std::vector<std::unique_ptr<InputMapper>> InputDevice::createMappers(
500 InputDeviceContext& contextPtr, const InputReaderConfiguration& readerConfig) {
501 ftl::Flags<InputDeviceClass> classes = contextPtr.getDeviceClasses();
502 std::vector<std::unique_ptr<InputMapper>> mappers;
503
504 // Switch-like devices.
505 if (classes.test(InputDeviceClass::SWITCH)) {
506 mappers.push_back(createInputMapper<SwitchInputMapper>(contextPtr, readerConfig));
507 }
508
509 // Scroll wheel-like devices.
510 if (classes.test(InputDeviceClass::ROTARY_ENCODER)) {
511 mappers.push_back(createInputMapper<RotaryEncoderInputMapper>(contextPtr, readerConfig));
512 }
513
514 // Vibrator-like devices.
515 if (classes.test(InputDeviceClass::VIBRATOR)) {
516 mappers.push_back(createInputMapper<VibratorInputMapper>(contextPtr, readerConfig));
517 }
518
519 // Battery-like devices or light-containing devices.
520 // PeripheralController will be created with associated EventHub device.
521 if (classes.test(InputDeviceClass::BATTERY) || classes.test(InputDeviceClass::LIGHT)) {
522 mController = std::make_unique<PeripheralController>(contextPtr);
523 }
524
525 // Keyboard-like devices.
526 uint32_t keyboardSource = 0;
527 if (classes.test(InputDeviceClass::KEYBOARD)) {
528 keyboardSource |= AINPUT_SOURCE_KEYBOARD;
529 }
530 if (classes.test(InputDeviceClass::DPAD)) {
531 keyboardSource |= AINPUT_SOURCE_DPAD;
532 }
533 if (classes.test(InputDeviceClass::GAMEPAD)) {
534 keyboardSource |= AINPUT_SOURCE_GAMEPAD;
535 }
536
537 if (keyboardSource != 0) {
538 mappers.push_back(
539 createInputMapper<KeyboardInputMapper>(contextPtr, readerConfig, keyboardSource));
540 }
541
542 // Cursor-like devices.
543 if (classes.test(InputDeviceClass::CURSOR)) {
544 mappers.push_back(createInputMapper<CursorInputMapper>(contextPtr, readerConfig));
545 }
546
547 // Touchscreens and touchpad devices.
548 if (classes.test(InputDeviceClass::TOUCHPAD) && classes.test(InputDeviceClass::TOUCH_MT)) {
549 mappers.push_back(createInputMapper<TouchpadInputMapper>(contextPtr, readerConfig));
550 } else if (classes.test(InputDeviceClass::TOUCH_MT)) {
551 mappers.push_back(createInputMapper<MultiTouchInputMapper>(contextPtr, readerConfig));
552 } else if (classes.test(InputDeviceClass::TOUCH)) {
553 mappers.push_back(createInputMapper<SingleTouchInputMapper>(contextPtr, readerConfig));
554 }
555
556 // Joystick-like devices.
557 if (classes.test(InputDeviceClass::JOYSTICK)) {
558 mappers.push_back(createInputMapper<JoystickInputMapper>(contextPtr, readerConfig));
559 }
560
561 // Motion sensor enabled devices.
562 if (classes.test(InputDeviceClass::SENSOR)) {
563 mappers.push_back(createInputMapper<SensorInputMapper>(contextPtr, readerConfig));
564 }
565
566 // External stylus-like devices.
567 if (classes.test(InputDeviceClass::EXTERNAL_STYLUS)) {
568 mappers.push_back(createInputMapper<ExternalStylusInputMapper>(contextPtr, readerConfig));
569 }
570 return mappers;
571 }
572
markSupportedKeyCodes(uint32_t sourceMask,const std::vector<int32_t> & keyCodes,uint8_t * outFlags)573 bool InputDevice::markSupportedKeyCodes(uint32_t sourceMask, const std::vector<int32_t>& keyCodes,
574 uint8_t* outFlags) {
575 bool result = false;
576 for_each_mapper([&result, sourceMask, keyCodes, outFlags](InputMapper& mapper) {
577 if (sourcesMatchMask(mapper.getSources(), sourceMask)) {
578 result |= mapper.markSupportedKeyCodes(sourceMask, keyCodes, outFlags);
579 }
580 });
581 return result;
582 }
583
getKeyCodeForKeyLocation(int32_t locationKeyCode) const584 int32_t InputDevice::getKeyCodeForKeyLocation(int32_t locationKeyCode) const {
585 std::optional<int32_t> result = first_in_mappers<int32_t>(
586 [locationKeyCode](const InputMapper& mapper) -> std::optional<int32_t> const {
587 if (sourcesMatchMask(mapper.getSources(), AINPUT_SOURCE_KEYBOARD)) {
588 return std::make_optional(mapper.getKeyCodeForKeyLocation(locationKeyCode));
589 }
590 return std::nullopt;
591 });
592 if (!result) {
593 ALOGE("Failed to get key code for key location: No matching InputMapper with source mask "
594 "KEYBOARD found. The provided input device with id %d has sources %s.",
595 getId(), inputEventSourceToString(getSources()).c_str());
596 return AKEYCODE_UNKNOWN;
597 }
598 return *result;
599 }
600
vibrate(const VibrationSequence & sequence,ssize_t repeat,int32_t token)601 std::list<NotifyArgs> InputDevice::vibrate(const VibrationSequence& sequence, ssize_t repeat,
602 int32_t token) {
603 std::list<NotifyArgs> out;
604 for_each_mapper([&](InputMapper& mapper) { out += mapper.vibrate(sequence, repeat, token); });
605 return out;
606 }
607
cancelVibrate(int32_t token)608 std::list<NotifyArgs> InputDevice::cancelVibrate(int32_t token) {
609 std::list<NotifyArgs> out;
610 for_each_mapper([&](InputMapper& mapper) { out += mapper.cancelVibrate(token); });
611 return out;
612 }
613
isVibrating()614 bool InputDevice::isVibrating() {
615 bool vibrating = false;
616 for_each_mapper([&vibrating](InputMapper& mapper) { vibrating |= mapper.isVibrating(); });
617 return vibrating;
618 }
619
620 /* There's no guarantee the IDs provided by the different mappers are unique, so if we have two
621 * different vibration mappers then we could have duplicate IDs.
622 * Alternatively, if we have a merged device that has multiple evdev nodes with FF_* capabilities,
623 * we would definitely have duplicate IDs.
624 */
getVibratorIds()625 std::vector<int32_t> InputDevice::getVibratorIds() {
626 std::vector<int32_t> vibrators;
627 for_each_mapper([&vibrators](InputMapper& mapper) {
628 std::vector<int32_t> devVibs = mapper.getVibratorIds();
629 vibrators.reserve(vibrators.size() + devVibs.size());
630 vibrators.insert(vibrators.end(), devVibs.begin(), devVibs.end());
631 });
632 return vibrators;
633 }
634
enableSensor(InputDeviceSensorType sensorType,std::chrono::microseconds samplingPeriod,std::chrono::microseconds maxBatchReportLatency)635 bool InputDevice::enableSensor(InputDeviceSensorType sensorType,
636 std::chrono::microseconds samplingPeriod,
637 std::chrono::microseconds maxBatchReportLatency) {
638 bool success = true;
639 for_each_mapper(
640 [&success, sensorType, samplingPeriod, maxBatchReportLatency](InputMapper& mapper) {
641 success &= mapper.enableSensor(sensorType, samplingPeriod, maxBatchReportLatency);
642 });
643 return success;
644 }
645
disableSensor(InputDeviceSensorType sensorType)646 void InputDevice::disableSensor(InputDeviceSensorType sensorType) {
647 for_each_mapper([sensorType](InputMapper& mapper) { mapper.disableSensor(sensorType); });
648 }
649
flushSensor(InputDeviceSensorType sensorType)650 void InputDevice::flushSensor(InputDeviceSensorType sensorType) {
651 for_each_mapper([sensorType](InputMapper& mapper) { mapper.flushSensor(sensorType); });
652 }
653
cancelTouch(nsecs_t when,nsecs_t readTime)654 std::list<NotifyArgs> InputDevice::cancelTouch(nsecs_t when, nsecs_t readTime) {
655 std::list<NotifyArgs> out;
656 for_each_mapper([&](InputMapper& mapper) { out += mapper.cancelTouch(when, readTime); });
657 return out;
658 }
659
setLightColor(int32_t lightId,int32_t color)660 bool InputDevice::setLightColor(int32_t lightId, int32_t color) {
661 return mController ? mController->setLightColor(lightId, color) : false;
662 }
663
setLightPlayerId(int32_t lightId,int32_t playerId)664 bool InputDevice::setLightPlayerId(int32_t lightId, int32_t playerId) {
665 return mController ? mController->setLightPlayerId(lightId, playerId) : false;
666 }
667
getLightColor(int32_t lightId)668 std::optional<int32_t> InputDevice::getLightColor(int32_t lightId) {
669 return mController ? mController->getLightColor(lightId) : std::nullopt;
670 }
671
getLightPlayerId(int32_t lightId)672 std::optional<int32_t> InputDevice::getLightPlayerId(int32_t lightId) {
673 return mController ? mController->getLightPlayerId(lightId) : std::nullopt;
674 }
675
getMetaState()676 int32_t InputDevice::getMetaState() {
677 int32_t result = 0;
678 for_each_mapper([&result](InputMapper& mapper) { result |= mapper.getMetaState(); });
679 return result;
680 }
681
updateMetaState(int32_t keyCode)682 void InputDevice::updateMetaState(int32_t keyCode) {
683 first_in_mappers<bool>([keyCode](InputMapper& mapper) {
684 if (sourcesMatchMask(mapper.getSources(), AINPUT_SOURCE_KEYBOARD) &&
685 mapper.updateMetaState(keyCode)) {
686 return std::make_optional(true);
687 }
688 return std::optional<bool>();
689 });
690 }
691
addKeyRemapping(int32_t fromKeyCode,int32_t toKeyCode)692 void InputDevice::addKeyRemapping(int32_t fromKeyCode, int32_t toKeyCode) {
693 for_each_subdevice([fromKeyCode, toKeyCode](auto& context) {
694 context.addKeyRemapping(fromKeyCode, toKeyCode);
695 });
696 }
697
bumpGeneration()698 void InputDevice::bumpGeneration() {
699 mGeneration = mContext->bumpGeneration();
700 }
701
notifyReset(nsecs_t when)702 NotifyDeviceResetArgs InputDevice::notifyReset(nsecs_t when) {
703 return NotifyDeviceResetArgs(mContext->getNextId(), when, mId);
704 }
705
getAssociatedDisplayId()706 std::optional<ui::LogicalDisplayId> InputDevice::getAssociatedDisplayId() {
707 // Check if we had associated to the specific display.
708 if (mAssociatedViewport) {
709 return mAssociatedViewport->displayId;
710 }
711
712 // No associated display port, check if some InputMapper is associated.
713 return first_in_mappers<ui::LogicalDisplayId>(
714 [](InputMapper& mapper) { return mapper.getAssociatedDisplayId(); });
715 }
716
717 // returns the number of mappers associated with the device
getMapperCount()718 size_t InputDevice::getMapperCount() {
719 size_t count = 0;
720 for (auto& deviceEntry : mDevices) {
721 auto& devicePair = deviceEntry.second;
722 auto& mappers = devicePair.second;
723 count += mappers.size();
724 }
725 return count;
726 }
727
updateLedState(bool reset)728 void InputDevice::updateLedState(bool reset) {
729 for_each_mapper([reset](InputMapper& mapper) { mapper.updateLedState(reset); });
730 }
731
getBatteryEventHubId() const732 std::optional<int32_t> InputDevice::getBatteryEventHubId() const {
733 return mController ? std::make_optional(mController->getEventHubId()) : std::nullopt;
734 }
735
setKeyboardType(KeyboardType keyboardType)736 void InputDevice::setKeyboardType(KeyboardType keyboardType) {
737 if (mKeyboardType != keyboardType) {
738 mKeyboardType = keyboardType;
739 bumpGeneration();
740 }
741 }
742
InputDeviceContext(InputDevice & device,int32_t eventHubId)743 InputDeviceContext::InputDeviceContext(InputDevice& device, int32_t eventHubId)
744 : mDevice(device),
745 mContext(device.getContext()),
746 mEventHub(device.getContext()->getEventHub()),
747 mId(eventHubId),
748 mDeviceId(device.getId()) {}
749
~InputDeviceContext()750 InputDeviceContext::~InputDeviceContext() {}
751
752 } // namespace android
753