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         mGeneration(1),
51         mNextInputDeviceId(END_RESERVED_ID),
52         mDisableVirtualKeysTimeout(LLONG_MIN),
53         mNextTimeout(LLONG_MAX),
54         mConfigurationChangesToRefresh(0) {
55     mQueuedListener = new QueuedInputListener(listener);
56 
57     { // acquire lock
58         AutoMutex _l(mLock);
59 
60         refreshConfigurationLocked(0);
61         updateGlobalMetaStateLocked();
62     } // release lock
63 }
64 
~InputReader()65 InputReader::~InputReader() {}
66 
start()67 status_t InputReader::start() {
68     if (mThread) {
69         return ALREADY_EXISTS;
70     }
71     mThread = std::make_unique<InputThread>(
72             "InputReader", [this]() { loopOnce(); }, [this]() { mEventHub->wake(); });
73     return OK;
74 }
75 
stop()76 status_t InputReader::stop() {
77     if (mThread && mThread->isCallingThread()) {
78         ALOGE("InputReader cannot be stopped from its own thread!");
79         return INVALID_OPERATION;
80     }
81     mThread.reset();
82     return OK;
83 }
84 
loopOnce()85 void InputReader::loopOnce() {
86     int32_t oldGeneration;
87     int32_t timeoutMillis;
88     bool inputDevicesChanged = false;
89     std::vector<InputDeviceInfo> inputDevices;
90     { // acquire lock
91         AutoMutex _l(mLock);
92 
93         oldGeneration = mGeneration;
94         timeoutMillis = -1;
95 
96         uint32_t changes = mConfigurationChangesToRefresh;
97         if (changes) {
98             mConfigurationChangesToRefresh = 0;
99             timeoutMillis = 0;
100             refreshConfigurationLocked(changes);
101         } else if (mNextTimeout != LLONG_MAX) {
102             nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
103             timeoutMillis = toMillisecondTimeoutDelay(now, mNextTimeout);
104         }
105     } // release lock
106 
107     size_t count = mEventHub->getEvents(timeoutMillis, mEventBuffer, EVENT_BUFFER_SIZE);
108 
109     { // acquire lock
110         AutoMutex _l(mLock);
111         mReaderIsAliveCondition.broadcast();
112 
113         if (count) {
114             processEventsLocked(mEventBuffer, count);
115         }
116 
117         if (mNextTimeout != LLONG_MAX) {
118             nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
119             if (now >= mNextTimeout) {
120 #if DEBUG_RAW_EVENTS
121                 ALOGD("Timeout expired, latency=%0.3fms", (now - mNextTimeout) * 0.000001f);
122 #endif
123                 mNextTimeout = LLONG_MAX;
124                 timeoutExpiredLocked(now);
125             }
126         }
127 
128         if (oldGeneration != mGeneration) {
129             inputDevicesChanged = true;
130             getInputDevicesLocked(inputDevices);
131         }
132     } // release lock
133 
134     // Send out a message that the describes the changed input devices.
135     if (inputDevicesChanged) {
136         mPolicy->notifyInputDevicesChanged(inputDevices);
137     }
138 
139     // Flush queued events out to the listener.
140     // This must happen outside of the lock because the listener could potentially call
141     // back into the InputReader's methods, such as getScanCodeState, or become blocked
142     // on another thread similarly waiting to acquire the InputReader lock thereby
143     // resulting in a deadlock.  This situation is actually quite plausible because the
144     // listener is actually the input dispatcher, which calls into the window manager,
145     // which occasionally calls into the input reader.
146     mQueuedListener->flush();
147 }
148 
processEventsLocked(const RawEvent * rawEvents,size_t count)149 void InputReader::processEventsLocked(const RawEvent* rawEvents, size_t count) {
150     for (const RawEvent* rawEvent = rawEvents; count;) {
151         int32_t type = rawEvent->type;
152         size_t batchSize = 1;
153         if (type < EventHubInterface::FIRST_SYNTHETIC_EVENT) {
154             int32_t deviceId = rawEvent->deviceId;
155             while (batchSize < count) {
156                 if (rawEvent[batchSize].type >= EventHubInterface::FIRST_SYNTHETIC_EVENT ||
157                     rawEvent[batchSize].deviceId != deviceId) {
158                     break;
159                 }
160                 batchSize += 1;
161             }
162 #if DEBUG_RAW_EVENTS
163             ALOGD("BatchSize: %zu Count: %zu", batchSize, count);
164 #endif
165             processEventsForDeviceLocked(deviceId, rawEvent, batchSize);
166         } else {
167             switch (rawEvent->type) {
168                 case EventHubInterface::DEVICE_ADDED:
169                     addDeviceLocked(rawEvent->when, rawEvent->deviceId);
170                     break;
171                 case EventHubInterface::DEVICE_REMOVED:
172                     removeDeviceLocked(rawEvent->when, rawEvent->deviceId);
173                     break;
174                 case EventHubInterface::FINISHED_DEVICE_SCAN:
175                     handleConfigurationChangedLocked(rawEvent->when);
176                     break;
177                 default:
178                     ALOG_ASSERT(false); // can't happen
179                     break;
180             }
181         }
182         count -= batchSize;
183         rawEvent += batchSize;
184     }
185 }
186 
addDeviceLocked(nsecs_t when,int32_t eventHubId)187 void InputReader::addDeviceLocked(nsecs_t when, int32_t eventHubId) {
188     if (mDevices.find(eventHubId) != mDevices.end()) {
189         ALOGW("Ignoring spurious device added event for eventHubId %d.", eventHubId);
190         return;
191     }
192 
193     InputDeviceIdentifier identifier = mEventHub->getDeviceIdentifier(eventHubId);
194     std::shared_ptr<InputDevice> device = createDeviceLocked(eventHubId, identifier);
195     device->configure(when, &mConfig, 0);
196     device->reset(when);
197 
198     if (device->isIgnored()) {
199         ALOGI("Device added: id=%d, eventHubId=%d, name='%s', descriptor='%s' "
200               "(ignored non-input device)",
201               device->getId(), eventHubId, identifier.name.c_str(), identifier.descriptor.c_str());
202     } else {
203         ALOGI("Device added: id=%d, eventHubId=%d, name='%s', descriptor='%s',sources=0x%08x",
204               device->getId(), eventHubId, identifier.name.c_str(), identifier.descriptor.c_str(),
205               device->getSources());
206     }
207 
208     mDevices.emplace(eventHubId, device);
209     bumpGenerationLocked();
210 
211     if (device->getClasses() & INPUT_DEVICE_CLASS_EXTERNAL_STYLUS) {
212         notifyExternalStylusPresenceChanged();
213     }
214 }
215 
removeDeviceLocked(nsecs_t when,int32_t eventHubId)216 void InputReader::removeDeviceLocked(nsecs_t when, int32_t eventHubId) {
217     auto deviceIt = mDevices.find(eventHubId);
218     if (deviceIt == mDevices.end()) {
219         ALOGW("Ignoring spurious device removed event for eventHubId %d.", eventHubId);
220         return;
221     }
222 
223     std::shared_ptr<InputDevice> device = std::move(deviceIt->second);
224     mDevices.erase(deviceIt);
225     bumpGenerationLocked();
226 
227     if (device->isIgnored()) {
228         ALOGI("Device removed: id=%d, eventHubId=%d, name='%s', descriptor='%s' "
229               "(ignored non-input device)",
230               device->getId(), eventHubId, device->getName().c_str(),
231               device->getDescriptor().c_str());
232     } else {
233         ALOGI("Device removed: id=%d, eventHubId=%d, name='%s', descriptor='%s', sources=0x%08x",
234               device->getId(), eventHubId, device->getName().c_str(),
235               device->getDescriptor().c_str(), device->getSources());
236     }
237 
238     device->removeEventHubDevice(eventHubId);
239 
240     if (device->getClasses() & INPUT_DEVICE_CLASS_EXTERNAL_STYLUS) {
241         notifyExternalStylusPresenceChanged();
242     }
243 
244     if (device->hasEventHubDevices()) {
245         device->configure(when, &mConfig, 0);
246     }
247     device->reset(when);
248 }
249 
createDeviceLocked(int32_t eventHubId,const InputDeviceIdentifier & identifier)250 std::shared_ptr<InputDevice> InputReader::createDeviceLocked(
251         int32_t eventHubId, const InputDeviceIdentifier& identifier) {
252     auto deviceIt = std::find_if(mDevices.begin(), mDevices.end(), [identifier](auto& devicePair) {
253         return devicePair.second->getDescriptor().size() && identifier.descriptor.size() &&
254                 devicePair.second->getDescriptor() == identifier.descriptor;
255     });
256 
257     std::shared_ptr<InputDevice> device;
258     if (deviceIt != mDevices.end()) {
259         device = deviceIt->second;
260     } else {
261         int32_t deviceId = (eventHubId < END_RESERVED_ID) ? eventHubId : nextInputDeviceIdLocked();
262         device = std::make_shared<InputDevice>(&mContext, deviceId, bumpGenerationLocked(),
263                                                identifier);
264     }
265     device->addEventHubDevice(eventHubId);
266     return device;
267 }
268 
processEventsForDeviceLocked(int32_t eventHubId,const RawEvent * rawEvents,size_t count)269 void InputReader::processEventsForDeviceLocked(int32_t eventHubId, const RawEvent* rawEvents,
270                                                size_t count) {
271     auto deviceIt = mDevices.find(eventHubId);
272     if (deviceIt == mDevices.end()) {
273         ALOGW("Discarding event for unknown eventHubId %d.", eventHubId);
274         return;
275     }
276 
277     std::shared_ptr<InputDevice>& device = deviceIt->second;
278     if (device->isIgnored()) {
279         // ALOGD("Discarding event for ignored deviceId %d.", deviceId);
280         return;
281     }
282 
283     device->process(rawEvents, count);
284 }
285 
findInputDevice(int32_t deviceId)286 InputDevice* InputReader::findInputDevice(int32_t deviceId) {
287     auto deviceIt =
288             std::find_if(mDevices.begin(), mDevices.end(), [deviceId](const auto& devicePair) {
289                 return devicePair.second->getId() == deviceId;
290             });
291     if (deviceIt != mDevices.end()) {
292         return deviceIt->second.get();
293     }
294     return nullptr;
295 }
296 
timeoutExpiredLocked(nsecs_t when)297 void InputReader::timeoutExpiredLocked(nsecs_t when) {
298     for (auto& devicePair : mDevices) {
299         std::shared_ptr<InputDevice>& device = devicePair.second;
300         if (!device->isIgnored()) {
301             device->timeoutExpired(when);
302         }
303     }
304 }
305 
nextInputDeviceIdLocked()306 int32_t InputReader::nextInputDeviceIdLocked() {
307     return ++mNextInputDeviceId;
308 }
309 
handleConfigurationChangedLocked(nsecs_t when)310 void InputReader::handleConfigurationChangedLocked(nsecs_t when) {
311     // Reset global meta state because it depends on the list of all configured devices.
312     updateGlobalMetaStateLocked();
313 
314     // Enqueue configuration changed.
315     NotifyConfigurationChangedArgs args(mContext.getNextId(), when);
316     mQueuedListener->notifyConfigurationChanged(&args);
317 }
318 
refreshConfigurationLocked(uint32_t changes)319 void InputReader::refreshConfigurationLocked(uint32_t changes) {
320     mPolicy->getReaderConfiguration(&mConfig);
321     mEventHub->setExcludedDevices(mConfig.excludedDeviceNames);
322 
323     if (changes) {
324         ALOGI("Reconfiguring input devices, changes=%s",
325               InputReaderConfiguration::changesToString(changes).c_str());
326         nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
327 
328         if (changes & InputReaderConfiguration::CHANGE_DISPLAY_INFO) {
329             updatePointerDisplayLocked();
330         }
331 
332         if (changes & InputReaderConfiguration::CHANGE_MUST_REOPEN) {
333             mEventHub->requestReopenDevices();
334         } else {
335             for (auto& devicePair : mDevices) {
336                 std::shared_ptr<InputDevice>& device = devicePair.second;
337                 device->configure(now, &mConfig, changes);
338             }
339         }
340     }
341 }
342 
updateGlobalMetaStateLocked()343 void InputReader::updateGlobalMetaStateLocked() {
344     mGlobalMetaState = 0;
345 
346     for (auto& devicePair : mDevices) {
347         std::shared_ptr<InputDevice>& device = devicePair.second;
348         mGlobalMetaState |= device->getMetaState();
349     }
350 }
351 
getGlobalMetaStateLocked()352 int32_t InputReader::getGlobalMetaStateLocked() {
353     return mGlobalMetaState;
354 }
355 
notifyExternalStylusPresenceChanged()356 void InputReader::notifyExternalStylusPresenceChanged() {
357     refreshConfigurationLocked(InputReaderConfiguration::CHANGE_EXTERNAL_STYLUS_PRESENCE);
358 }
359 
getExternalStylusDevicesLocked(std::vector<InputDeviceInfo> & outDevices)360 void InputReader::getExternalStylusDevicesLocked(std::vector<InputDeviceInfo>& outDevices) {
361     for (auto& devicePair : mDevices) {
362         std::shared_ptr<InputDevice>& device = devicePair.second;
363         if (device->getClasses() & INPUT_DEVICE_CLASS_EXTERNAL_STYLUS && !device->isIgnored()) {
364             InputDeviceInfo info;
365             device->getDeviceInfo(&info);
366             outDevices.push_back(info);
367         }
368     }
369 }
370 
dispatchExternalStylusState(const StylusState & state)371 void InputReader::dispatchExternalStylusState(const StylusState& state) {
372     for (auto& devicePair : mDevices) {
373         std::shared_ptr<InputDevice>& device = devicePair.second;
374         device->updateExternalStylusState(state);
375     }
376 }
377 
disableVirtualKeysUntilLocked(nsecs_t time)378 void InputReader::disableVirtualKeysUntilLocked(nsecs_t time) {
379     mDisableVirtualKeysTimeout = time;
380 }
381 
shouldDropVirtualKeyLocked(nsecs_t now,int32_t keyCode,int32_t scanCode)382 bool InputReader::shouldDropVirtualKeyLocked(nsecs_t now, int32_t keyCode, int32_t scanCode) {
383     if (now < mDisableVirtualKeysTimeout) {
384         ALOGI("Dropping virtual key from device because virtual keys are "
385               "temporarily disabled for the next %0.3fms.  keyCode=%d, scanCode=%d",
386               (mDisableVirtualKeysTimeout - now) * 0.000001, keyCode, scanCode);
387         return true;
388     } else {
389         return false;
390     }
391 }
392 
getPointerControllerLocked(int32_t deviceId)393 sp<PointerControllerInterface> InputReader::getPointerControllerLocked(int32_t deviceId) {
394     sp<PointerControllerInterface> controller = mPointerController.promote();
395     if (controller == nullptr) {
396         controller = mPolicy->obtainPointerController(deviceId);
397         mPointerController = controller;
398         updatePointerDisplayLocked();
399     }
400     return controller;
401 }
402 
updatePointerDisplayLocked()403 void InputReader::updatePointerDisplayLocked() {
404     sp<PointerControllerInterface> controller = mPointerController.promote();
405     if (controller == nullptr) {
406         return;
407     }
408 
409     std::optional<DisplayViewport> viewport =
410             mConfig.getDisplayViewportById(mConfig.defaultPointerDisplayId);
411     if (!viewport) {
412         ALOGW("Can't find the designated viewport with ID %" PRId32 " to update cursor input "
413               "mapper. Fall back to default display",
414               mConfig.defaultPointerDisplayId);
415         viewport = mConfig.getDisplayViewportById(ADISPLAY_ID_DEFAULT);
416     }
417     if (!viewport) {
418         ALOGE("Still can't find a viable viewport to update cursor input mapper. Skip setting it to"
419               " PointerController.");
420         return;
421     }
422 
423     controller->setDisplayViewport(*viewport);
424 }
425 
fadePointerLocked()426 void InputReader::fadePointerLocked() {
427     sp<PointerControllerInterface> controller = mPointerController.promote();
428     if (controller != nullptr) {
429         controller->fade(PointerControllerInterface::TRANSITION_GRADUAL);
430     }
431 }
432 
requestTimeoutAtTimeLocked(nsecs_t when)433 void InputReader::requestTimeoutAtTimeLocked(nsecs_t when) {
434     if (when < mNextTimeout) {
435         mNextTimeout = when;
436         mEventHub->wake();
437     }
438 }
439 
bumpGenerationLocked()440 int32_t InputReader::bumpGenerationLocked() {
441     return ++mGeneration;
442 }
443 
getInputDevices(std::vector<InputDeviceInfo> & outInputDevices)444 void InputReader::getInputDevices(std::vector<InputDeviceInfo>& outInputDevices) {
445     AutoMutex _l(mLock);
446     getInputDevicesLocked(outInputDevices);
447 }
448 
getInputDevicesLocked(std::vector<InputDeviceInfo> & outInputDevices)449 void InputReader::getInputDevicesLocked(std::vector<InputDeviceInfo>& outInputDevices) {
450     outInputDevices.clear();
451 
452     for (auto& devicePair : mDevices) {
453         std::shared_ptr<InputDevice>& device = devicePair.second;
454         if (!device->isIgnored()) {
455             InputDeviceInfo info;
456             device->getDeviceInfo(&info);
457             outInputDevices.push_back(info);
458         }
459     }
460 }
461 
getKeyCodeState(int32_t deviceId,uint32_t sourceMask,int32_t keyCode)462 int32_t InputReader::getKeyCodeState(int32_t deviceId, uint32_t sourceMask, int32_t keyCode) {
463     AutoMutex _l(mLock);
464 
465     return getStateLocked(deviceId, sourceMask, keyCode, &InputDevice::getKeyCodeState);
466 }
467 
getScanCodeState(int32_t deviceId,uint32_t sourceMask,int32_t scanCode)468 int32_t InputReader::getScanCodeState(int32_t deviceId, uint32_t sourceMask, int32_t scanCode) {
469     AutoMutex _l(mLock);
470 
471     return getStateLocked(deviceId, sourceMask, scanCode, &InputDevice::getScanCodeState);
472 }
473 
getSwitchState(int32_t deviceId,uint32_t sourceMask,int32_t switchCode)474 int32_t InputReader::getSwitchState(int32_t deviceId, uint32_t sourceMask, int32_t switchCode) {
475     AutoMutex _l(mLock);
476 
477     return getStateLocked(deviceId, sourceMask, switchCode, &InputDevice::getSwitchState);
478 }
479 
getStateLocked(int32_t deviceId,uint32_t sourceMask,int32_t code,GetStateFunc getStateFunc)480 int32_t InputReader::getStateLocked(int32_t deviceId, uint32_t sourceMask, int32_t code,
481                                     GetStateFunc getStateFunc) {
482     int32_t result = AKEY_STATE_UNKNOWN;
483     if (deviceId >= 0) {
484         InputDevice* device = findInputDevice(deviceId);
485         if (device && !device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
486             result = (device->*getStateFunc)(sourceMask, code);
487         }
488     } else {
489         for (auto& devicePair : mDevices) {
490             std::shared_ptr<InputDevice>& device = devicePair.second;
491             if (!device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
492                 // If any device reports AKEY_STATE_DOWN or AKEY_STATE_VIRTUAL, return that
493                 // value.  Otherwise, return AKEY_STATE_UP as long as one device reports it.
494                 int32_t currentResult = (device.get()->*getStateFunc)(sourceMask, code);
495                 if (currentResult >= AKEY_STATE_DOWN) {
496                     return currentResult;
497                 } else if (currentResult == AKEY_STATE_UP) {
498                     result = currentResult;
499                 }
500             }
501         }
502     }
503     return result;
504 }
505 
toggleCapsLockState(int32_t deviceId)506 void InputReader::toggleCapsLockState(int32_t deviceId) {
507     InputDevice* device = findInputDevice(deviceId);
508     if (!device) {
509         ALOGW("Ignoring toggleCapsLock for unknown deviceId %" PRId32 ".", deviceId);
510         return;
511     }
512 
513     if (device->isIgnored()) {
514         return;
515     }
516 
517     device->updateMetaState(AKEYCODE_CAPS_LOCK);
518 }
519 
hasKeys(int32_t deviceId,uint32_t sourceMask,size_t numCodes,const int32_t * keyCodes,uint8_t * outFlags)520 bool InputReader::hasKeys(int32_t deviceId, uint32_t sourceMask, size_t numCodes,
521                           const int32_t* keyCodes, uint8_t* outFlags) {
522     AutoMutex _l(mLock);
523 
524     memset(outFlags, 0, numCodes);
525     return markSupportedKeyCodesLocked(deviceId, sourceMask, numCodes, keyCodes, outFlags);
526 }
527 
markSupportedKeyCodesLocked(int32_t deviceId,uint32_t sourceMask,size_t numCodes,const int32_t * keyCodes,uint8_t * outFlags)528 bool InputReader::markSupportedKeyCodesLocked(int32_t deviceId, uint32_t sourceMask,
529                                               size_t numCodes, const int32_t* keyCodes,
530                                               uint8_t* outFlags) {
531     bool result = false;
532     if (deviceId >= 0) {
533         InputDevice* device = findInputDevice(deviceId);
534         if (device && !device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
535             result = device->markSupportedKeyCodes(sourceMask, numCodes, keyCodes, outFlags);
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                 result |= device->markSupportedKeyCodes(sourceMask, numCodes, keyCodes, outFlags);
542             }
543         }
544     }
545     return result;
546 }
547 
requestRefreshConfiguration(uint32_t changes)548 void InputReader::requestRefreshConfiguration(uint32_t changes) {
549     AutoMutex _l(mLock);
550 
551     if (changes) {
552         bool needWake = !mConfigurationChangesToRefresh;
553         mConfigurationChangesToRefresh |= changes;
554 
555         if (needWake) {
556             mEventHub->wake();
557         }
558     }
559 }
560 
vibrate(int32_t deviceId,const nsecs_t * pattern,size_t patternSize,ssize_t repeat,int32_t token)561 void InputReader::vibrate(int32_t deviceId, const nsecs_t* pattern, size_t patternSize,
562                           ssize_t repeat, int32_t token) {
563     AutoMutex _l(mLock);
564     InputDevice* device = findInputDevice(deviceId);
565     if (device) {
566         device->vibrate(pattern, patternSize, repeat, token);
567     }
568 }
569 
cancelVibrate(int32_t deviceId,int32_t token)570 void InputReader::cancelVibrate(int32_t deviceId, int32_t token) {
571     AutoMutex _l(mLock);
572 
573     InputDevice* device = findInputDevice(deviceId);
574     if (device) {
575         device->cancelVibrate(token);
576     }
577 }
578 
isInputDeviceEnabled(int32_t deviceId)579 bool InputReader::isInputDeviceEnabled(int32_t deviceId) {
580     AutoMutex _l(mLock);
581 
582     InputDevice* device = findInputDevice(deviceId);
583     if (device) {
584         return device->isEnabled();
585     }
586     ALOGW("Ignoring invalid device id %" PRId32 ".", deviceId);
587     return false;
588 }
589 
canDispatchToDisplay(int32_t deviceId,int32_t displayId)590 bool InputReader::canDispatchToDisplay(int32_t deviceId, int32_t displayId) {
591     AutoMutex _l(mLock);
592 
593     InputDevice* device = findInputDevice(deviceId);
594     if (!device) {
595         ALOGW("Ignoring invalid device id %" PRId32 ".", deviceId);
596         return false;
597     }
598 
599     if (!device->isEnabled()) {
600         ALOGW("Ignoring disabled device %s", device->getName().c_str());
601         return false;
602     }
603 
604     std::optional<int32_t> associatedDisplayId = device->getAssociatedDisplayId();
605     // No associated display. By default, can dispatch to all displays.
606     if (!associatedDisplayId) {
607         return true;
608     }
609 
610     if (*associatedDisplayId == ADISPLAY_ID_NONE) {
611         ALOGW("Device %s is associated with display ADISPLAY_ID_NONE.", device->getName().c_str());
612         return true;
613     }
614 
615     return *associatedDisplayId == displayId;
616 }
617 
dump(std::string & dump)618 void InputReader::dump(std::string& dump) {
619     AutoMutex _l(mLock);
620 
621     mEventHub->dump(dump);
622     dump += "\n";
623 
624     dump += "Input Reader State:\n";
625 
626     for (const auto& devicePair : mDevices) {
627         const std::shared_ptr<InputDevice>& device = devicePair.second;
628         device->dump(dump);
629     }
630 
631     dump += INDENT "Configuration:\n";
632     dump += INDENT2 "ExcludedDeviceNames: [";
633     for (size_t i = 0; i < mConfig.excludedDeviceNames.size(); i++) {
634         if (i != 0) {
635             dump += ", ";
636         }
637         dump += mConfig.excludedDeviceNames[i];
638     }
639     dump += "]\n";
640     dump += StringPrintf(INDENT2 "VirtualKeyQuietTime: %0.1fms\n",
641                          mConfig.virtualKeyQuietTime * 0.000001f);
642 
643     dump += StringPrintf(INDENT2 "PointerVelocityControlParameters: "
644                                  "scale=%0.3f, lowThreshold=%0.3f, highThreshold=%0.3f, "
645                                  "acceleration=%0.3f\n",
646                          mConfig.pointerVelocityControlParameters.scale,
647                          mConfig.pointerVelocityControlParameters.lowThreshold,
648                          mConfig.pointerVelocityControlParameters.highThreshold,
649                          mConfig.pointerVelocityControlParameters.acceleration);
650 
651     dump += StringPrintf(INDENT2 "WheelVelocityControlParameters: "
652                                  "scale=%0.3f, lowThreshold=%0.3f, highThreshold=%0.3f, "
653                                  "acceleration=%0.3f\n",
654                          mConfig.wheelVelocityControlParameters.scale,
655                          mConfig.wheelVelocityControlParameters.lowThreshold,
656                          mConfig.wheelVelocityControlParameters.highThreshold,
657                          mConfig.wheelVelocityControlParameters.acceleration);
658 
659     dump += StringPrintf(INDENT2 "PointerGesture:\n");
660     dump += StringPrintf(INDENT3 "Enabled: %s\n", toString(mConfig.pointerGesturesEnabled));
661     dump += StringPrintf(INDENT3 "QuietInterval: %0.1fms\n",
662                          mConfig.pointerGestureQuietInterval * 0.000001f);
663     dump += StringPrintf(INDENT3 "DragMinSwitchSpeed: %0.1fpx/s\n",
664                          mConfig.pointerGestureDragMinSwitchSpeed);
665     dump += StringPrintf(INDENT3 "TapInterval: %0.1fms\n",
666                          mConfig.pointerGestureTapInterval * 0.000001f);
667     dump += StringPrintf(INDENT3 "TapDragInterval: %0.1fms\n",
668                          mConfig.pointerGestureTapDragInterval * 0.000001f);
669     dump += StringPrintf(INDENT3 "TapSlop: %0.1fpx\n", mConfig.pointerGestureTapSlop);
670     dump += StringPrintf(INDENT3 "MultitouchSettleInterval: %0.1fms\n",
671                          mConfig.pointerGestureMultitouchSettleInterval * 0.000001f);
672     dump += StringPrintf(INDENT3 "MultitouchMinDistance: %0.1fpx\n",
673                          mConfig.pointerGestureMultitouchMinDistance);
674     dump += StringPrintf(INDENT3 "SwipeTransitionAngleCosine: %0.1f\n",
675                          mConfig.pointerGestureSwipeTransitionAngleCosine);
676     dump += StringPrintf(INDENT3 "SwipeMaxWidthRatio: %0.1f\n",
677                          mConfig.pointerGestureSwipeMaxWidthRatio);
678     dump += StringPrintf(INDENT3 "MovementSpeedRatio: %0.1f\n",
679                          mConfig.pointerGestureMovementSpeedRatio);
680     dump += StringPrintf(INDENT3 "ZoomSpeedRatio: %0.1f\n", mConfig.pointerGestureZoomSpeedRatio);
681 
682     dump += INDENT3 "Viewports:\n";
683     mConfig.dump(dump);
684 }
685 
monitor()686 void InputReader::monitor() {
687     // Acquire and release the lock to ensure that the reader has not deadlocked.
688     mLock.lock();
689     mEventHub->wake();
690     mReaderIsAliveCondition.wait(mLock);
691     mLock.unlock();
692 
693     // Check the EventHub
694     mEventHub->monitor();
695 }
696 
697 // --- InputReader::ContextImpl ---
698 
ContextImpl(InputReader * reader)699 InputReader::ContextImpl::ContextImpl(InputReader* reader)
700       : mReader(reader), mIdGenerator(IdGenerator::Source::INPUT_READER) {}
701 
updateGlobalMetaState()702 void InputReader::ContextImpl::updateGlobalMetaState() {
703     // lock is already held by the input loop
704     mReader->updateGlobalMetaStateLocked();
705 }
706 
getGlobalMetaState()707 int32_t InputReader::ContextImpl::getGlobalMetaState() {
708     // lock is already held by the input loop
709     return mReader->getGlobalMetaStateLocked();
710 }
711 
disableVirtualKeysUntil(nsecs_t time)712 void InputReader::ContextImpl::disableVirtualKeysUntil(nsecs_t time) {
713     // lock is already held by the input loop
714     mReader->disableVirtualKeysUntilLocked(time);
715 }
716 
shouldDropVirtualKey(nsecs_t now,int32_t keyCode,int32_t scanCode)717 bool InputReader::ContextImpl::shouldDropVirtualKey(nsecs_t now, int32_t keyCode,
718                                                     int32_t scanCode) {
719     // lock is already held by the input loop
720     return mReader->shouldDropVirtualKeyLocked(now, keyCode, scanCode);
721 }
722 
fadePointer()723 void InputReader::ContextImpl::fadePointer() {
724     // lock is already held by the input loop
725     mReader->fadePointerLocked();
726 }
727 
getPointerController(int32_t deviceId)728 sp<PointerControllerInterface> InputReader::ContextImpl::getPointerController(int32_t deviceId) {
729     // lock is already held by the input loop
730     return mReader->getPointerControllerLocked(deviceId);
731 }
732 
requestTimeoutAtTime(nsecs_t when)733 void InputReader::ContextImpl::requestTimeoutAtTime(nsecs_t when) {
734     // lock is already held by the input loop
735     mReader->requestTimeoutAtTimeLocked(when);
736 }
737 
bumpGeneration()738 int32_t InputReader::ContextImpl::bumpGeneration() {
739     // lock is already held by the input loop
740     return mReader->bumpGenerationLocked();
741 }
742 
getExternalStylusDevices(std::vector<InputDeviceInfo> & outDevices)743 void InputReader::ContextImpl::getExternalStylusDevices(std::vector<InputDeviceInfo>& outDevices) {
744     // lock is already held by whatever called refreshConfigurationLocked
745     mReader->getExternalStylusDevicesLocked(outDevices);
746 }
747 
dispatchExternalStylusState(const StylusState & state)748 void InputReader::ContextImpl::dispatchExternalStylusState(const StylusState& state) {
749     mReader->dispatchExternalStylusState(state);
750 }
751 
getPolicy()752 InputReaderPolicyInterface* InputReader::ContextImpl::getPolicy() {
753     return mReader->mPolicy.get();
754 }
755 
getListener()756 InputListenerInterface* InputReader::ContextImpl::getListener() {
757     return mReader->mQueuedListener.get();
758 }
759 
getEventHub()760 EventHubInterface* InputReader::ContextImpl::getEventHub() {
761     return mReader->mEventHub.get();
762 }
763 
getNextId()764 int32_t InputReader::ContextImpl::getNextId() {
765     return mIdGenerator.nextId();
766 }
767 
768 } // namespace android
769