1 /*
2  * Copyright (C) 2010 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 "InputReader.h"
20 
21 #include <android-base/stringprintf.h>
22 #include <errno.h>
23 #include <input/Keyboard.h>
24 #include <input/VirtualKeyMap.h>
25 #include <inttypes.h>
26 #include <limits.h>
27 #include <log/log.h>
28 #include <math.h>
29 #include <stddef.h>
30 #include <stdlib.h>
31 #include <unistd.h>
32 #include <utils/Errors.h>
33 #include <utils/Thread.h>
34 
35 #include "InputDevice.h"
36 
37 using android::base::StringPrintf;
38 
39 namespace android {
40 
41 // --- InputReader ---
42 
InputReader(std::shared_ptr<EventHubInterface> eventHub,const sp<InputReaderPolicyInterface> & policy,const sp<InputListenerInterface> & listener)43 InputReader::InputReader(std::shared_ptr<EventHubInterface> eventHub,
44                          const sp<InputReaderPolicyInterface>& policy,
45                          const sp<InputListenerInterface>& listener)
46       : mContext(this),
47         mEventHub(eventHub),
48         mPolicy(policy),
49         mGlobalMetaState(0),
50         mLedMetaState(AMETA_NUM_LOCK_ON),
51         mGeneration(1),
52         mNextInputDeviceId(END_RESERVED_ID),
53         mDisableVirtualKeysTimeout(LLONG_MIN),
54         mNextTimeout(LLONG_MAX),
55         mConfigurationChangesToRefresh(0) {
56     mQueuedListener = new QueuedInputListener(listener);
57 
58     { // acquire lock
59         std::scoped_lock _l(mLock);
60 
61         refreshConfigurationLocked(0);
62         updateGlobalMetaStateLocked();
63     } // release lock
64 }
65 
~InputReader()66 InputReader::~InputReader() {}
67 
start()68 status_t InputReader::start() {
69     if (mThread) {
70         return ALREADY_EXISTS;
71     }
72     mThread = std::make_unique<InputThread>(
73             "InputReader", [this]() { loopOnce(); }, [this]() { mEventHub->wake(); });
74     return OK;
75 }
76 
stop()77 status_t InputReader::stop() {
78     if (mThread && mThread->isCallingThread()) {
79         ALOGE("InputReader cannot be stopped from its own thread!");
80         return INVALID_OPERATION;
81     }
82     mThread.reset();
83     return OK;
84 }
85 
loopOnce()86 void InputReader::loopOnce() {
87     int32_t oldGeneration;
88     int32_t timeoutMillis;
89     bool inputDevicesChanged = false;
90     std::vector<InputDeviceInfo> inputDevices;
91     { // acquire lock
92         std::scoped_lock _l(mLock);
93 
94         oldGeneration = mGeneration;
95         timeoutMillis = -1;
96 
97         uint32_t changes = mConfigurationChangesToRefresh;
98         if (changes) {
99             mConfigurationChangesToRefresh = 0;
100             timeoutMillis = 0;
101             refreshConfigurationLocked(changes);
102         } else if (mNextTimeout != LLONG_MAX) {
103             nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
104             timeoutMillis = toMillisecondTimeoutDelay(now, mNextTimeout);
105         }
106     } // release lock
107 
108     size_t count = mEventHub->getEvents(timeoutMillis, mEventBuffer, EVENT_BUFFER_SIZE);
109 
110     { // acquire lock
111         std::scoped_lock _l(mLock);
112         mReaderIsAliveCondition.notify_all();
113 
114         if (count) {
115             processEventsLocked(mEventBuffer, count);
116         }
117 
118         if (mNextTimeout != LLONG_MAX) {
119             nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
120             if (now >= mNextTimeout) {
121 #if DEBUG_RAW_EVENTS
122                 ALOGD("Timeout expired, latency=%0.3fms", (now - mNextTimeout) * 0.000001f);
123 #endif
124                 mNextTimeout = LLONG_MAX;
125                 timeoutExpiredLocked(now);
126             }
127         }
128 
129         if (oldGeneration != mGeneration) {
130             inputDevicesChanged = true;
131             inputDevices = getInputDevicesLocked();
132         }
133     } // release lock
134 
135     // Send out a message that the describes the changed input devices.
136     if (inputDevicesChanged) {
137         mPolicy->notifyInputDevicesChanged(inputDevices);
138     }
139 
140     // Flush queued events out to the listener.
141     // This must happen outside of the lock because the listener could potentially call
142     // back into the InputReader's methods, such as getScanCodeState, or become blocked
143     // on another thread similarly waiting to acquire the InputReader lock thereby
144     // resulting in a deadlock.  This situation is actually quite plausible because the
145     // listener is actually the input dispatcher, which calls into the window manager,
146     // which occasionally calls into the input reader.
147     mQueuedListener->flush();
148 }
149 
processEventsLocked(const RawEvent * rawEvents,size_t count)150 void InputReader::processEventsLocked(const RawEvent* rawEvents, size_t count) {
151     for (const RawEvent* rawEvent = rawEvents; count;) {
152         int32_t type = rawEvent->type;
153         size_t batchSize = 1;
154         if (type < EventHubInterface::FIRST_SYNTHETIC_EVENT) {
155             int32_t deviceId = rawEvent->deviceId;
156             while (batchSize < count) {
157                 if (rawEvent[batchSize].type >= EventHubInterface::FIRST_SYNTHETIC_EVENT ||
158                     rawEvent[batchSize].deviceId != deviceId) {
159                     break;
160                 }
161                 batchSize += 1;
162             }
163 #if DEBUG_RAW_EVENTS
164             ALOGD("BatchSize: %zu Count: %zu", batchSize, count);
165 #endif
166             processEventsForDeviceLocked(deviceId, rawEvent, batchSize);
167         } else {
168             switch (rawEvent->type) {
169                 case EventHubInterface::DEVICE_ADDED:
170                     addDeviceLocked(rawEvent->when, rawEvent->deviceId);
171                     break;
172                 case EventHubInterface::DEVICE_REMOVED:
173                     removeDeviceLocked(rawEvent->when, rawEvent->deviceId);
174                     break;
175                 case EventHubInterface::FINISHED_DEVICE_SCAN:
176                     handleConfigurationChangedLocked(rawEvent->when);
177                     break;
178                 default:
179                     ALOG_ASSERT(false); // can't happen
180                     break;
181             }
182         }
183         count -= batchSize;
184         rawEvent += batchSize;
185     }
186 }
187 
addDeviceLocked(nsecs_t when,int32_t eventHubId)188 void InputReader::addDeviceLocked(nsecs_t when, int32_t eventHubId) {
189     if (mDevices.find(eventHubId) != mDevices.end()) {
190         ALOGW("Ignoring spurious device added event for eventHubId %d.", eventHubId);
191         return;
192     }
193 
194     InputDeviceIdentifier identifier = mEventHub->getDeviceIdentifier(eventHubId);
195     std::shared_ptr<InputDevice> device = createDeviceLocked(eventHubId, identifier);
196     device->configure(when, &mConfig, 0);
197     device->reset(when);
198 
199     if (device->isIgnored()) {
200         ALOGI("Device added: id=%d, eventHubId=%d, name='%s', descriptor='%s' "
201               "(ignored non-input device)",
202               device->getId(), eventHubId, identifier.name.c_str(), identifier.descriptor.c_str());
203     } else {
204         ALOGI("Device added: id=%d, eventHubId=%d, name='%s', descriptor='%s',sources=0x%08x",
205               device->getId(), eventHubId, identifier.name.c_str(), identifier.descriptor.c_str(),
206               device->getSources());
207     }
208 
209     mDevices.emplace(eventHubId, device);
210     // Add device to device to EventHub ids map.
211     const auto mapIt = mDeviceToEventHubIdsMap.find(device);
212     if (mapIt == mDeviceToEventHubIdsMap.end()) {
213         std::vector<int32_t> ids = {eventHubId};
214         mDeviceToEventHubIdsMap.emplace(device, ids);
215     } else {
216         mapIt->second.push_back(eventHubId);
217     }
218     bumpGenerationLocked();
219 
220     if (device->getClasses().test(InputDeviceClass::EXTERNAL_STYLUS)) {
221         notifyExternalStylusPresenceChangedLocked();
222     }
223 
224     // Sensor input device is noisy, to save power disable it by default.
225     // Input device is classified as SENSOR when any sub device is a SENSOR device, check Eventhub
226     // device class to disable SENSOR sub device only.
227     if (mEventHub->getDeviceClasses(eventHubId).test(InputDeviceClass::SENSOR)) {
228         mEventHub->disableDevice(eventHubId);
229     }
230 }
231 
removeDeviceLocked(nsecs_t when,int32_t eventHubId)232 void InputReader::removeDeviceLocked(nsecs_t when, int32_t eventHubId) {
233     auto deviceIt = mDevices.find(eventHubId);
234     if (deviceIt == mDevices.end()) {
235         ALOGW("Ignoring spurious device removed event for eventHubId %d.", eventHubId);
236         return;
237     }
238 
239     std::shared_ptr<InputDevice> device = std::move(deviceIt->second);
240     mDevices.erase(deviceIt);
241     // Erase device from device to EventHub ids map.
242     auto mapIt = mDeviceToEventHubIdsMap.find(device);
243     if (mapIt != mDeviceToEventHubIdsMap.end()) {
244         std::vector<int32_t>& eventHubIds = mapIt->second;
245         eventHubIds.erase(std::remove_if(eventHubIds.begin(), eventHubIds.end(),
246                                          [eventHubId](int32_t eId) { return eId == eventHubId; }),
247                           eventHubIds.end());
248         if (eventHubIds.size() == 0) {
249             mDeviceToEventHubIdsMap.erase(mapIt);
250         }
251     }
252     bumpGenerationLocked();
253 
254     if (device->isIgnored()) {
255         ALOGI("Device removed: id=%d, eventHubId=%d, name='%s', descriptor='%s' "
256               "(ignored non-input device)",
257               device->getId(), eventHubId, device->getName().c_str(),
258               device->getDescriptor().c_str());
259     } else {
260         ALOGI("Device removed: id=%d, eventHubId=%d, name='%s', descriptor='%s', sources=0x%08x",
261               device->getId(), eventHubId, device->getName().c_str(),
262               device->getDescriptor().c_str(), device->getSources());
263     }
264 
265     device->removeEventHubDevice(eventHubId);
266 
267     if (device->getClasses().test(InputDeviceClass::EXTERNAL_STYLUS)) {
268         notifyExternalStylusPresenceChangedLocked();
269     }
270 
271     if (device->hasEventHubDevices()) {
272         device->configure(when, &mConfig, 0);
273     }
274     device->reset(when);
275 }
276 
createDeviceLocked(int32_t eventHubId,const InputDeviceIdentifier & identifier)277 std::shared_ptr<InputDevice> InputReader::createDeviceLocked(
278         int32_t eventHubId, const InputDeviceIdentifier& identifier) {
279     auto deviceIt = std::find_if(mDevices.begin(), mDevices.end(), [identifier](auto& devicePair) {
280         return devicePair.second->getDescriptor().size() && identifier.descriptor.size() &&
281                 devicePair.second->getDescriptor() == identifier.descriptor;
282     });
283 
284     std::shared_ptr<InputDevice> device;
285     if (deviceIt != mDevices.end()) {
286         device = deviceIt->second;
287     } else {
288         int32_t deviceId = (eventHubId < END_RESERVED_ID) ? eventHubId : nextInputDeviceIdLocked();
289         device = std::make_shared<InputDevice>(&mContext, deviceId, bumpGenerationLocked(),
290                                                identifier);
291     }
292     device->addEventHubDevice(eventHubId);
293     return device;
294 }
295 
processEventsForDeviceLocked(int32_t eventHubId,const RawEvent * rawEvents,size_t count)296 void InputReader::processEventsForDeviceLocked(int32_t eventHubId, const RawEvent* rawEvents,
297                                                size_t count) {
298     auto deviceIt = mDevices.find(eventHubId);
299     if (deviceIt == mDevices.end()) {
300         ALOGW("Discarding event for unknown eventHubId %d.", eventHubId);
301         return;
302     }
303 
304     std::shared_ptr<InputDevice>& device = deviceIt->second;
305     if (device->isIgnored()) {
306         // ALOGD("Discarding event for ignored deviceId %d.", deviceId);
307         return;
308     }
309 
310     device->process(rawEvents, count);
311 }
312 
findInputDeviceLocked(int32_t deviceId)313 InputDevice* InputReader::findInputDeviceLocked(int32_t deviceId) {
314     auto deviceIt =
315             std::find_if(mDevices.begin(), mDevices.end(), [deviceId](const auto& devicePair) {
316                 return devicePair.second->getId() == deviceId;
317             });
318     if (deviceIt != mDevices.end()) {
319         return deviceIt->second.get();
320     }
321     return nullptr;
322 }
323 
timeoutExpiredLocked(nsecs_t when)324 void InputReader::timeoutExpiredLocked(nsecs_t when) {
325     for (auto& devicePair : mDevices) {
326         std::shared_ptr<InputDevice>& device = devicePair.second;
327         if (!device->isIgnored()) {
328             device->timeoutExpired(when);
329         }
330     }
331 }
332 
nextInputDeviceIdLocked()333 int32_t InputReader::nextInputDeviceIdLocked() {
334     return ++mNextInputDeviceId;
335 }
336 
handleConfigurationChangedLocked(nsecs_t when)337 void InputReader::handleConfigurationChangedLocked(nsecs_t when) {
338     // Reset global meta state because it depends on the list of all configured devices.
339     updateGlobalMetaStateLocked();
340 
341     // Enqueue configuration changed.
342     NotifyConfigurationChangedArgs args(mContext.getNextId(), when);
343     mQueuedListener->notifyConfigurationChanged(&args);
344 }
345 
refreshConfigurationLocked(uint32_t changes)346 void InputReader::refreshConfigurationLocked(uint32_t changes) {
347     mPolicy->getReaderConfiguration(&mConfig);
348     mEventHub->setExcludedDevices(mConfig.excludedDeviceNames);
349 
350     if (!changes) return;
351 
352     ALOGI("Reconfiguring input devices, changes=%s",
353           InputReaderConfiguration::changesToString(changes).c_str());
354     nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
355 
356     if (changes & InputReaderConfiguration::CHANGE_DISPLAY_INFO) {
357         updatePointerDisplayLocked();
358     }
359 
360     if (changes & InputReaderConfiguration::CHANGE_MUST_REOPEN) {
361         mEventHub->requestReopenDevices();
362     } else {
363         for (auto& devicePair : mDevices) {
364             std::shared_ptr<InputDevice>& device = devicePair.second;
365             device->configure(now, &mConfig, changes);
366         }
367     }
368 
369     if (changes & InputReaderConfiguration::CHANGE_POINTER_CAPTURE) {
370         if (mCurrentPointerCaptureRequest == mConfig.pointerCaptureRequest) {
371             ALOGV("Skipping notifying pointer capture changes: "
372                   "There was no change in the pointer capture state.");
373         } else {
374             mCurrentPointerCaptureRequest = mConfig.pointerCaptureRequest;
375             const NotifyPointerCaptureChangedArgs args(mContext.getNextId(), now,
376                                                        mCurrentPointerCaptureRequest);
377             mQueuedListener->notifyPointerCaptureChanged(&args);
378         }
379     }
380 }
381 
updateGlobalMetaStateLocked()382 void InputReader::updateGlobalMetaStateLocked() {
383     mGlobalMetaState = 0;
384 
385     for (auto& devicePair : mDevices) {
386         std::shared_ptr<InputDevice>& device = devicePair.second;
387         mGlobalMetaState |= device->getMetaState();
388     }
389 }
390 
getGlobalMetaStateLocked()391 int32_t InputReader::getGlobalMetaStateLocked() {
392     return mGlobalMetaState;
393 }
394 
updateLedMetaStateLocked(int32_t metaState)395 void InputReader::updateLedMetaStateLocked(int32_t metaState) {
396     mLedMetaState = metaState;
397     for (auto& devicePair : mDevices) {
398         std::shared_ptr<InputDevice>& device = devicePair.second;
399         device->updateLedState(false);
400     }
401 }
402 
getLedMetaStateLocked()403 int32_t InputReader::getLedMetaStateLocked() {
404     return mLedMetaState;
405 }
406 
notifyExternalStylusPresenceChangedLocked()407 void InputReader::notifyExternalStylusPresenceChangedLocked() {
408     refreshConfigurationLocked(InputReaderConfiguration::CHANGE_EXTERNAL_STYLUS_PRESENCE);
409 }
410 
getExternalStylusDevicesLocked(std::vector<InputDeviceInfo> & outDevices)411 void InputReader::getExternalStylusDevicesLocked(std::vector<InputDeviceInfo>& outDevices) {
412     for (auto& devicePair : mDevices) {
413         std::shared_ptr<InputDevice>& device = devicePair.second;
414         if (device->getClasses().test(InputDeviceClass::EXTERNAL_STYLUS) && !device->isIgnored()) {
415             outDevices.push_back(device->getDeviceInfo());
416         }
417     }
418 }
419 
dispatchExternalStylusStateLocked(const StylusState & state)420 void InputReader::dispatchExternalStylusStateLocked(const StylusState& state) {
421     for (auto& devicePair : mDevices) {
422         std::shared_ptr<InputDevice>& device = devicePair.second;
423         device->updateExternalStylusState(state);
424     }
425 }
426 
disableVirtualKeysUntilLocked(nsecs_t time)427 void InputReader::disableVirtualKeysUntilLocked(nsecs_t time) {
428     mDisableVirtualKeysTimeout = time;
429 }
430 
shouldDropVirtualKeyLocked(nsecs_t now,int32_t keyCode,int32_t scanCode)431 bool InputReader::shouldDropVirtualKeyLocked(nsecs_t now, int32_t keyCode, int32_t scanCode) {
432     if (now < mDisableVirtualKeysTimeout) {
433         ALOGI("Dropping virtual key from device because virtual keys are "
434               "temporarily disabled for the next %0.3fms.  keyCode=%d, scanCode=%d",
435               (mDisableVirtualKeysTimeout - now) * 0.000001, keyCode, scanCode);
436         return true;
437     } else {
438         return false;
439     }
440 }
441 
getPointerControllerLocked(int32_t deviceId)442 std::shared_ptr<PointerControllerInterface> InputReader::getPointerControllerLocked(
443         int32_t deviceId) {
444     std::shared_ptr<PointerControllerInterface> controller = mPointerController.lock();
445     if (controller == nullptr) {
446         controller = mPolicy->obtainPointerController(deviceId);
447         mPointerController = controller;
448         updatePointerDisplayLocked();
449     }
450     return controller;
451 }
452 
updatePointerDisplayLocked()453 void InputReader::updatePointerDisplayLocked() {
454     std::shared_ptr<PointerControllerInterface> controller = mPointerController.lock();
455     if (controller == nullptr) {
456         return;
457     }
458 
459     std::optional<DisplayViewport> viewport =
460             mConfig.getDisplayViewportById(mConfig.defaultPointerDisplayId);
461     if (!viewport) {
462         ALOGW("Can't find the designated viewport with ID %" PRId32 " to update cursor input "
463               "mapper. Fall back to default display",
464               mConfig.defaultPointerDisplayId);
465         viewport = mConfig.getDisplayViewportById(ADISPLAY_ID_DEFAULT);
466     }
467     if (!viewport) {
468         ALOGE("Still can't find a viable viewport to update cursor input mapper. Skip setting it to"
469               " PointerController.");
470         return;
471     }
472 
473     controller->setDisplayViewport(*viewport);
474 }
475 
fadePointerLocked()476 void InputReader::fadePointerLocked() {
477     std::shared_ptr<PointerControllerInterface> controller = mPointerController.lock();
478     if (controller != nullptr) {
479         controller->fade(PointerControllerInterface::Transition::GRADUAL);
480     }
481 }
482 
requestTimeoutAtTimeLocked(nsecs_t when)483 void InputReader::requestTimeoutAtTimeLocked(nsecs_t when) {
484     if (when < mNextTimeout) {
485         mNextTimeout = when;
486         mEventHub->wake();
487     }
488 }
489 
bumpGenerationLocked()490 int32_t InputReader::bumpGenerationLocked() {
491     return ++mGeneration;
492 }
493 
getInputDevices() const494 std::vector<InputDeviceInfo> InputReader::getInputDevices() const {
495     std::scoped_lock _l(mLock);
496     return getInputDevicesLocked();
497 }
498 
getInputDevicesLocked() const499 std::vector<InputDeviceInfo> InputReader::getInputDevicesLocked() const {
500     std::vector<InputDeviceInfo> outInputDevices;
501     outInputDevices.reserve(mDeviceToEventHubIdsMap.size());
502 
503     for (const auto& [device, eventHubIds] : mDeviceToEventHubIdsMap) {
504         if (!device->isIgnored()) {
505             outInputDevices.push_back(device->getDeviceInfo());
506         }
507     }
508     return outInputDevices;
509 }
510 
getKeyCodeState(int32_t deviceId,uint32_t sourceMask,int32_t keyCode)511 int32_t InputReader::getKeyCodeState(int32_t deviceId, uint32_t sourceMask, int32_t keyCode) {
512     std::scoped_lock _l(mLock);
513 
514     return getStateLocked(deviceId, sourceMask, keyCode, &InputDevice::getKeyCodeState);
515 }
516 
getScanCodeState(int32_t deviceId,uint32_t sourceMask,int32_t scanCode)517 int32_t InputReader::getScanCodeState(int32_t deviceId, uint32_t sourceMask, int32_t scanCode) {
518     std::scoped_lock _l(mLock);
519 
520     return getStateLocked(deviceId, sourceMask, scanCode, &InputDevice::getScanCodeState);
521 }
522 
getSwitchState(int32_t deviceId,uint32_t sourceMask,int32_t switchCode)523 int32_t InputReader::getSwitchState(int32_t deviceId, uint32_t sourceMask, int32_t switchCode) {
524     std::scoped_lock _l(mLock);
525 
526     return getStateLocked(deviceId, sourceMask, switchCode, &InputDevice::getSwitchState);
527 }
528 
getStateLocked(int32_t deviceId,uint32_t sourceMask,int32_t code,GetStateFunc getStateFunc)529 int32_t InputReader::getStateLocked(int32_t deviceId, uint32_t sourceMask, int32_t code,
530                                     GetStateFunc getStateFunc) {
531     int32_t result = AKEY_STATE_UNKNOWN;
532     if (deviceId >= 0) {
533         InputDevice* device = findInputDeviceLocked(deviceId);
534         if (device && !device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
535             result = (device->*getStateFunc)(sourceMask, code);
536         }
537     } else {
538         for (auto& devicePair : mDevices) {
539             std::shared_ptr<InputDevice>& device = devicePair.second;
540             if (!device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
541                 // If any device reports AKEY_STATE_DOWN or AKEY_STATE_VIRTUAL, return that
542                 // value.  Otherwise, return AKEY_STATE_UP as long as one device reports it.
543                 int32_t currentResult = (device.get()->*getStateFunc)(sourceMask, code);
544                 if (currentResult >= AKEY_STATE_DOWN) {
545                     return currentResult;
546                 } else if (currentResult == AKEY_STATE_UP) {
547                     result = currentResult;
548                 }
549             }
550         }
551     }
552     return result;
553 }
554 
toggleCapsLockState(int32_t deviceId)555 void InputReader::toggleCapsLockState(int32_t deviceId) {
556     std::scoped_lock _l(mLock);
557     InputDevice* device = findInputDeviceLocked(deviceId);
558     if (!device) {
559         ALOGW("Ignoring toggleCapsLock for unknown deviceId %" PRId32 ".", deviceId);
560         return;
561     }
562 
563     if (device->isIgnored()) {
564         return;
565     }
566 
567     device->updateMetaState(AKEYCODE_CAPS_LOCK);
568 }
569 
hasKeys(int32_t deviceId,uint32_t sourceMask,size_t numCodes,const int32_t * keyCodes,uint8_t * outFlags)570 bool InputReader::hasKeys(int32_t deviceId, uint32_t sourceMask, size_t numCodes,
571                           const int32_t* keyCodes, uint8_t* outFlags) {
572     std::scoped_lock _l(mLock);
573 
574     memset(outFlags, 0, numCodes);
575     return markSupportedKeyCodesLocked(deviceId, sourceMask, numCodes, keyCodes, outFlags);
576 }
577 
markSupportedKeyCodesLocked(int32_t deviceId,uint32_t sourceMask,size_t numCodes,const int32_t * keyCodes,uint8_t * outFlags)578 bool InputReader::markSupportedKeyCodesLocked(int32_t deviceId, uint32_t sourceMask,
579                                               size_t numCodes, const int32_t* keyCodes,
580                                               uint8_t* outFlags) {
581     bool result = false;
582     if (deviceId >= 0) {
583         InputDevice* device = findInputDeviceLocked(deviceId);
584         if (device && !device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
585             result = device->markSupportedKeyCodes(sourceMask, numCodes, keyCodes, outFlags);
586         }
587     } else {
588         for (auto& devicePair : mDevices) {
589             std::shared_ptr<InputDevice>& device = devicePair.second;
590             if (!device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
591                 result |= device->markSupportedKeyCodes(sourceMask, numCodes, keyCodes, outFlags);
592             }
593         }
594     }
595     return result;
596 }
597 
requestRefreshConfiguration(uint32_t changes)598 void InputReader::requestRefreshConfiguration(uint32_t changes) {
599     std::scoped_lock _l(mLock);
600 
601     if (changes) {
602         bool needWake = !mConfigurationChangesToRefresh;
603         mConfigurationChangesToRefresh |= changes;
604 
605         if (needWake) {
606             mEventHub->wake();
607         }
608     }
609 }
610 
vibrate(int32_t deviceId,const VibrationSequence & sequence,ssize_t repeat,int32_t token)611 void InputReader::vibrate(int32_t deviceId, const VibrationSequence& sequence, ssize_t repeat,
612                           int32_t token) {
613     std::scoped_lock _l(mLock);
614 
615     InputDevice* device = findInputDeviceLocked(deviceId);
616     if (device) {
617         device->vibrate(sequence, repeat, token);
618     }
619 }
620 
cancelVibrate(int32_t deviceId,int32_t token)621 void InputReader::cancelVibrate(int32_t deviceId, int32_t token) {
622     std::scoped_lock _l(mLock);
623 
624     InputDevice* device = findInputDeviceLocked(deviceId);
625     if (device) {
626         device->cancelVibrate(token);
627     }
628 }
629 
isVibrating(int32_t deviceId)630 bool InputReader::isVibrating(int32_t deviceId) {
631     std::scoped_lock _l(mLock);
632 
633     InputDevice* device = findInputDeviceLocked(deviceId);
634     if (device) {
635         return device->isVibrating();
636     }
637     return false;
638 }
639 
getVibratorIds(int32_t deviceId)640 std::vector<int32_t> InputReader::getVibratorIds(int32_t deviceId) {
641     std::scoped_lock _l(mLock);
642 
643     InputDevice* device = findInputDeviceLocked(deviceId);
644     if (device) {
645         return device->getVibratorIds();
646     }
647     return {};
648 }
649 
disableSensor(int32_t deviceId,InputDeviceSensorType sensorType)650 void InputReader::disableSensor(int32_t deviceId, InputDeviceSensorType sensorType) {
651     std::scoped_lock _l(mLock);
652 
653     InputDevice* device = findInputDeviceLocked(deviceId);
654     if (device) {
655         device->disableSensor(sensorType);
656     }
657 }
658 
enableSensor(int32_t deviceId,InputDeviceSensorType sensorType,std::chrono::microseconds samplingPeriod,std::chrono::microseconds maxBatchReportLatency)659 bool InputReader::enableSensor(int32_t deviceId, InputDeviceSensorType sensorType,
660                                std::chrono::microseconds samplingPeriod,
661                                std::chrono::microseconds maxBatchReportLatency) {
662     std::scoped_lock _l(mLock);
663 
664     InputDevice* device = findInputDeviceLocked(deviceId);
665     if (device) {
666         return device->enableSensor(sensorType, samplingPeriod, maxBatchReportLatency);
667     }
668     return false;
669 }
670 
flushSensor(int32_t deviceId,InputDeviceSensorType sensorType)671 void InputReader::flushSensor(int32_t deviceId, InputDeviceSensorType sensorType) {
672     std::scoped_lock _l(mLock);
673 
674     InputDevice* device = findInputDeviceLocked(deviceId);
675     if (device) {
676         device->flushSensor(sensorType);
677     }
678 }
679 
getBatteryCapacity(int32_t deviceId)680 std::optional<int32_t> InputReader::getBatteryCapacity(int32_t deviceId) {
681     std::scoped_lock _l(mLock);
682 
683     InputDevice* device = findInputDeviceLocked(deviceId);
684     if (device) {
685         return device->getBatteryCapacity();
686     }
687     return std::nullopt;
688 }
689 
getBatteryStatus(int32_t deviceId)690 std::optional<int32_t> InputReader::getBatteryStatus(int32_t deviceId) {
691     std::scoped_lock _l(mLock);
692 
693     InputDevice* device = findInputDeviceLocked(deviceId);
694     if (device) {
695         return device->getBatteryStatus();
696     }
697     return std::nullopt;
698 }
699 
getLights(int32_t deviceId)700 std::vector<InputDeviceLightInfo> InputReader::getLights(int32_t deviceId) {
701     std::scoped_lock _l(mLock);
702 
703     InputDevice* device = findInputDeviceLocked(deviceId);
704     if (device == nullptr) {
705         return {};
706     }
707 
708     return device->getDeviceInfo().getLights();
709 }
710 
getSensors(int32_t deviceId)711 std::vector<InputDeviceSensorInfo> InputReader::getSensors(int32_t deviceId) {
712     std::scoped_lock _l(mLock);
713 
714     InputDevice* device = findInputDeviceLocked(deviceId);
715     if (device == nullptr) {
716         return {};
717     }
718 
719     return device->getDeviceInfo().getSensors();
720 }
721 
setLightColor(int32_t deviceId,int32_t lightId,int32_t color)722 bool InputReader::setLightColor(int32_t deviceId, int32_t lightId, int32_t color) {
723     std::scoped_lock _l(mLock);
724 
725     InputDevice* device = findInputDeviceLocked(deviceId);
726     if (device) {
727         return device->setLightColor(lightId, color);
728     }
729     return false;
730 }
731 
setLightPlayerId(int32_t deviceId,int32_t lightId,int32_t playerId)732 bool InputReader::setLightPlayerId(int32_t deviceId, int32_t lightId, int32_t playerId) {
733     std::scoped_lock _l(mLock);
734 
735     InputDevice* device = findInputDeviceLocked(deviceId);
736     if (device) {
737         return device->setLightPlayerId(lightId, playerId);
738     }
739     return false;
740 }
741 
getLightColor(int32_t deviceId,int32_t lightId)742 std::optional<int32_t> InputReader::getLightColor(int32_t deviceId, int32_t lightId) {
743     std::scoped_lock _l(mLock);
744 
745     InputDevice* device = findInputDeviceLocked(deviceId);
746     if (device) {
747         return device->getLightColor(lightId);
748     }
749     return std::nullopt;
750 }
751 
getLightPlayerId(int32_t deviceId,int32_t lightId)752 std::optional<int32_t> InputReader::getLightPlayerId(int32_t deviceId, int32_t lightId) {
753     std::scoped_lock _l(mLock);
754 
755     InputDevice* device = findInputDeviceLocked(deviceId);
756     if (device) {
757         return device->getLightPlayerId(lightId);
758     }
759     return std::nullopt;
760 }
761 
isInputDeviceEnabled(int32_t deviceId)762 bool InputReader::isInputDeviceEnabled(int32_t deviceId) {
763     std::scoped_lock _l(mLock);
764 
765     InputDevice* device = findInputDeviceLocked(deviceId);
766     if (device) {
767         return device->isEnabled();
768     }
769     ALOGW("Ignoring invalid device id %" PRId32 ".", deviceId);
770     return false;
771 }
772 
canDispatchToDisplay(int32_t deviceId,int32_t displayId)773 bool InputReader::canDispatchToDisplay(int32_t deviceId, int32_t displayId) {
774     std::scoped_lock _l(mLock);
775 
776     InputDevice* device = findInputDeviceLocked(deviceId);
777     if (!device) {
778         ALOGW("Ignoring invalid device id %" PRId32 ".", deviceId);
779         return false;
780     }
781 
782     if (!device->isEnabled()) {
783         ALOGW("Ignoring disabled device %s", device->getName().c_str());
784         return false;
785     }
786 
787     std::optional<int32_t> associatedDisplayId = device->getAssociatedDisplayId();
788     // No associated display. By default, can dispatch to all displays.
789     if (!associatedDisplayId) {
790         return true;
791     }
792 
793     if (*associatedDisplayId == ADISPLAY_ID_NONE) {
794         ALOGW("Device %s is associated with display ADISPLAY_ID_NONE.", device->getName().c_str());
795         return true;
796     }
797 
798     return *associatedDisplayId == displayId;
799 }
800 
dump(std::string & dump)801 void InputReader::dump(std::string& dump) {
802     std::scoped_lock _l(mLock);
803 
804     mEventHub->dump(dump);
805     dump += "\n";
806 
807     dump += StringPrintf("Input Reader State (Nums of device: %zu):\n",
808                          mDeviceToEventHubIdsMap.size());
809 
810     for (const auto& devicePair : mDeviceToEventHubIdsMap) {
811         const std::shared_ptr<InputDevice>& device = devicePair.first;
812         std::string eventHubDevStr = INDENT "EventHub Devices: [ ";
813         for (const auto& eId : devicePair.second) {
814             eventHubDevStr += StringPrintf("%d ", eId);
815         }
816         eventHubDevStr += "] \n";
817         device->dump(dump, eventHubDevStr);
818     }
819 
820     dump += INDENT "Configuration:\n";
821     dump += INDENT2 "ExcludedDeviceNames: [";
822     for (size_t i = 0; i < mConfig.excludedDeviceNames.size(); i++) {
823         if (i != 0) {
824             dump += ", ";
825         }
826         dump += mConfig.excludedDeviceNames[i];
827     }
828     dump += "]\n";
829     dump += StringPrintf(INDENT2 "VirtualKeyQuietTime: %0.1fms\n",
830                          mConfig.virtualKeyQuietTime * 0.000001f);
831 
832     dump += StringPrintf(INDENT2 "PointerVelocityControlParameters: "
833                                  "scale=%0.3f, lowThreshold=%0.3f, highThreshold=%0.3f, "
834                                  "acceleration=%0.3f\n",
835                          mConfig.pointerVelocityControlParameters.scale,
836                          mConfig.pointerVelocityControlParameters.lowThreshold,
837                          mConfig.pointerVelocityControlParameters.highThreshold,
838                          mConfig.pointerVelocityControlParameters.acceleration);
839 
840     dump += StringPrintf(INDENT2 "WheelVelocityControlParameters: "
841                                  "scale=%0.3f, lowThreshold=%0.3f, highThreshold=%0.3f, "
842                                  "acceleration=%0.3f\n",
843                          mConfig.wheelVelocityControlParameters.scale,
844                          mConfig.wheelVelocityControlParameters.lowThreshold,
845                          mConfig.wheelVelocityControlParameters.highThreshold,
846                          mConfig.wheelVelocityControlParameters.acceleration);
847 
848     dump += StringPrintf(INDENT2 "PointerGesture:\n");
849     dump += StringPrintf(INDENT3 "Enabled: %s\n", toString(mConfig.pointerGesturesEnabled));
850     dump += StringPrintf(INDENT3 "QuietInterval: %0.1fms\n",
851                          mConfig.pointerGestureQuietInterval * 0.000001f);
852     dump += StringPrintf(INDENT3 "DragMinSwitchSpeed: %0.1fpx/s\n",
853                          mConfig.pointerGestureDragMinSwitchSpeed);
854     dump += StringPrintf(INDENT3 "TapInterval: %0.1fms\n",
855                          mConfig.pointerGestureTapInterval * 0.000001f);
856     dump += StringPrintf(INDENT3 "TapDragInterval: %0.1fms\n",
857                          mConfig.pointerGestureTapDragInterval * 0.000001f);
858     dump += StringPrintf(INDENT3 "TapSlop: %0.1fpx\n", mConfig.pointerGestureTapSlop);
859     dump += StringPrintf(INDENT3 "MultitouchSettleInterval: %0.1fms\n",
860                          mConfig.pointerGestureMultitouchSettleInterval * 0.000001f);
861     dump += StringPrintf(INDENT3 "MultitouchMinDistance: %0.1fpx\n",
862                          mConfig.pointerGestureMultitouchMinDistance);
863     dump += StringPrintf(INDENT3 "SwipeTransitionAngleCosine: %0.1f\n",
864                          mConfig.pointerGestureSwipeTransitionAngleCosine);
865     dump += StringPrintf(INDENT3 "SwipeMaxWidthRatio: %0.1f\n",
866                          mConfig.pointerGestureSwipeMaxWidthRatio);
867     dump += StringPrintf(INDENT3 "MovementSpeedRatio: %0.1f\n",
868                          mConfig.pointerGestureMovementSpeedRatio);
869     dump += StringPrintf(INDENT3 "ZoomSpeedRatio: %0.1f\n", mConfig.pointerGestureZoomSpeedRatio);
870 
871     dump += INDENT3 "Viewports:\n";
872     mConfig.dump(dump);
873 }
874 
monitor()875 void InputReader::monitor() {
876     // Acquire and release the lock to ensure that the reader has not deadlocked.
877     std::unique_lock<std::mutex> lock(mLock);
878     mEventHub->wake();
879     mReaderIsAliveCondition.wait(lock);
880     // Check the EventHub
881     mEventHub->monitor();
882 }
883 
884 // --- InputReader::ContextImpl ---
885 
ContextImpl(InputReader * reader)886 InputReader::ContextImpl::ContextImpl(InputReader* reader)
887       : mReader(reader), mIdGenerator(IdGenerator::Source::INPUT_READER) {}
888 
updateGlobalMetaState()889 void InputReader::ContextImpl::updateGlobalMetaState() {
890     // lock is already held by the input loop
891     mReader->updateGlobalMetaStateLocked();
892 }
893 
getGlobalMetaState()894 int32_t InputReader::ContextImpl::getGlobalMetaState() {
895     // lock is already held by the input loop
896     return mReader->getGlobalMetaStateLocked();
897 }
898 
updateLedMetaState(int32_t metaState)899 void InputReader::ContextImpl::updateLedMetaState(int32_t metaState) {
900     // lock is already held by the input loop
901     mReader->updateLedMetaStateLocked(metaState);
902 }
903 
getLedMetaState()904 int32_t InputReader::ContextImpl::getLedMetaState() {
905     // lock is already held by the input loop
906     return mReader->getLedMetaStateLocked();
907 }
908 
disableVirtualKeysUntil(nsecs_t time)909 void InputReader::ContextImpl::disableVirtualKeysUntil(nsecs_t time) {
910     // lock is already held by the input loop
911     mReader->disableVirtualKeysUntilLocked(time);
912 }
913 
shouldDropVirtualKey(nsecs_t now,int32_t keyCode,int32_t scanCode)914 bool InputReader::ContextImpl::shouldDropVirtualKey(nsecs_t now, int32_t keyCode,
915                                                     int32_t scanCode) {
916     // lock is already held by the input loop
917     return mReader->shouldDropVirtualKeyLocked(now, keyCode, scanCode);
918 }
919 
fadePointer()920 void InputReader::ContextImpl::fadePointer() {
921     // lock is already held by the input loop
922     mReader->fadePointerLocked();
923 }
924 
getPointerController(int32_t deviceId)925 std::shared_ptr<PointerControllerInterface> InputReader::ContextImpl::getPointerController(
926         int32_t deviceId) {
927     // lock is already held by the input loop
928     return mReader->getPointerControllerLocked(deviceId);
929 }
930 
requestTimeoutAtTime(nsecs_t when)931 void InputReader::ContextImpl::requestTimeoutAtTime(nsecs_t when) {
932     // lock is already held by the input loop
933     mReader->requestTimeoutAtTimeLocked(when);
934 }
935 
bumpGeneration()936 int32_t InputReader::ContextImpl::bumpGeneration() {
937     // lock is already held by the input loop
938     return mReader->bumpGenerationLocked();
939 }
940 
getExternalStylusDevices(std::vector<InputDeviceInfo> & outDevices)941 void InputReader::ContextImpl::getExternalStylusDevices(std::vector<InputDeviceInfo>& outDevices) {
942     // lock is already held by whatever called refreshConfigurationLocked
943     mReader->getExternalStylusDevicesLocked(outDevices);
944 }
945 
dispatchExternalStylusState(const StylusState & state)946 void InputReader::ContextImpl::dispatchExternalStylusState(const StylusState& state) {
947     mReader->dispatchExternalStylusStateLocked(state);
948 }
949 
getPolicy()950 InputReaderPolicyInterface* InputReader::ContextImpl::getPolicy() {
951     return mReader->mPolicy.get();
952 }
953 
getListener()954 InputListenerInterface* InputReader::ContextImpl::getListener() {
955     return mReader->mQueuedListener.get();
956 }
957 
getEventHub()958 EventHubInterface* InputReader::ContextImpl::getEventHub() {
959     return mReader->mEventHub.get();
960 }
961 
getNextId()962 int32_t InputReader::ContextImpl::getNextId() {
963     return mIdGenerator.nextId();
964 }
965 
966 } // namespace android
967