• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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         mIsExternal(false),
52         mHasMic(false),
53         mDropUntilNextSync(false) {}
54 
~InputDevice()55 InputDevice::~InputDevice() {}
56 
isEnabled()57 bool InputDevice::isEnabled() {
58     if (!hasEventHubDevices()) {
59         return false;
60     }
61     // An input device composed of sub devices can be individually enabled or disabled.
62     // If any of the sub device is enabled then the input device is considered as enabled.
63     bool enabled = false;
64     for_each_subdevice([&enabled](auto& context) { enabled |= context.isDeviceEnabled(); });
65     return enabled;
66 }
67 
setEnabled(bool enabled,nsecs_t when)68 std::list<NotifyArgs> InputDevice::setEnabled(bool enabled, nsecs_t when) {
69     std::list<NotifyArgs> out;
70     if (enabled && mAssociatedDisplayPort && !mAssociatedViewport) {
71         ALOGW("Cannot enable input device %s because it is associated with port %" PRIu8 ", "
72               "but the corresponding viewport is not found",
73               getName().c_str(), *mAssociatedDisplayPort);
74         enabled = false;
75     }
76 
77     if (isEnabled() == enabled) {
78         return out;
79     }
80 
81     // When resetting some devices, the driver needs to be queried to ensure that a proper reset is
82     // performed. The querying must happen when the device is enabled, so we reset after enabling
83     // but before disabling the device. See MultiTouchMotionAccumulator::reset for more information.
84     if (enabled) {
85         for_each_subdevice([](auto& context) { context.enableDevice(); });
86         out += reset(when);
87     } else {
88         out += reset(when);
89         for_each_subdevice([](auto& context) { context.disableDevice(); });
90     }
91     // Must change generation to flag this device as changed
92     bumpGeneration();
93     return out;
94 }
95 
dump(std::string & dump,const std::string & eventHubDevStr)96 void InputDevice::dump(std::string& dump, const std::string& eventHubDevStr) {
97     InputDeviceInfo deviceInfo = getDeviceInfo();
98 
99     dump += StringPrintf(INDENT "Device %d: %s\n", deviceInfo.getId(),
100                          deviceInfo.getDisplayName().c_str());
101     dump += StringPrintf(INDENT "%s", eventHubDevStr.c_str());
102     dump += StringPrintf(INDENT2 "Generation: %d\n", mGeneration);
103     dump += StringPrintf(INDENT2 "IsExternal: %s\n", toString(mIsExternal));
104     dump += StringPrintf(INDENT2 "AssociatedDisplayPort: ");
105     if (mAssociatedDisplayPort) {
106         dump += StringPrintf("%" PRIu8 "\n", *mAssociatedDisplayPort);
107     } else {
108         dump += "<none>\n";
109     }
110     dump += StringPrintf(INDENT2 "AssociatedDisplayUniqueId: ");
111     if (mAssociatedDisplayUniqueId) {
112         dump += StringPrintf("%s\n", mAssociatedDisplayUniqueId->c_str());
113     } else {
114         dump += "<none>\n";
115     }
116     dump += StringPrintf(INDENT2 "HasMic:     %s\n", toString(mHasMic));
117     dump += StringPrintf(INDENT2 "Sources: %s\n",
118                          inputEventSourceToString(deviceInfo.getSources()).c_str());
119     dump += StringPrintf(INDENT2 "KeyboardType: %d\n", deviceInfo.getKeyboardType());
120     dump += StringPrintf(INDENT2 "ControllerNum: %d\n", deviceInfo.getControllerNumber());
121 
122     const std::vector<InputDeviceInfo::MotionRange>& ranges = deviceInfo.getMotionRanges();
123     if (!ranges.empty()) {
124         dump += INDENT2 "Motion Ranges:\n";
125         for (size_t i = 0; i < ranges.size(); i++) {
126             const InputDeviceInfo::MotionRange& range = ranges[i];
127             const char* label = InputEventLookup::getAxisLabel(range.axis);
128             char name[32];
129             if (label) {
130                 strncpy(name, label, sizeof(name));
131                 name[sizeof(name) - 1] = '\0';
132             } else {
133                 snprintf(name, sizeof(name), "%d", range.axis);
134             }
135             dump += StringPrintf(INDENT3
136                                  "%s: source=%s, "
137                                  "min=%0.3f, max=%0.3f, flat=%0.3f, fuzz=%0.3f, resolution=%0.3f\n",
138                                  name, inputEventSourceToString(range.source).c_str(), range.min,
139                                  range.max, range.flat, range.fuzz, range.resolution);
140         }
141     }
142 
143     for_each_mapper([&dump](InputMapper& mapper) { mapper.dump(dump); });
144     if (mController) {
145         mController->dump(dump);
146     }
147 }
148 
addEmptyEventHubDevice(int32_t eventHubId)149 void InputDevice::addEmptyEventHubDevice(int32_t eventHubId) {
150     if (mDevices.find(eventHubId) != mDevices.end()) {
151         return;
152     }
153     std::unique_ptr<InputDeviceContext> contextPtr(new InputDeviceContext(*this, eventHubId));
154     std::vector<std::unique_ptr<InputMapper>> mappers;
155 
156     mDevices.insert({eventHubId, std::make_pair(std::move(contextPtr), std::move(mappers))});
157 }
158 
addEventHubDevice(int32_t eventHubId,const InputReaderConfiguration & readerConfig)159 void InputDevice::addEventHubDevice(int32_t eventHubId,
160                                     const InputReaderConfiguration& readerConfig) {
161     if (mDevices.find(eventHubId) != mDevices.end()) {
162         return;
163     }
164     std::unique_ptr<InputDeviceContext> contextPtr(new InputDeviceContext(*this, eventHubId));
165     std::vector<std::unique_ptr<InputMapper>> mappers = createMappers(*contextPtr, readerConfig);
166 
167     // insert the context into the devices set
168     mDevices.insert({eventHubId, std::make_pair(std::move(contextPtr), std::move(mappers))});
169     // Must change generation to flag this device as changed
170     bumpGeneration();
171 }
172 
removeEventHubDevice(int32_t eventHubId)173 void InputDevice::removeEventHubDevice(int32_t eventHubId) {
174     if (mController != nullptr && mController->getEventHubId() == eventHubId) {
175         // Delete mController, since the corresponding eventhub device is going away
176         mController = nullptr;
177     }
178     mDevices.erase(eventHubId);
179 }
180 
configure(nsecs_t when,const InputReaderConfiguration & readerConfig,ConfigurationChanges changes)181 std::list<NotifyArgs> InputDevice::configure(nsecs_t when,
182                                              const InputReaderConfiguration& readerConfig,
183                                              ConfigurationChanges changes) {
184     std::list<NotifyArgs> out;
185     mSources = 0;
186     mClasses = ftl::Flags<InputDeviceClass>(0);
187     mControllerNumber = 0;
188 
189     for_each_subdevice([this](InputDeviceContext& context) {
190         mClasses |= context.getDeviceClasses();
191         int32_t controllerNumber = context.getDeviceControllerNumber();
192         if (controllerNumber > 0) {
193             if (mControllerNumber && mControllerNumber != controllerNumber) {
194                 ALOGW("InputDevice::configure(): composite device contains multiple unique "
195                       "controller numbers");
196             }
197             mControllerNumber = controllerNumber;
198         }
199     });
200 
201     mIsExternal = mClasses.test(InputDeviceClass::EXTERNAL);
202     mHasMic = mClasses.test(InputDeviceClass::MIC);
203 
204     using Change = InputReaderConfiguration::Change;
205 
206     if (!changes.any() || !isIgnored()) {
207         // Full configuration should happen the first time configure is called
208         // and when the device type is changed. Changing a device type can
209         // affect various other parameters so should result in a
210         // reconfiguration.
211         if (!changes.any() || changes.test(Change::DEVICE_TYPE)) {
212             mConfiguration.clear();
213             for_each_subdevice([this](InputDeviceContext& context) {
214                 std::optional<PropertyMap> configuration =
215                         getEventHub()->getConfiguration(context.getEventHubId());
216                 if (configuration) {
217                     mConfiguration.addAll(&(*configuration));
218                 }
219             });
220 
221             mAssociatedDeviceType =
222                     getValueByKey(readerConfig.deviceTypeAssociations, mIdentifier.location);
223         }
224 
225         if (!changes.any() || changes.test(Change::KEYBOARD_LAYOUTS)) {
226             if (!mClasses.test(InputDeviceClass::VIRTUAL)) {
227                 std::shared_ptr<KeyCharacterMap> keyboardLayout =
228                         mContext->getPolicy()->getKeyboardLayoutOverlay(mIdentifier);
229                 bool shouldBumpGeneration = false;
230                 for_each_subdevice(
231                         [&keyboardLayout, &shouldBumpGeneration](InputDeviceContext& context) {
232                             if (context.setKeyboardLayoutOverlay(keyboardLayout)) {
233                                 shouldBumpGeneration = true;
234                             }
235                         });
236                 if (shouldBumpGeneration) {
237                     bumpGeneration();
238                 }
239             }
240         }
241 
242         if (!changes.any() || changes.test(Change::DEVICE_ALIAS)) {
243             if (!(mClasses.test(InputDeviceClass::VIRTUAL))) {
244                 std::string alias = mContext->getPolicy()->getDeviceAlias(mIdentifier);
245                 if (mAlias != alias) {
246                     mAlias = alias;
247                     bumpGeneration();
248                 }
249             }
250         }
251 
252         if (changes.test(Change::ENABLED_STATE)) {
253             // Do not execute this code on the first configure, because 'setEnabled' would call
254             // InputMapper::reset, and you can't reset a mapper before it has been configured.
255             // The mappers are configured for the first time at the bottom of this function.
256             auto it = readerConfig.disabledDevices.find(mId);
257             bool enabled = it == readerConfig.disabledDevices.end();
258             out += setEnabled(enabled, when);
259         }
260 
261         if (!changes.any() || changes.test(Change::DISPLAY_INFO)) {
262             // In most situations, no port or name will be specified.
263             mAssociatedDisplayPort = std::nullopt;
264             mAssociatedDisplayUniqueId = std::nullopt;
265             mAssociatedViewport = std::nullopt;
266             // Find the display port that corresponds to the current input port.
267             const std::string& inputPort = mIdentifier.location;
268             if (!inputPort.empty()) {
269                 const std::unordered_map<std::string, uint8_t>& ports =
270                         readerConfig.portAssociations;
271                 const auto& displayPort = ports.find(inputPort);
272                 if (displayPort != ports.end()) {
273                     mAssociatedDisplayPort = std::make_optional(displayPort->second);
274                 } else {
275                     const std::unordered_map<std::string, std::string>& displayUniqueIds =
276                             readerConfig.uniqueIdAssociations;
277                     const auto& displayUniqueId = displayUniqueIds.find(inputPort);
278                     if (displayUniqueId != displayUniqueIds.end()) {
279                         mAssociatedDisplayUniqueId = displayUniqueId->second;
280                     }
281                 }
282             }
283 
284             // If the device was explicitly disabled by the user, it would be present in the
285             // "disabledDevices" list. If it is associated with a specific display, and it was not
286             // explicitly disabled, then enable/disable the device based on whether we can find the
287             // corresponding viewport.
288             bool enabled =
289                     (readerConfig.disabledDevices.find(mId) == readerConfig.disabledDevices.end());
290             if (mAssociatedDisplayPort) {
291                 mAssociatedViewport =
292                         readerConfig.getDisplayViewportByPort(*mAssociatedDisplayPort);
293                 if (!mAssociatedViewport) {
294                     ALOGW("Input device %s should be associated with display on port %" PRIu8 ", "
295                           "but the corresponding viewport is not found.",
296                           getName().c_str(), *mAssociatedDisplayPort);
297                     enabled = false;
298                 }
299             } else if (mAssociatedDisplayUniqueId != std::nullopt) {
300                 mAssociatedViewport =
301                         readerConfig.getDisplayViewportByUniqueId(*mAssociatedDisplayUniqueId);
302                 if (!mAssociatedViewport) {
303                     ALOGW("Input device %s should be associated with display %s but the "
304                           "corresponding viewport cannot be found",
305                           getName().c_str(), mAssociatedDisplayUniqueId->c_str());
306                     enabled = false;
307                 }
308             }
309 
310             if (changes.any()) {
311                 // For first-time configuration, only allow device to be disabled after mappers have
312                 // finished configuring. This is because we need to read some of the properties from
313                 // the device's open fd.
314                 out += setEnabled(enabled, when);
315             }
316         }
317 
318         for_each_mapper([this, when, &readerConfig, changes, &out](InputMapper& mapper) {
319             out += mapper.reconfigure(when, readerConfig, changes);
320             mSources |= mapper.getSources();
321         });
322 
323         // If a device is just plugged but it might be disabled, we need to update some info like
324         // axis range of touch from each InputMapper first, then disable it.
325         if (!changes.any()) {
326             out += setEnabled(readerConfig.disabledDevices.find(mId) ==
327                                       readerConfig.disabledDevices.end(),
328                               when);
329         }
330     }
331     return out;
332 }
333 
reset(nsecs_t when)334 std::list<NotifyArgs> InputDevice::reset(nsecs_t when) {
335     std::list<NotifyArgs> out;
336     for_each_mapper([&](InputMapper& mapper) { out += mapper.reset(when); });
337 
338     mContext->updateGlobalMetaState();
339 
340     out.push_back(notifyReset(when));
341     return out;
342 }
343 
process(const RawEvent * rawEvents,size_t count)344 std::list<NotifyArgs> InputDevice::process(const RawEvent* rawEvents, size_t count) {
345     // Process all of the events in order for each mapper.
346     // We cannot simply ask each mapper to process them in bulk because mappers may
347     // have side-effects that must be interleaved.  For example, joystick movement events and
348     // gamepad button presses are handled by different mappers but they should be dispatched
349     // in the order received.
350     std::list<NotifyArgs> out;
351     for (const RawEvent* rawEvent = rawEvents; count != 0; rawEvent++) {
352         if (debugRawEvents()) {
353             const auto [type, code, value] =
354                     InputEventLookup::getLinuxEvdevLabel(rawEvent->type, rawEvent->code,
355                                                          rawEvent->value);
356             ALOGD("Input event: eventHubDevice=%d type=%s code=%s value=%s when=%" PRId64,
357                   rawEvent->deviceId, type.c_str(), code.c_str(), value.c_str(), rawEvent->when);
358         }
359 
360         if (mDropUntilNextSync) {
361             if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
362                 mDropUntilNextSync = false;
363                 ALOGD_IF(debugRawEvents(), "Recovered from input event buffer overrun.");
364             } else {
365                 ALOGD_IF(debugRawEvents(),
366                          "Dropped input event while waiting for next input sync.");
367             }
368         } else if (rawEvent->type == EV_SYN && rawEvent->code == SYN_DROPPED) {
369             ALOGI("Detected input event buffer overrun for device %s.", getName().c_str());
370             mDropUntilNextSync = true;
371             out += reset(rawEvent->when);
372         } else {
373             for_each_mapper_in_subdevice(rawEvent->deviceId, [&](InputMapper& mapper) {
374                 out += mapper.process(rawEvent);
375             });
376         }
377         --count;
378     }
379     return out;
380 }
381 
timeoutExpired(nsecs_t when)382 std::list<NotifyArgs> InputDevice::timeoutExpired(nsecs_t when) {
383     std::list<NotifyArgs> out;
384     for_each_mapper([&](InputMapper& mapper) { out += mapper.timeoutExpired(when); });
385     return out;
386 }
387 
updateExternalStylusState(const StylusState & state)388 std::list<NotifyArgs> InputDevice::updateExternalStylusState(const StylusState& state) {
389     std::list<NotifyArgs> out;
390     for_each_mapper([&](InputMapper& mapper) { out += mapper.updateExternalStylusState(state); });
391     return out;
392 }
393 
getDeviceInfo()394 InputDeviceInfo InputDevice::getDeviceInfo() {
395     InputDeviceInfo outDeviceInfo;
396     outDeviceInfo.initialize(mId, mGeneration, mControllerNumber, mIdentifier, mAlias, mIsExternal,
397                              mHasMic, getAssociatedDisplayId().value_or(ADISPLAY_ID_NONE));
398 
399     for_each_mapper(
400             [&outDeviceInfo](InputMapper& mapper) { mapper.populateDeviceInfo(outDeviceInfo); });
401 
402     if (mController) {
403         mController->populateDeviceInfo(&outDeviceInfo);
404     }
405     return outDeviceInfo;
406 }
407 
getKeyCodeState(uint32_t sourceMask,int32_t keyCode)408 int32_t InputDevice::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
409     return getState(sourceMask, keyCode, &InputMapper::getKeyCodeState);
410 }
411 
getScanCodeState(uint32_t sourceMask,int32_t scanCode)412 int32_t InputDevice::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
413     return getState(sourceMask, scanCode, &InputMapper::getScanCodeState);
414 }
415 
getSwitchState(uint32_t sourceMask,int32_t switchCode)416 int32_t InputDevice::getSwitchState(uint32_t sourceMask, int32_t switchCode) {
417     return getState(sourceMask, switchCode, &InputMapper::getSwitchState);
418 }
419 
getState(uint32_t sourceMask,int32_t code,GetStateFunc getStateFunc)420 int32_t InputDevice::getState(uint32_t sourceMask, int32_t code, GetStateFunc getStateFunc) {
421     int32_t result = AKEY_STATE_UNKNOWN;
422     for (auto& deviceEntry : mDevices) {
423         auto& devicePair = deviceEntry.second;
424         auto& mappers = devicePair.second;
425         for (auto& mapperPtr : mappers) {
426             InputMapper& mapper = *mapperPtr;
427             if (sourcesMatchMask(mapper.getSources(), sourceMask)) {
428                 // If any mapper reports AKEY_STATE_DOWN or AKEY_STATE_VIRTUAL, return that
429                 // value.  Otherwise, return AKEY_STATE_UP as long as one mapper reports it.
430                 int32_t currentResult = (mapper.*getStateFunc)(sourceMask, code);
431                 if (currentResult >= AKEY_STATE_DOWN) {
432                     return currentResult;
433                 } else if (currentResult == AKEY_STATE_UP) {
434                     result = currentResult;
435                 }
436             }
437         }
438     }
439     return result;
440 }
441 
createMappers(InputDeviceContext & contextPtr,const InputReaderConfiguration & readerConfig)442 std::vector<std::unique_ptr<InputMapper>> InputDevice::createMappers(
443         InputDeviceContext& contextPtr, const InputReaderConfiguration& readerConfig) {
444     ftl::Flags<InputDeviceClass> classes = contextPtr.getDeviceClasses();
445     std::vector<std::unique_ptr<InputMapper>> mappers;
446 
447     // Switch-like devices.
448     if (classes.test(InputDeviceClass::SWITCH)) {
449         mappers.push_back(createInputMapper<SwitchInputMapper>(contextPtr, readerConfig));
450     }
451 
452     // Scroll wheel-like devices.
453     if (classes.test(InputDeviceClass::ROTARY_ENCODER)) {
454         mappers.push_back(createInputMapper<RotaryEncoderInputMapper>(contextPtr, readerConfig));
455     }
456 
457     // Vibrator-like devices.
458     if (classes.test(InputDeviceClass::VIBRATOR)) {
459         mappers.push_back(createInputMapper<VibratorInputMapper>(contextPtr, readerConfig));
460     }
461 
462     // Battery-like devices or light-containing devices.
463     // PeripheralController will be created with associated EventHub device.
464     if (classes.test(InputDeviceClass::BATTERY) || classes.test(InputDeviceClass::LIGHT)) {
465         mController = std::make_unique<PeripheralController>(contextPtr);
466     }
467 
468     // Keyboard-like devices.
469     uint32_t keyboardSource = 0;
470     int32_t keyboardType = AINPUT_KEYBOARD_TYPE_NON_ALPHABETIC;
471     if (classes.test(InputDeviceClass::KEYBOARD)) {
472         keyboardSource |= AINPUT_SOURCE_KEYBOARD;
473     }
474     if (classes.test(InputDeviceClass::ALPHAKEY)) {
475         keyboardType = AINPUT_KEYBOARD_TYPE_ALPHABETIC;
476     }
477     if (classes.test(InputDeviceClass::DPAD)) {
478         keyboardSource |= AINPUT_SOURCE_DPAD;
479     }
480     if (classes.test(InputDeviceClass::GAMEPAD)) {
481         keyboardSource |= AINPUT_SOURCE_GAMEPAD;
482     }
483 
484     if (keyboardSource != 0) {
485         mappers.push_back(createInputMapper<KeyboardInputMapper>(contextPtr, readerConfig,
486                                                                  keyboardSource, keyboardType));
487     }
488 
489     // Cursor-like devices.
490     if (classes.test(InputDeviceClass::CURSOR)) {
491         mappers.push_back(createInputMapper<CursorInputMapper>(contextPtr, readerConfig));
492     }
493 
494     // Touchscreens and touchpad devices.
495     static const bool ENABLE_TOUCHPAD_GESTURES_LIBRARY =
496             sysprop::InputProperties::enable_touchpad_gestures_library().value_or(true);
497     // TODO(b/272518665): Fix the new touchpad stack for Sony DualShock 4 (5c4, 9cc) touchpads, or
498     // at least load this setting from the IDC file.
499     const InputDeviceIdentifier identifier = contextPtr.getDeviceIdentifier();
500     const bool isSonyDualShock4Touchpad = identifier.vendor == 0x054c &&
501             (identifier.product == 0x05c4 || identifier.product == 0x09cc);
502     if (ENABLE_TOUCHPAD_GESTURES_LIBRARY && classes.test(InputDeviceClass::TOUCHPAD) &&
503         classes.test(InputDeviceClass::TOUCH_MT) && !isSonyDualShock4Touchpad) {
504         mappers.push_back(createInputMapper<TouchpadInputMapper>(contextPtr, readerConfig));
505     } else if (classes.test(InputDeviceClass::TOUCH_MT)) {
506         mappers.push_back(std::make_unique<MultiTouchInputMapper>(contextPtr, readerConfig));
507     } else if (classes.test(InputDeviceClass::TOUCH)) {
508         mappers.push_back(std::make_unique<SingleTouchInputMapper>(contextPtr, readerConfig));
509     }
510 
511     // Joystick-like devices.
512     if (classes.test(InputDeviceClass::JOYSTICK)) {
513         mappers.push_back(createInputMapper<JoystickInputMapper>(contextPtr, readerConfig));
514     }
515 
516     // Motion sensor enabled devices.
517     if (classes.test(InputDeviceClass::SENSOR)) {
518         mappers.push_back(createInputMapper<SensorInputMapper>(contextPtr, readerConfig));
519     }
520 
521     // External stylus-like devices.
522     if (classes.test(InputDeviceClass::EXTERNAL_STYLUS)) {
523         mappers.push_back(createInputMapper<ExternalStylusInputMapper>(contextPtr, readerConfig));
524     }
525     return mappers;
526 }
527 
markSupportedKeyCodes(uint32_t sourceMask,const std::vector<int32_t> & keyCodes,uint8_t * outFlags)528 bool InputDevice::markSupportedKeyCodes(uint32_t sourceMask, const std::vector<int32_t>& keyCodes,
529                                         uint8_t* outFlags) {
530     bool result = false;
531     for_each_mapper([&result, sourceMask, keyCodes, outFlags](InputMapper& mapper) {
532         if (sourcesMatchMask(mapper.getSources(), sourceMask)) {
533             result |= mapper.markSupportedKeyCodes(sourceMask, keyCodes, outFlags);
534         }
535     });
536     return result;
537 }
538 
getKeyCodeForKeyLocation(int32_t locationKeyCode) const539 int32_t InputDevice::getKeyCodeForKeyLocation(int32_t locationKeyCode) const {
540     std::optional<int32_t> result = first_in_mappers<int32_t>(
541             [locationKeyCode](const InputMapper& mapper) -> std::optional<int32_t> const {
542                 if (sourcesMatchMask(mapper.getSources(), AINPUT_SOURCE_KEYBOARD)) {
543                     return std::make_optional(mapper.getKeyCodeForKeyLocation(locationKeyCode));
544                 }
545                 return std::nullopt;
546             });
547     if (!result) {
548         ALOGE("Failed to get key code for key location: No matching InputMapper with source mask "
549               "KEYBOARD found. The provided input device with id %d has sources %s.",
550               getId(), inputEventSourceToString(getSources()).c_str());
551         return AKEYCODE_UNKNOWN;
552     }
553     return *result;
554 }
555 
vibrate(const VibrationSequence & sequence,ssize_t repeat,int32_t token)556 std::list<NotifyArgs> InputDevice::vibrate(const VibrationSequence& sequence, ssize_t repeat,
557                                            int32_t token) {
558     std::list<NotifyArgs> out;
559     for_each_mapper([&](InputMapper& mapper) { out += mapper.vibrate(sequence, repeat, token); });
560     return out;
561 }
562 
cancelVibrate(int32_t token)563 std::list<NotifyArgs> InputDevice::cancelVibrate(int32_t token) {
564     std::list<NotifyArgs> out;
565     for_each_mapper([&](InputMapper& mapper) { out += mapper.cancelVibrate(token); });
566     return out;
567 }
568 
isVibrating()569 bool InputDevice::isVibrating() {
570     bool vibrating = false;
571     for_each_mapper([&vibrating](InputMapper& mapper) { vibrating |= mapper.isVibrating(); });
572     return vibrating;
573 }
574 
575 /* There's no guarantee the IDs provided by the different mappers are unique, so if we have two
576  * different vibration mappers then we could have duplicate IDs.
577  * Alternatively, if we have a merged device that has multiple evdev nodes with FF_* capabilities,
578  * we would definitely have duplicate IDs.
579  */
getVibratorIds()580 std::vector<int32_t> InputDevice::getVibratorIds() {
581     std::vector<int32_t> vibrators;
582     for_each_mapper([&vibrators](InputMapper& mapper) {
583         std::vector<int32_t> devVibs = mapper.getVibratorIds();
584         vibrators.reserve(vibrators.size() + devVibs.size());
585         vibrators.insert(vibrators.end(), devVibs.begin(), devVibs.end());
586     });
587     return vibrators;
588 }
589 
enableSensor(InputDeviceSensorType sensorType,std::chrono::microseconds samplingPeriod,std::chrono::microseconds maxBatchReportLatency)590 bool InputDevice::enableSensor(InputDeviceSensorType sensorType,
591                                std::chrono::microseconds samplingPeriod,
592                                std::chrono::microseconds maxBatchReportLatency) {
593     bool success = true;
594     for_each_mapper(
595             [&success, sensorType, samplingPeriod, maxBatchReportLatency](InputMapper& mapper) {
596                 success &= mapper.enableSensor(sensorType, samplingPeriod, maxBatchReportLatency);
597             });
598     return success;
599 }
600 
disableSensor(InputDeviceSensorType sensorType)601 void InputDevice::disableSensor(InputDeviceSensorType sensorType) {
602     for_each_mapper([sensorType](InputMapper& mapper) { mapper.disableSensor(sensorType); });
603 }
604 
flushSensor(InputDeviceSensorType sensorType)605 void InputDevice::flushSensor(InputDeviceSensorType sensorType) {
606     for_each_mapper([sensorType](InputMapper& mapper) { mapper.flushSensor(sensorType); });
607 }
608 
cancelTouch(nsecs_t when,nsecs_t readTime)609 std::list<NotifyArgs> InputDevice::cancelTouch(nsecs_t when, nsecs_t readTime) {
610     std::list<NotifyArgs> out;
611     for_each_mapper([&](InputMapper& mapper) { out += mapper.cancelTouch(when, readTime); });
612     return out;
613 }
614 
setLightColor(int32_t lightId,int32_t color)615 bool InputDevice::setLightColor(int32_t lightId, int32_t color) {
616     return mController ? mController->setLightColor(lightId, color) : false;
617 }
618 
setLightPlayerId(int32_t lightId,int32_t playerId)619 bool InputDevice::setLightPlayerId(int32_t lightId, int32_t playerId) {
620     return mController ? mController->setLightPlayerId(lightId, playerId) : false;
621 }
622 
getLightColor(int32_t lightId)623 std::optional<int32_t> InputDevice::getLightColor(int32_t lightId) {
624     return mController ? mController->getLightColor(lightId) : std::nullopt;
625 }
626 
getLightPlayerId(int32_t lightId)627 std::optional<int32_t> InputDevice::getLightPlayerId(int32_t lightId) {
628     return mController ? mController->getLightPlayerId(lightId) : std::nullopt;
629 }
630 
getMetaState()631 int32_t InputDevice::getMetaState() {
632     int32_t result = 0;
633     for_each_mapper([&result](InputMapper& mapper) { result |= mapper.getMetaState(); });
634     return result;
635 }
636 
updateMetaState(int32_t keyCode)637 void InputDevice::updateMetaState(int32_t keyCode) {
638     first_in_mappers<bool>([keyCode](InputMapper& mapper) {
639         if (sourcesMatchMask(mapper.getSources(), AINPUT_SOURCE_KEYBOARD) &&
640             mapper.updateMetaState(keyCode)) {
641             return std::make_optional(true);
642         }
643         return std::optional<bool>();
644     });
645 }
646 
addKeyRemapping(int32_t fromKeyCode,int32_t toKeyCode)647 void InputDevice::addKeyRemapping(int32_t fromKeyCode, int32_t toKeyCode) {
648     for_each_subdevice([fromKeyCode, toKeyCode](auto& context) {
649         context.addKeyRemapping(fromKeyCode, toKeyCode);
650     });
651 }
652 
bumpGeneration()653 void InputDevice::bumpGeneration() {
654     mGeneration = mContext->bumpGeneration();
655 }
656 
notifyReset(nsecs_t when)657 NotifyDeviceResetArgs InputDevice::notifyReset(nsecs_t when) {
658     return NotifyDeviceResetArgs(mContext->getNextId(), when, mId);
659 }
660 
getAssociatedDisplayId()661 std::optional<int32_t> InputDevice::getAssociatedDisplayId() {
662     // Check if we had associated to the specific display.
663     if (mAssociatedViewport) {
664         return mAssociatedViewport->displayId;
665     }
666 
667     // No associated display port, check if some InputMapper is associated.
668     return first_in_mappers<int32_t>(
669             [](InputMapper& mapper) { return mapper.getAssociatedDisplayId(); });
670 }
671 
672 // returns the number of mappers associated with the device
getMapperCount()673 size_t InputDevice::getMapperCount() {
674     size_t count = 0;
675     for (auto& deviceEntry : mDevices) {
676         auto& devicePair = deviceEntry.second;
677         auto& mappers = devicePair.second;
678         count += mappers.size();
679     }
680     return count;
681 }
682 
updateLedState(bool reset)683 void InputDevice::updateLedState(bool reset) {
684     for_each_mapper([reset](InputMapper& mapper) { mapper.updateLedState(reset); });
685 }
686 
getBatteryEventHubId() const687 std::optional<int32_t> InputDevice::getBatteryEventHubId() const {
688     return mController ? std::make_optional(mController->getEventHubId()) : std::nullopt;
689 }
690 
InputDeviceContext(InputDevice & device,int32_t eventHubId)691 InputDeviceContext::InputDeviceContext(InputDevice& device, int32_t eventHubId)
692       : mDevice(device),
693         mContext(device.getContext()),
694         mEventHub(device.getContext()->getEventHub()),
695         mId(eventHubId),
696         mDeviceId(device.getId()) {}
697 
~InputDeviceContext()698 InputDeviceContext::~InputDeviceContext() {}
699 
700 } // namespace android
701