xref: /aosp_15_r20/frameworks/native/services/inputflinger/reader/InputDevice.cpp (revision 38e8c45f13ce32b0dcecb25141ffecaf386fa17f)
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         if (!changes.any() || changes.test(InputReaderConfiguration::Change::KEY_REMAPPING)) {
370             const bool isFullKeyboard =
371                     (mSources & AINPUT_SOURCE_KEYBOARD) == AINPUT_SOURCE_KEYBOARD &&
372                     mKeyboardType == KeyboardType::ALPHABETIC;
373             if (isFullKeyboard) {
374                 for_each_subdevice([&readerConfig](auto& context) {
375                     context.setKeyRemapping(readerConfig.keyRemapping);
376                 });
377                 bumpGeneration();
378             }
379         }
380     }
381     return out;
382 }
383 
reset(nsecs_t when)384 std::list<NotifyArgs> InputDevice::reset(nsecs_t when) {
385     std::list<NotifyArgs> out;
386     for_each_mapper([&](InputMapper& mapper) { out += mapper.reset(when); });
387 
388     mContext->updateGlobalMetaState();
389 
390     out.push_back(notifyReset(when));
391     return out;
392 }
393 
process(const RawEvent * rawEvents,size_t count)394 std::list<NotifyArgs> InputDevice::process(const RawEvent* rawEvents, size_t count) {
395     // Process all of the events in order for each mapper.
396     // We cannot simply ask each mapper to process them in bulk because mappers may
397     // have side-effects that must be interleaved.  For example, joystick movement events and
398     // gamepad button presses are handled by different mappers but they should be dispatched
399     // in the order received.
400     std::list<NotifyArgs> out;
401     for (const RawEvent* rawEvent = rawEvents; count != 0; rawEvent++) {
402         if (debugRawEvents()) {
403             const auto [type, code, value] =
404                     InputEventLookup::getLinuxEvdevLabel(rawEvent->type, rawEvent->code,
405                                                          rawEvent->value);
406             ALOGD("Input event: eventHubDevice=%d type=%s code=%s value=%s when=%" PRId64,
407                   rawEvent->deviceId, type.c_str(), code.c_str(), value.c_str(), rawEvent->when);
408         }
409 
410         if (mDropUntilNextSync) {
411             if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
412                 out += reset(rawEvent->when);
413                 mDropUntilNextSync = false;
414                 ALOGD_IF(debugRawEvents(), "Recovered from input event buffer overrun.");
415             } else {
416                 ALOGD_IF(debugRawEvents(),
417                          "Dropped input event while waiting for next input sync.");
418             }
419         } else if (rawEvent->type == EV_SYN && rawEvent->code == SYN_DROPPED) {
420             ALOGI("Detected input event buffer overrun for device %s.", getName().c_str());
421             mDropUntilNextSync = true;
422         } else {
423             for_each_mapper_in_subdevice(rawEvent->deviceId, [&](InputMapper& mapper) {
424                 out += mapper.process(*rawEvent);
425             });
426         }
427         --count;
428     }
429     postProcess(out);
430     return out;
431 }
432 
postProcess(std::list<NotifyArgs> & args) const433 void InputDevice::postProcess(std::list<NotifyArgs>& args) const {
434     if (mIsWaking) {
435         // Update policy flags to request wake for the `NotifyArgs` that come from waking devices.
436         for (auto& arg : args) {
437             if (const auto notifyMotionArgs = std::get_if<NotifyMotionArgs>(&arg)) {
438                 notifyMotionArgs->policyFlags |= POLICY_FLAG_WAKE;
439             } else if (const auto notifySwitchArgs = std::get_if<NotifySwitchArgs>(&arg)) {
440                 notifySwitchArgs->policyFlags |= POLICY_FLAG_WAKE;
441             } else if (const auto notifyKeyArgs = std::get_if<NotifyKeyArgs>(&arg)) {
442                 notifyKeyArgs->policyFlags |= POLICY_FLAG_WAKE;
443             }
444         }
445     }
446 }
447 
timeoutExpired(nsecs_t when)448 std::list<NotifyArgs> InputDevice::timeoutExpired(nsecs_t when) {
449     std::list<NotifyArgs> out;
450     for_each_mapper([&](InputMapper& mapper) { out += mapper.timeoutExpired(when); });
451     return out;
452 }
453 
updateExternalStylusState(const StylusState & state)454 std::list<NotifyArgs> InputDevice::updateExternalStylusState(const StylusState& state) {
455     std::list<NotifyArgs> out;
456     for_each_mapper([&](InputMapper& mapper) { out += mapper.updateExternalStylusState(state); });
457     return out;
458 }
459 
getDeviceInfo()460 InputDeviceInfo InputDevice::getDeviceInfo() {
461     InputDeviceInfo outDeviceInfo;
462     outDeviceInfo.initialize(mId, mGeneration, mControllerNumber, mIdentifier, mAlias, mIsExternal,
463                              mHasMic,
464                              getAssociatedDisplayId().value_or(ui::LogicalDisplayId::INVALID),
465                              {mShouldSmoothScroll}, isEnabled());
466     outDeviceInfo.setKeyboardType(static_cast<int32_t>(mKeyboardType));
467 
468     for_each_mapper(
469             [&outDeviceInfo](InputMapper& mapper) { mapper.populateDeviceInfo(outDeviceInfo); });
470 
471     if (mController) {
472         mController->populateDeviceInfo(&outDeviceInfo);
473     }
474     return outDeviceInfo;
475 }
476 
getKeyCodeState(uint32_t sourceMask,int32_t keyCode)477 int32_t InputDevice::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
478     return getState(sourceMask, keyCode, &InputMapper::getKeyCodeState);
479 }
480 
getScanCodeState(uint32_t sourceMask,int32_t scanCode)481 int32_t InputDevice::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
482     return getState(sourceMask, scanCode, &InputMapper::getScanCodeState);
483 }
484 
getSwitchState(uint32_t sourceMask,int32_t switchCode)485 int32_t InputDevice::getSwitchState(uint32_t sourceMask, int32_t switchCode) {
486     return getState(sourceMask, switchCode, &InputMapper::getSwitchState);
487 }
488 
getState(uint32_t sourceMask,int32_t code,GetStateFunc getStateFunc)489 int32_t InputDevice::getState(uint32_t sourceMask, int32_t code, GetStateFunc getStateFunc) {
490     int32_t result = AKEY_STATE_UNKNOWN;
491     for (auto& deviceEntry : mDevices) {
492         auto& devicePair = deviceEntry.second;
493         auto& mappers = devicePair.second;
494         for (auto& mapperPtr : mappers) {
495             InputMapper& mapper = *mapperPtr;
496             if (sourcesMatchMask(mapper.getSources(), sourceMask)) {
497                 // If any mapper reports AKEY_STATE_DOWN or AKEY_STATE_VIRTUAL, return that
498                 // value.  Otherwise, return AKEY_STATE_UP as long as one mapper reports it.
499                 int32_t currentResult = (mapper.*getStateFunc)(sourceMask, code);
500                 if (currentResult >= AKEY_STATE_DOWN) {
501                     return currentResult;
502                 } else if (currentResult == AKEY_STATE_UP) {
503                     result = currentResult;
504                 }
505             }
506         }
507     }
508     return result;
509 }
510 
createMappers(InputDeviceContext & contextPtr,const InputReaderConfiguration & readerConfig)511 std::vector<std::unique_ptr<InputMapper>> InputDevice::createMappers(
512         InputDeviceContext& contextPtr, const InputReaderConfiguration& readerConfig) {
513     ftl::Flags<InputDeviceClass> classes = contextPtr.getDeviceClasses();
514     std::vector<std::unique_ptr<InputMapper>> mappers;
515 
516     // Switch-like devices.
517     if (classes.test(InputDeviceClass::SWITCH)) {
518         mappers.push_back(createInputMapper<SwitchInputMapper>(contextPtr, readerConfig));
519     }
520 
521     // Scroll wheel-like devices.
522     if (classes.test(InputDeviceClass::ROTARY_ENCODER)) {
523         mappers.push_back(createInputMapper<RotaryEncoderInputMapper>(contextPtr, readerConfig));
524     }
525 
526     // Vibrator-like devices.
527     if (classes.test(InputDeviceClass::VIBRATOR)) {
528         mappers.push_back(createInputMapper<VibratorInputMapper>(contextPtr, readerConfig));
529     }
530 
531     // Battery-like devices or light-containing devices.
532     // PeripheralController will be created with associated EventHub device.
533     if (classes.test(InputDeviceClass::BATTERY) || classes.test(InputDeviceClass::LIGHT)) {
534         mController = std::make_unique<PeripheralController>(contextPtr);
535     }
536 
537     // Keyboard-like devices.
538     uint32_t keyboardSource = 0;
539     if (classes.test(InputDeviceClass::KEYBOARD)) {
540         keyboardSource |= AINPUT_SOURCE_KEYBOARD;
541     }
542     if (classes.test(InputDeviceClass::DPAD)) {
543         keyboardSource |= AINPUT_SOURCE_DPAD;
544     }
545     if (classes.test(InputDeviceClass::GAMEPAD)) {
546         keyboardSource |= AINPUT_SOURCE_GAMEPAD;
547     }
548 
549     if (keyboardSource != 0) {
550         mappers.push_back(
551                 createInputMapper<KeyboardInputMapper>(contextPtr, readerConfig, keyboardSource));
552     }
553 
554     // Cursor-like devices.
555     if (classes.test(InputDeviceClass::CURSOR)) {
556         mappers.push_back(createInputMapper<CursorInputMapper>(contextPtr, readerConfig));
557     }
558 
559     // Touchscreens and touchpad devices.
560     if (classes.test(InputDeviceClass::TOUCHPAD) && classes.test(InputDeviceClass::TOUCH_MT)) {
561         mappers.push_back(createInputMapper<TouchpadInputMapper>(contextPtr, readerConfig));
562     } else if (classes.test(InputDeviceClass::TOUCH_MT)) {
563         mappers.push_back(createInputMapper<MultiTouchInputMapper>(contextPtr, readerConfig));
564     } else if (classes.test(InputDeviceClass::TOUCH)) {
565         mappers.push_back(createInputMapper<SingleTouchInputMapper>(contextPtr, readerConfig));
566     }
567 
568     // Joystick-like devices.
569     if (classes.test(InputDeviceClass::JOYSTICK)) {
570         mappers.push_back(createInputMapper<JoystickInputMapper>(contextPtr, readerConfig));
571     }
572 
573     // Motion sensor enabled devices.
574     if (classes.test(InputDeviceClass::SENSOR)) {
575         mappers.push_back(createInputMapper<SensorInputMapper>(contextPtr, readerConfig));
576     }
577 
578     // External stylus-like devices.
579     if (classes.test(InputDeviceClass::EXTERNAL_STYLUS)) {
580         mappers.push_back(createInputMapper<ExternalStylusInputMapper>(contextPtr, readerConfig));
581     }
582     return mappers;
583 }
584 
markSupportedKeyCodes(uint32_t sourceMask,const std::vector<int32_t> & keyCodes,uint8_t * outFlags)585 bool InputDevice::markSupportedKeyCodes(uint32_t sourceMask, const std::vector<int32_t>& keyCodes,
586                                         uint8_t* outFlags) {
587     bool result = false;
588     for_each_mapper([&result, sourceMask, keyCodes, outFlags](InputMapper& mapper) {
589         if (sourcesMatchMask(mapper.getSources(), sourceMask)) {
590             result |= mapper.markSupportedKeyCodes(sourceMask, keyCodes, outFlags);
591         }
592     });
593     return result;
594 }
595 
getKeyCodeForKeyLocation(int32_t locationKeyCode) const596 int32_t InputDevice::getKeyCodeForKeyLocation(int32_t locationKeyCode) const {
597     std::optional<int32_t> result = first_in_mappers<int32_t>(
598             [locationKeyCode](const InputMapper& mapper) -> std::optional<int32_t> const {
599                 if (sourcesMatchMask(mapper.getSources(), AINPUT_SOURCE_KEYBOARD)) {
600                     return std::make_optional(mapper.getKeyCodeForKeyLocation(locationKeyCode));
601                 }
602                 return std::nullopt;
603             });
604     if (!result) {
605         ALOGE("Failed to get key code for key location: No matching InputMapper with source mask "
606               "KEYBOARD found. The provided input device with id %d has sources %s.",
607               getId(), inputEventSourceToString(getSources()).c_str());
608         return AKEYCODE_UNKNOWN;
609     }
610     return *result;
611 }
612 
vibrate(const VibrationSequence & sequence,ssize_t repeat,int32_t token)613 std::list<NotifyArgs> InputDevice::vibrate(const VibrationSequence& sequence, ssize_t repeat,
614                                            int32_t token) {
615     std::list<NotifyArgs> out;
616     for_each_mapper([&](InputMapper& mapper) { out += mapper.vibrate(sequence, repeat, token); });
617     return out;
618 }
619 
cancelVibrate(int32_t token)620 std::list<NotifyArgs> InputDevice::cancelVibrate(int32_t token) {
621     std::list<NotifyArgs> out;
622     for_each_mapper([&](InputMapper& mapper) { out += mapper.cancelVibrate(token); });
623     return out;
624 }
625 
isVibrating()626 bool InputDevice::isVibrating() {
627     bool vibrating = false;
628     for_each_mapper([&vibrating](InputMapper& mapper) { vibrating |= mapper.isVibrating(); });
629     return vibrating;
630 }
631 
632 /* There's no guarantee the IDs provided by the different mappers are unique, so if we have two
633  * different vibration mappers then we could have duplicate IDs.
634  * Alternatively, if we have a merged device that has multiple evdev nodes with FF_* capabilities,
635  * we would definitely have duplicate IDs.
636  */
getVibratorIds()637 std::vector<int32_t> InputDevice::getVibratorIds() {
638     std::vector<int32_t> vibrators;
639     for_each_mapper([&vibrators](InputMapper& mapper) {
640         std::vector<int32_t> devVibs = mapper.getVibratorIds();
641         vibrators.reserve(vibrators.size() + devVibs.size());
642         vibrators.insert(vibrators.end(), devVibs.begin(), devVibs.end());
643     });
644     return vibrators;
645 }
646 
enableSensor(InputDeviceSensorType sensorType,std::chrono::microseconds samplingPeriod,std::chrono::microseconds maxBatchReportLatency)647 bool InputDevice::enableSensor(InputDeviceSensorType sensorType,
648                                std::chrono::microseconds samplingPeriod,
649                                std::chrono::microseconds maxBatchReportLatency) {
650     bool success = true;
651     for_each_mapper(
652             [&success, sensorType, samplingPeriod, maxBatchReportLatency](InputMapper& mapper) {
653                 success &= mapper.enableSensor(sensorType, samplingPeriod, maxBatchReportLatency);
654             });
655     return success;
656 }
657 
disableSensor(InputDeviceSensorType sensorType)658 void InputDevice::disableSensor(InputDeviceSensorType sensorType) {
659     for_each_mapper([sensorType](InputMapper& mapper) { mapper.disableSensor(sensorType); });
660 }
661 
flushSensor(InputDeviceSensorType sensorType)662 void InputDevice::flushSensor(InputDeviceSensorType sensorType) {
663     for_each_mapper([sensorType](InputMapper& mapper) { mapper.flushSensor(sensorType); });
664 }
665 
cancelTouch(nsecs_t when,nsecs_t readTime)666 std::list<NotifyArgs> InputDevice::cancelTouch(nsecs_t when, nsecs_t readTime) {
667     std::list<NotifyArgs> out;
668     for_each_mapper([&](InputMapper& mapper) { out += mapper.cancelTouch(when, readTime); });
669     return out;
670 }
671 
setLightColor(int32_t lightId,int32_t color)672 bool InputDevice::setLightColor(int32_t lightId, int32_t color) {
673     return mController ? mController->setLightColor(lightId, color) : false;
674 }
675 
setLightPlayerId(int32_t lightId,int32_t playerId)676 bool InputDevice::setLightPlayerId(int32_t lightId, int32_t playerId) {
677     return mController ? mController->setLightPlayerId(lightId, playerId) : false;
678 }
679 
getLightColor(int32_t lightId)680 std::optional<int32_t> InputDevice::getLightColor(int32_t lightId) {
681     return mController ? mController->getLightColor(lightId) : std::nullopt;
682 }
683 
getLightPlayerId(int32_t lightId)684 std::optional<int32_t> InputDevice::getLightPlayerId(int32_t lightId) {
685     return mController ? mController->getLightPlayerId(lightId) : std::nullopt;
686 }
687 
getMetaState()688 int32_t InputDevice::getMetaState() {
689     int32_t result = 0;
690     for_each_mapper([&result](InputMapper& mapper) { result |= mapper.getMetaState(); });
691     return result;
692 }
693 
bumpGeneration()694 void InputDevice::bumpGeneration() {
695     mGeneration = mContext->bumpGeneration();
696 }
697 
notifyReset(nsecs_t when)698 NotifyDeviceResetArgs InputDevice::notifyReset(nsecs_t when) {
699     return NotifyDeviceResetArgs(mContext->getNextId(), when, mId);
700 }
701 
getAssociatedDisplayId()702 std::optional<ui::LogicalDisplayId> InputDevice::getAssociatedDisplayId() {
703     // Check if we had associated to the specific display.
704     if (mAssociatedViewport) {
705         return mAssociatedViewport->displayId;
706     }
707 
708     // No associated display port, check if some InputMapper is associated.
709     return first_in_mappers<ui::LogicalDisplayId>(
710             [](InputMapper& mapper) { return mapper.getAssociatedDisplayId(); });
711 }
712 
713 // returns the number of mappers associated with the device
getMapperCount()714 size_t InputDevice::getMapperCount() {
715     size_t count = 0;
716     for (auto& deviceEntry : mDevices) {
717         auto& devicePair = deviceEntry.second;
718         auto& mappers = devicePair.second;
719         count += mappers.size();
720     }
721     return count;
722 }
723 
getTouchpadHardwareProperties()724 std::optional<HardwareProperties> InputDevice::getTouchpadHardwareProperties() {
725     std::optional<HardwareProperties> result = first_in_mappers<HardwareProperties>(
726             [](InputMapper& mapper) -> std::optional<HardwareProperties> {
727                 return mapper.getTouchpadHardwareProperties();
728             });
729 
730     return result;
731 }
732 
updateLedState(bool reset)733 void InputDevice::updateLedState(bool reset) {
734     for_each_mapper([reset](InputMapper& mapper) { mapper.updateLedState(reset); });
735 }
736 
getBatteryEventHubId() const737 std::optional<int32_t> InputDevice::getBatteryEventHubId() const {
738     return mController ? std::make_optional(mController->getEventHubId()) : std::nullopt;
739 }
740 
setKeyboardType(KeyboardType keyboardType)741 void InputDevice::setKeyboardType(KeyboardType keyboardType) {
742     if (mKeyboardType != keyboardType) {
743         mKeyboardType = keyboardType;
744         bumpGeneration();
745     }
746 }
747 
setKernelWakeEnabled(bool enabled)748 bool InputDevice::setKernelWakeEnabled(bool enabled) {
749     bool success = false;
750     for_each_subdevice([&enabled, &success](InputDeviceContext& context) {
751         success |= context.setKernelWakeEnabled(enabled);
752     });
753     return success;
754 }
755 
InputDeviceContext(InputDevice & device,int32_t eventHubId)756 InputDeviceContext::InputDeviceContext(InputDevice& device, int32_t eventHubId)
757       : mDevice(device),
758         mContext(device.getContext()),
759         mEventHub(device.getContext()->getEventHub()),
760         mId(eventHubId),
761         mDeviceId(device.getId()) {}
762 
~InputDeviceContext()763 InputDeviceContext::~InputDeviceContext() {}
764 
765 } // namespace android
766