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