• 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 "CursorInputMapper.h"
24 #include "ExternalStylusInputMapper.h"
25 #include "InputReaderContext.h"
26 #include "JoystickInputMapper.h"
27 #include "KeyboardInputMapper.h"
28 #include "MultiTouchInputMapper.h"
29 #include "RotaryEncoderInputMapper.h"
30 #include "SingleTouchInputMapper.h"
31 #include "SwitchInputMapper.h"
32 #include "VibratorInputMapper.h"
33 
34 namespace android {
35 
InputDevice(InputReaderContext * context,int32_t id,int32_t generation,const InputDeviceIdentifier & identifier)36 InputDevice::InputDevice(InputReaderContext* context, int32_t id, int32_t generation,
37                          const InputDeviceIdentifier& identifier)
38       : mContext(context),
39         mId(id),
40         mGeneration(generation),
41         mControllerNumber(0),
42         mIdentifier(identifier),
43         mClasses(0),
44         mSources(0),
45         mIsExternal(false),
46         mHasMic(false),
47         mDropUntilNextSync(false) {}
48 
~InputDevice()49 InputDevice::~InputDevice() {}
50 
isEnabled()51 bool InputDevice::isEnabled() {
52     if (!hasEventHubDevices()) {
53         return false;
54     }
55     // devices are either all enabled or all disabled, so we only need to check the first
56     auto& devicePair = mDevices.begin()->second;
57     auto& contextPtr = devicePair.first;
58     return contextPtr->isDeviceEnabled();
59 }
60 
setEnabled(bool enabled,nsecs_t when)61 void InputDevice::setEnabled(bool enabled, nsecs_t when) {
62     if (enabled && mAssociatedDisplayPort && !mAssociatedViewport) {
63         ALOGW("Cannot enable input device %s because it is associated with port %" PRIu8 ", "
64               "but the corresponding viewport is not found",
65               getName().c_str(), *mAssociatedDisplayPort);
66         enabled = false;
67     }
68 
69     if (isEnabled() == enabled) {
70         return;
71     }
72 
73     // When resetting some devices, the driver needs to be queried to ensure that a proper reset is
74     // performed. The querying must happen when the device is enabled, so we reset after enabling
75     // but before disabling the device. See MultiTouchMotionAccumulator::reset for more information.
76     if (enabled) {
77         for_each_subdevice([](auto& context) { context.enableDevice(); });
78         reset(when);
79     } else {
80         reset(when);
81         for_each_subdevice([](auto& context) { context.disableDevice(); });
82     }
83     // Must change generation to flag this device as changed
84     bumpGeneration();
85 }
86 
dump(std::string & dump,const std::string & eventHubDevStr)87 void InputDevice::dump(std::string& dump, const std::string& eventHubDevStr) {
88     InputDeviceInfo deviceInfo;
89     getDeviceInfo(&deviceInfo);
90 
91     dump += StringPrintf(INDENT "Device %d: %s\n", deviceInfo.getId(),
92                          deviceInfo.getDisplayName().c_str());
93     dump += StringPrintf(INDENT "%s", eventHubDevStr.c_str());
94     dump += StringPrintf(INDENT2 "Generation: %d\n", mGeneration);
95     dump += StringPrintf(INDENT2 "IsExternal: %s\n", toString(mIsExternal));
96     dump += StringPrintf(INDENT2 "AssociatedDisplayPort: ");
97     if (mAssociatedDisplayPort) {
98         dump += StringPrintf("%" PRIu8 "\n", *mAssociatedDisplayPort);
99     } else {
100         dump += "<none>\n";
101     }
102     dump += StringPrintf(INDENT2 "HasMic:     %s\n", toString(mHasMic));
103     dump += StringPrintf(INDENT2 "Sources: 0x%08x\n", deviceInfo.getSources());
104     dump += StringPrintf(INDENT2 "KeyboardType: %d\n", deviceInfo.getKeyboardType());
105     dump += StringPrintf(INDENT2 "ControllerNum: %d\n", deviceInfo.getControllerNumber());
106 
107     const std::vector<InputDeviceInfo::MotionRange>& ranges = deviceInfo.getMotionRanges();
108     if (!ranges.empty()) {
109         dump += INDENT2 "Motion Ranges:\n";
110         for (size_t i = 0; i < ranges.size(); i++) {
111             const InputDeviceInfo::MotionRange& range = ranges[i];
112             const char* label = getAxisLabel(range.axis);
113             char name[32];
114             if (label) {
115                 strncpy(name, label, sizeof(name));
116                 name[sizeof(name) - 1] = '\0';
117             } else {
118                 snprintf(name, sizeof(name), "%d", range.axis);
119             }
120             dump += StringPrintf(INDENT3
121                                  "%s: source=0x%08x, "
122                                  "min=%0.3f, max=%0.3f, flat=%0.3f, fuzz=%0.3f, resolution=%0.3f\n",
123                                  name, range.source, range.min, range.max, range.flat, range.fuzz,
124                                  range.resolution);
125         }
126     }
127 
128     for_each_mapper([&dump](InputMapper& mapper) { mapper.dump(dump); });
129 }
130 
addEventHubDevice(int32_t eventHubId,bool populateMappers)131 void InputDevice::addEventHubDevice(int32_t eventHubId, bool populateMappers) {
132     if (mDevices.find(eventHubId) != mDevices.end()) {
133         return;
134     }
135     std::unique_ptr<InputDeviceContext> contextPtr(new InputDeviceContext(*this, eventHubId));
136     uint32_t classes = contextPtr->getDeviceClasses();
137     std::vector<std::unique_ptr<InputMapper>> mappers;
138 
139     // Check if we should skip population
140     if (!populateMappers) {
141         mDevices.insert({eventHubId, std::make_pair(std::move(contextPtr), std::move(mappers))});
142         return;
143     }
144 
145     // Switch-like devices.
146     if (classes & INPUT_DEVICE_CLASS_SWITCH) {
147         mappers.push_back(std::make_unique<SwitchInputMapper>(*contextPtr));
148     }
149 
150     // Scroll wheel-like devices.
151     if (classes & INPUT_DEVICE_CLASS_ROTARY_ENCODER) {
152         mappers.push_back(std::make_unique<RotaryEncoderInputMapper>(*contextPtr));
153     }
154 
155     // Vibrator-like devices.
156     if (classes & INPUT_DEVICE_CLASS_VIBRATOR) {
157         mappers.push_back(std::make_unique<VibratorInputMapper>(*contextPtr));
158     }
159 
160     // Keyboard-like devices.
161     uint32_t keyboardSource = 0;
162     int32_t keyboardType = AINPUT_KEYBOARD_TYPE_NON_ALPHABETIC;
163     if (classes & INPUT_DEVICE_CLASS_KEYBOARD) {
164         keyboardSource |= AINPUT_SOURCE_KEYBOARD;
165     }
166     if (classes & INPUT_DEVICE_CLASS_ALPHAKEY) {
167         keyboardType = AINPUT_KEYBOARD_TYPE_ALPHABETIC;
168     }
169     if (classes & INPUT_DEVICE_CLASS_DPAD) {
170         keyboardSource |= AINPUT_SOURCE_DPAD;
171     }
172     if (classes & INPUT_DEVICE_CLASS_GAMEPAD) {
173         keyboardSource |= AINPUT_SOURCE_GAMEPAD;
174     }
175 
176     if (keyboardSource != 0) {
177         mappers.push_back(
178                 std::make_unique<KeyboardInputMapper>(*contextPtr, keyboardSource, keyboardType));
179     }
180 
181     // Cursor-like devices.
182     if (classes & INPUT_DEVICE_CLASS_CURSOR) {
183         mappers.push_back(std::make_unique<CursorInputMapper>(*contextPtr));
184     }
185 
186     // Touchscreens and touchpad devices.
187     if (classes & INPUT_DEVICE_CLASS_TOUCH_MT) {
188         mappers.push_back(std::make_unique<MultiTouchInputMapper>(*contextPtr));
189     } else if (classes & INPUT_DEVICE_CLASS_TOUCH) {
190         mappers.push_back(std::make_unique<SingleTouchInputMapper>(*contextPtr));
191     }
192 
193     // Joystick-like devices.
194     if (classes & INPUT_DEVICE_CLASS_JOYSTICK) {
195         mappers.push_back(std::make_unique<JoystickInputMapper>(*contextPtr));
196     }
197 
198     // External stylus-like devices.
199     if (classes & INPUT_DEVICE_CLASS_EXTERNAL_STYLUS) {
200         mappers.push_back(std::make_unique<ExternalStylusInputMapper>(*contextPtr));
201     }
202 
203     // insert the context into the devices set
204     mDevices.insert({eventHubId, std::make_pair(std::move(contextPtr), std::move(mappers))});
205     // Must change generation to flag this device as changed
206     bumpGeneration();
207 }
208 
removeEventHubDevice(int32_t eventHubId)209 void InputDevice::removeEventHubDevice(int32_t eventHubId) {
210     mDevices.erase(eventHubId);
211 }
212 
configure(nsecs_t when,const InputReaderConfiguration * config,uint32_t changes)213 void InputDevice::configure(nsecs_t when, const InputReaderConfiguration* config,
214                             uint32_t changes) {
215     mSources = 0;
216     mClasses = 0;
217     mControllerNumber = 0;
218 
219     for_each_subdevice([this](InputDeviceContext& context) {
220         mClasses |= context.getDeviceClasses();
221         int32_t controllerNumber = context.getDeviceControllerNumber();
222         if (controllerNumber > 0) {
223             if (mControllerNumber && mControllerNumber != controllerNumber) {
224                 ALOGW("InputDevice::configure(): composite device contains multiple unique "
225                       "controller numbers");
226             }
227             mControllerNumber = controllerNumber;
228         }
229     });
230 
231     mIsExternal = !!(mClasses & INPUT_DEVICE_CLASS_EXTERNAL);
232     mHasMic = !!(mClasses & INPUT_DEVICE_CLASS_MIC);
233 
234     if (!isIgnored()) {
235         if (!changes) { // first time only
236             mConfiguration.clear();
237             for_each_subdevice([this](InputDeviceContext& context) {
238                 PropertyMap configuration;
239                 context.getConfiguration(&configuration);
240                 mConfiguration.addAll(&configuration);
241             });
242         }
243 
244         if (!changes || (changes & InputReaderConfiguration::CHANGE_KEYBOARD_LAYOUTS)) {
245             if (!(mClasses & INPUT_DEVICE_CLASS_VIRTUAL)) {
246                 sp<KeyCharacterMap> keyboardLayout =
247                         mContext->getPolicy()->getKeyboardLayoutOverlay(mIdentifier);
248                 bool shouldBumpGeneration = false;
249                 for_each_subdevice(
250                         [&keyboardLayout, &shouldBumpGeneration](InputDeviceContext& context) {
251                             if (context.setKeyboardLayoutOverlay(keyboardLayout)) {
252                                 shouldBumpGeneration = true;
253                             }
254                         });
255                 if (shouldBumpGeneration) {
256                     bumpGeneration();
257                 }
258             }
259         }
260 
261         if (!changes || (changes & InputReaderConfiguration::CHANGE_DEVICE_ALIAS)) {
262             if (!(mClasses & INPUT_DEVICE_CLASS_VIRTUAL)) {
263                 std::string alias = mContext->getPolicy()->getDeviceAlias(mIdentifier);
264                 if (mAlias != alias) {
265                     mAlias = alias;
266                     bumpGeneration();
267                 }
268             }
269         }
270 
271         if (!changes || (changes & InputReaderConfiguration::CHANGE_ENABLED_STATE)) {
272             auto it = config->disabledDevices.find(mId);
273             bool enabled = it == config->disabledDevices.end();
274             setEnabled(enabled, when);
275         }
276 
277         if (!changes || (changes & InputReaderConfiguration::CHANGE_DISPLAY_INFO)) {
278             // In most situations, no port will be specified.
279             mAssociatedDisplayPort = std::nullopt;
280             mAssociatedViewport = std::nullopt;
281             // Find the display port that corresponds to the current input port.
282             const std::string& inputPort = mIdentifier.location;
283             if (!inputPort.empty()) {
284                 const std::unordered_map<std::string, uint8_t>& ports = config->portAssociations;
285                 const auto& displayPort = ports.find(inputPort);
286                 if (displayPort != ports.end()) {
287                     mAssociatedDisplayPort = std::make_optional(displayPort->second);
288                 }
289             }
290 
291             // If the device was explicitly disabled by the user, it would be present in the
292             // "disabledDevices" list. If it is associated with a specific display, and it was not
293             // explicitly disabled, then enable/disable the device based on whether we can find the
294             // corresponding viewport.
295             bool enabled = (config->disabledDevices.find(mId) == config->disabledDevices.end());
296             if (mAssociatedDisplayPort) {
297                 mAssociatedViewport = config->getDisplayViewportByPort(*mAssociatedDisplayPort);
298                 if (!mAssociatedViewport) {
299                     ALOGW("Input device %s should be associated with display on port %" PRIu8 ", "
300                           "but the corresponding viewport is not found.",
301                           getName().c_str(), *mAssociatedDisplayPort);
302                     enabled = false;
303                 }
304             }
305 
306             if (changes) {
307                 // For first-time configuration, only allow device to be disabled after mappers have
308                 // finished configuring. This is because we need to read some of the properties from
309                 // the device's open fd.
310                 setEnabled(enabled, when);
311             }
312         }
313 
314         for_each_mapper([this, when, config, changes](InputMapper& mapper) {
315             mapper.configure(when, config, changes);
316             mSources |= mapper.getSources();
317         });
318 
319         // If a device is just plugged but it might be disabled, we need to update some info like
320         // axis range of touch from each InputMapper first, then disable it.
321         if (!changes) {
322             setEnabled(config->disabledDevices.find(mId) == config->disabledDevices.end(), when);
323         }
324     }
325 }
326 
reset(nsecs_t when)327 void InputDevice::reset(nsecs_t when) {
328     for_each_mapper([when](InputMapper& mapper) { mapper.reset(when); });
329 
330     mContext->updateGlobalMetaState();
331 
332     notifyReset(when);
333 }
334 
process(const RawEvent * rawEvents,size_t count)335 void InputDevice::process(const RawEvent* rawEvents, size_t count) {
336     // Process all of the events in order for each mapper.
337     // We cannot simply ask each mapper to process them in bulk because mappers may
338     // have side-effects that must be interleaved.  For example, joystick movement events and
339     // gamepad button presses are handled by different mappers but they should be dispatched
340     // in the order received.
341     for (const RawEvent* rawEvent = rawEvents; count != 0; rawEvent++) {
342 #if DEBUG_RAW_EVENTS
343         ALOGD("Input event: device=%d type=0x%04x code=0x%04x value=0x%08x when=%" PRId64,
344               rawEvent->deviceId, rawEvent->type, rawEvent->code, rawEvent->value, rawEvent->when);
345 #endif
346 
347         if (mDropUntilNextSync) {
348             if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
349                 mDropUntilNextSync = false;
350 #if DEBUG_RAW_EVENTS
351                 ALOGD("Recovered from input event buffer overrun.");
352 #endif
353             } else {
354 #if DEBUG_RAW_EVENTS
355                 ALOGD("Dropped input event while waiting for next input sync.");
356 #endif
357             }
358         } else if (rawEvent->type == EV_SYN && rawEvent->code == SYN_DROPPED) {
359             ALOGI("Detected input event buffer overrun for device %s.", getName().c_str());
360             mDropUntilNextSync = true;
361             reset(rawEvent->when);
362         } else {
363             for_each_mapper_in_subdevice(rawEvent->deviceId, [rawEvent](InputMapper& mapper) {
364                 mapper.process(rawEvent);
365             });
366         }
367         --count;
368     }
369 }
370 
timeoutExpired(nsecs_t when)371 void InputDevice::timeoutExpired(nsecs_t when) {
372     for_each_mapper([when](InputMapper& mapper) { mapper.timeoutExpired(when); });
373 }
374 
updateExternalStylusState(const StylusState & state)375 void InputDevice::updateExternalStylusState(const StylusState& state) {
376     for_each_mapper([state](InputMapper& mapper) { mapper.updateExternalStylusState(state); });
377 }
378 
getDeviceInfo(InputDeviceInfo * outDeviceInfo)379 void InputDevice::getDeviceInfo(InputDeviceInfo* outDeviceInfo) {
380     outDeviceInfo->initialize(mId, mGeneration, mControllerNumber, mIdentifier, mAlias, mIsExternal,
381                               mHasMic);
382     for_each_mapper(
383             [outDeviceInfo](InputMapper& mapper) { mapper.populateDeviceInfo(outDeviceInfo); });
384 }
385 
getKeyCodeState(uint32_t sourceMask,int32_t keyCode)386 int32_t InputDevice::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
387     return getState(sourceMask, keyCode, &InputMapper::getKeyCodeState);
388 }
389 
getScanCodeState(uint32_t sourceMask,int32_t scanCode)390 int32_t InputDevice::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
391     return getState(sourceMask, scanCode, &InputMapper::getScanCodeState);
392 }
393 
getSwitchState(uint32_t sourceMask,int32_t switchCode)394 int32_t InputDevice::getSwitchState(uint32_t sourceMask, int32_t switchCode) {
395     return getState(sourceMask, switchCode, &InputMapper::getSwitchState);
396 }
397 
getState(uint32_t sourceMask,int32_t code,GetStateFunc getStateFunc)398 int32_t InputDevice::getState(uint32_t sourceMask, int32_t code, GetStateFunc getStateFunc) {
399     int32_t result = AKEY_STATE_UNKNOWN;
400     for (auto& deviceEntry : mDevices) {
401         auto& devicePair = deviceEntry.second;
402         auto& mappers = devicePair.second;
403         for (auto& mapperPtr : mappers) {
404             InputMapper& mapper = *mapperPtr;
405             if (sourcesMatchMask(mapper.getSources(), sourceMask)) {
406                 // If any mapper reports AKEY_STATE_DOWN or AKEY_STATE_VIRTUAL, return that
407                 // value.  Otherwise, return AKEY_STATE_UP as long as one mapper reports it.
408                 int32_t currentResult = (mapper.*getStateFunc)(sourceMask, code);
409                 if (currentResult >= AKEY_STATE_DOWN) {
410                     return currentResult;
411                 } else if (currentResult == AKEY_STATE_UP) {
412                     result = currentResult;
413                 }
414             }
415         }
416     }
417     return result;
418 }
419 
markSupportedKeyCodes(uint32_t sourceMask,size_t numCodes,const int32_t * keyCodes,uint8_t * outFlags)420 bool InputDevice::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
421                                         const int32_t* keyCodes, uint8_t* outFlags) {
422     bool result = false;
423     for_each_mapper([&result, sourceMask, numCodes, keyCodes, outFlags](InputMapper& mapper) {
424         if (sourcesMatchMask(mapper.getSources(), sourceMask)) {
425             result |= mapper.markSupportedKeyCodes(sourceMask, numCodes, keyCodes, outFlags);
426         }
427     });
428     return result;
429 }
430 
vibrate(const nsecs_t * pattern,size_t patternSize,ssize_t repeat,int32_t token)431 void InputDevice::vibrate(const nsecs_t* pattern, size_t patternSize, ssize_t repeat,
432                           int32_t token) {
433     for_each_mapper([pattern, patternSize, repeat, token](InputMapper& mapper) {
434         mapper.vibrate(pattern, patternSize, repeat, token);
435     });
436 }
437 
cancelVibrate(int32_t token)438 void InputDevice::cancelVibrate(int32_t token) {
439     for_each_mapper([token](InputMapper& mapper) { mapper.cancelVibrate(token); });
440 }
441 
cancelTouch(nsecs_t when)442 void InputDevice::cancelTouch(nsecs_t when) {
443     for_each_mapper([when](InputMapper& mapper) { mapper.cancelTouch(when); });
444 }
445 
getMetaState()446 int32_t InputDevice::getMetaState() {
447     int32_t result = 0;
448     for_each_mapper([&result](InputMapper& mapper) { result |= mapper.getMetaState(); });
449     return result;
450 }
451 
updateMetaState(int32_t keyCode)452 void InputDevice::updateMetaState(int32_t keyCode) {
453     for_each_mapper([keyCode](InputMapper& mapper) { mapper.updateMetaState(keyCode); });
454 }
455 
bumpGeneration()456 void InputDevice::bumpGeneration() {
457     mGeneration = mContext->bumpGeneration();
458 }
459 
notifyReset(nsecs_t when)460 void InputDevice::notifyReset(nsecs_t when) {
461     NotifyDeviceResetArgs args(mContext->getNextId(), when, mId);
462     mContext->getListener()->notifyDeviceReset(&args);
463 }
464 
getAssociatedDisplayId()465 std::optional<int32_t> InputDevice::getAssociatedDisplayId() {
466     // Check if we had associated to the specific display.
467     if (mAssociatedViewport) {
468         return mAssociatedViewport->displayId;
469     }
470 
471     // No associated display port, check if some InputMapper is associated.
472     return first_in_mappers<int32_t>(
473             [](InputMapper& mapper) { return mapper.getAssociatedDisplayId(); });
474 }
475 
476 // returns the number of mappers associated with the device
getMapperCount()477 size_t InputDevice::getMapperCount() {
478     size_t count = 0;
479     for (auto& deviceEntry : mDevices) {
480         auto& devicePair = deviceEntry.second;
481         auto& mappers = devicePair.second;
482         count += mappers.size();
483     }
484     return count;
485 }
486 
InputDeviceContext(InputDevice & device,int32_t eventHubId)487 InputDeviceContext::InputDeviceContext(InputDevice& device, int32_t eventHubId)
488       : mDevice(device),
489         mContext(device.getContext()),
490         mEventHub(device.getContext()->getEventHub()),
491         mId(eventHubId),
492         mDeviceId(device.getId()) {}
493 
~InputDeviceContext()494 InputDeviceContext::~InputDeviceContext() {}
495 
496 } // namespace android
497