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 // Add device to device to EventHub ids map.
210 const auto mapIt = mDeviceToEventHubIdsMap.find(device);
211 if (mapIt == mDeviceToEventHubIdsMap.end()) {
212 std::vector<int32_t> ids = {eventHubId};
213 mDeviceToEventHubIdsMap.emplace(device, ids);
214 } else {
215 mapIt->second.push_back(eventHubId);
216 }
217 bumpGenerationLocked();
218
219 if (device->getClasses() & INPUT_DEVICE_CLASS_EXTERNAL_STYLUS) {
220 notifyExternalStylusPresenceChanged();
221 }
222 }
223
removeDeviceLocked(nsecs_t when,int32_t eventHubId)224 void InputReader::removeDeviceLocked(nsecs_t when, int32_t eventHubId) {
225 auto deviceIt = mDevices.find(eventHubId);
226 if (deviceIt == mDevices.end()) {
227 ALOGW("Ignoring spurious device removed event for eventHubId %d.", eventHubId);
228 return;
229 }
230
231 std::shared_ptr<InputDevice> device = std::move(deviceIt->second);
232 mDevices.erase(deviceIt);
233 // Erase device from device to EventHub ids map.
234 auto mapIt = mDeviceToEventHubIdsMap.find(device);
235 if (mapIt != mDeviceToEventHubIdsMap.end()) {
236 std::vector<int32_t>& eventHubIds = mapIt->second;
237 eventHubIds.erase(std::remove_if(eventHubIds.begin(), eventHubIds.end(),
238 [eventHubId](int32_t eId) { return eId == eventHubId; }),
239 eventHubIds.end());
240 if (eventHubIds.size() == 0) {
241 mDeviceToEventHubIdsMap.erase(mapIt);
242 }
243 }
244 bumpGenerationLocked();
245
246 if (device->isIgnored()) {
247 ALOGI("Device removed: id=%d, eventHubId=%d, name='%s', descriptor='%s' "
248 "(ignored non-input device)",
249 device->getId(), eventHubId, device->getName().c_str(),
250 device->getDescriptor().c_str());
251 } else {
252 ALOGI("Device removed: id=%d, eventHubId=%d, name='%s', descriptor='%s', sources=0x%08x",
253 device->getId(), eventHubId, device->getName().c_str(),
254 device->getDescriptor().c_str(), device->getSources());
255 }
256
257 device->removeEventHubDevice(eventHubId);
258
259 if (device->getClasses() & INPUT_DEVICE_CLASS_EXTERNAL_STYLUS) {
260 notifyExternalStylusPresenceChanged();
261 }
262
263 if (device->hasEventHubDevices()) {
264 device->configure(when, &mConfig, 0);
265 }
266 device->reset(when);
267 }
268
createDeviceLocked(int32_t eventHubId,const InputDeviceIdentifier & identifier)269 std::shared_ptr<InputDevice> InputReader::createDeviceLocked(
270 int32_t eventHubId, const InputDeviceIdentifier& identifier) {
271 auto deviceIt = std::find_if(mDevices.begin(), mDevices.end(), [identifier](auto& devicePair) {
272 return devicePair.second->getDescriptor().size() && identifier.descriptor.size() &&
273 devicePair.second->getDescriptor() == identifier.descriptor;
274 });
275
276 std::shared_ptr<InputDevice> device;
277 if (deviceIt != mDevices.end()) {
278 device = deviceIt->second;
279 } else {
280 int32_t deviceId = (eventHubId < END_RESERVED_ID) ? eventHubId : nextInputDeviceIdLocked();
281 device = std::make_shared<InputDevice>(&mContext, deviceId, bumpGenerationLocked(),
282 identifier);
283 }
284 device->addEventHubDevice(eventHubId);
285 return device;
286 }
287
processEventsForDeviceLocked(int32_t eventHubId,const RawEvent * rawEvents,size_t count)288 void InputReader::processEventsForDeviceLocked(int32_t eventHubId, const RawEvent* rawEvents,
289 size_t count) {
290 auto deviceIt = mDevices.find(eventHubId);
291 if (deviceIt == mDevices.end()) {
292 ALOGW("Discarding event for unknown eventHubId %d.", eventHubId);
293 return;
294 }
295
296 std::shared_ptr<InputDevice>& device = deviceIt->second;
297 if (device->isIgnored()) {
298 // ALOGD("Discarding event for ignored deviceId %d.", deviceId);
299 return;
300 }
301
302 device->process(rawEvents, count);
303 }
304
findInputDevice(int32_t deviceId)305 InputDevice* InputReader::findInputDevice(int32_t deviceId) {
306 auto deviceIt =
307 std::find_if(mDevices.begin(), mDevices.end(), [deviceId](const auto& devicePair) {
308 return devicePair.second->getId() == deviceId;
309 });
310 if (deviceIt != mDevices.end()) {
311 return deviceIt->second.get();
312 }
313 return nullptr;
314 }
315
timeoutExpiredLocked(nsecs_t when)316 void InputReader::timeoutExpiredLocked(nsecs_t when) {
317 for (auto& devicePair : mDevices) {
318 std::shared_ptr<InputDevice>& device = devicePair.second;
319 if (!device->isIgnored()) {
320 device->timeoutExpired(when);
321 }
322 }
323 }
324
nextInputDeviceIdLocked()325 int32_t InputReader::nextInputDeviceIdLocked() {
326 return ++mNextInputDeviceId;
327 }
328
handleConfigurationChangedLocked(nsecs_t when)329 void InputReader::handleConfigurationChangedLocked(nsecs_t when) {
330 // Reset global meta state because it depends on the list of all configured devices.
331 updateGlobalMetaStateLocked();
332
333 // Enqueue configuration changed.
334 NotifyConfigurationChangedArgs args(mContext.getNextId(), when);
335 mQueuedListener->notifyConfigurationChanged(&args);
336 }
337
refreshConfigurationLocked(uint32_t changes)338 void InputReader::refreshConfigurationLocked(uint32_t changes) {
339 mPolicy->getReaderConfiguration(&mConfig);
340 mEventHub->setExcludedDevices(mConfig.excludedDeviceNames);
341
342 if (changes) {
343 ALOGI("Reconfiguring input devices, changes=%s",
344 InputReaderConfiguration::changesToString(changes).c_str());
345 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
346
347 if (changes & InputReaderConfiguration::CHANGE_DISPLAY_INFO) {
348 updatePointerDisplayLocked();
349 }
350
351 if (changes & InputReaderConfiguration::CHANGE_MUST_REOPEN) {
352 mEventHub->requestReopenDevices();
353 } else {
354 for (auto& devicePair : mDevices) {
355 std::shared_ptr<InputDevice>& device = devicePair.second;
356 device->configure(now, &mConfig, changes);
357 }
358 }
359 }
360 }
361
updateGlobalMetaStateLocked()362 void InputReader::updateGlobalMetaStateLocked() {
363 mGlobalMetaState = 0;
364
365 for (auto& devicePair : mDevices) {
366 std::shared_ptr<InputDevice>& device = devicePair.second;
367 mGlobalMetaState |= device->getMetaState();
368 }
369 }
370
getGlobalMetaStateLocked()371 int32_t InputReader::getGlobalMetaStateLocked() {
372 return mGlobalMetaState;
373 }
374
notifyExternalStylusPresenceChanged()375 void InputReader::notifyExternalStylusPresenceChanged() {
376 refreshConfigurationLocked(InputReaderConfiguration::CHANGE_EXTERNAL_STYLUS_PRESENCE);
377 }
378
getExternalStylusDevicesLocked(std::vector<InputDeviceInfo> & outDevices)379 void InputReader::getExternalStylusDevicesLocked(std::vector<InputDeviceInfo>& outDevices) {
380 for (auto& devicePair : mDevices) {
381 std::shared_ptr<InputDevice>& device = devicePair.second;
382 if (device->getClasses() & INPUT_DEVICE_CLASS_EXTERNAL_STYLUS && !device->isIgnored()) {
383 InputDeviceInfo info;
384 device->getDeviceInfo(&info);
385 outDevices.push_back(info);
386 }
387 }
388 }
389
dispatchExternalStylusState(const StylusState & state)390 void InputReader::dispatchExternalStylusState(const StylusState& state) {
391 for (auto& devicePair : mDevices) {
392 std::shared_ptr<InputDevice>& device = devicePair.second;
393 device->updateExternalStylusState(state);
394 }
395 }
396
disableVirtualKeysUntilLocked(nsecs_t time)397 void InputReader::disableVirtualKeysUntilLocked(nsecs_t time) {
398 mDisableVirtualKeysTimeout = time;
399 }
400
shouldDropVirtualKeyLocked(nsecs_t now,int32_t keyCode,int32_t scanCode)401 bool InputReader::shouldDropVirtualKeyLocked(nsecs_t now, int32_t keyCode, int32_t scanCode) {
402 if (now < mDisableVirtualKeysTimeout) {
403 ALOGI("Dropping virtual key from device because virtual keys are "
404 "temporarily disabled for the next %0.3fms. keyCode=%d, scanCode=%d",
405 (mDisableVirtualKeysTimeout - now) * 0.000001, keyCode, scanCode);
406 return true;
407 } else {
408 return false;
409 }
410 }
411
getPointerControllerLocked(int32_t deviceId)412 sp<PointerControllerInterface> InputReader::getPointerControllerLocked(int32_t deviceId) {
413 sp<PointerControllerInterface> controller = mPointerController.promote();
414 if (controller == nullptr) {
415 controller = mPolicy->obtainPointerController(deviceId);
416 mPointerController = controller;
417 updatePointerDisplayLocked();
418 }
419 return controller;
420 }
421
updatePointerDisplayLocked()422 void InputReader::updatePointerDisplayLocked() {
423 sp<PointerControllerInterface> controller = mPointerController.promote();
424 if (controller == nullptr) {
425 return;
426 }
427
428 std::optional<DisplayViewport> viewport =
429 mConfig.getDisplayViewportById(mConfig.defaultPointerDisplayId);
430 if (!viewport) {
431 ALOGW("Can't find the designated viewport with ID %" PRId32 " to update cursor input "
432 "mapper. Fall back to default display",
433 mConfig.defaultPointerDisplayId);
434 viewport = mConfig.getDisplayViewportById(ADISPLAY_ID_DEFAULT);
435 }
436 if (!viewport) {
437 ALOGE("Still can't find a viable viewport to update cursor input mapper. Skip setting it to"
438 " PointerController.");
439 return;
440 }
441
442 controller->setDisplayViewport(*viewport);
443 }
444
fadePointerLocked()445 void InputReader::fadePointerLocked() {
446 sp<PointerControllerInterface> controller = mPointerController.promote();
447 if (controller != nullptr) {
448 controller->fade(PointerControllerInterface::TRANSITION_GRADUAL);
449 }
450 }
451
requestTimeoutAtTimeLocked(nsecs_t when)452 void InputReader::requestTimeoutAtTimeLocked(nsecs_t when) {
453 if (when < mNextTimeout) {
454 mNextTimeout = when;
455 mEventHub->wake();
456 }
457 }
458
bumpGenerationLocked()459 int32_t InputReader::bumpGenerationLocked() {
460 return ++mGeneration;
461 }
462
getInputDevices(std::vector<InputDeviceInfo> & outInputDevices)463 void InputReader::getInputDevices(std::vector<InputDeviceInfo>& outInputDevices) {
464 AutoMutex _l(mLock);
465 getInputDevicesLocked(outInputDevices);
466 }
467
getInputDevicesLocked(std::vector<InputDeviceInfo> & outInputDevices)468 void InputReader::getInputDevicesLocked(std::vector<InputDeviceInfo>& outInputDevices) {
469 outInputDevices.clear();
470
471 for (const auto& [device, eventHubIds] : mDeviceToEventHubIdsMap) {
472 if (!device->isIgnored()) {
473 InputDeviceInfo info;
474 device->getDeviceInfo(&info);
475 outInputDevices.push_back(info);
476 }
477 }
478 }
479
getKeyCodeState(int32_t deviceId,uint32_t sourceMask,int32_t keyCode)480 int32_t InputReader::getKeyCodeState(int32_t deviceId, uint32_t sourceMask, int32_t keyCode) {
481 AutoMutex _l(mLock);
482
483 return getStateLocked(deviceId, sourceMask, keyCode, &InputDevice::getKeyCodeState);
484 }
485
getScanCodeState(int32_t deviceId,uint32_t sourceMask,int32_t scanCode)486 int32_t InputReader::getScanCodeState(int32_t deviceId, uint32_t sourceMask, int32_t scanCode) {
487 AutoMutex _l(mLock);
488
489 return getStateLocked(deviceId, sourceMask, scanCode, &InputDevice::getScanCodeState);
490 }
491
getSwitchState(int32_t deviceId,uint32_t sourceMask,int32_t switchCode)492 int32_t InputReader::getSwitchState(int32_t deviceId, uint32_t sourceMask, int32_t switchCode) {
493 AutoMutex _l(mLock);
494
495 return getStateLocked(deviceId, sourceMask, switchCode, &InputDevice::getSwitchState);
496 }
497
getStateLocked(int32_t deviceId,uint32_t sourceMask,int32_t code,GetStateFunc getStateFunc)498 int32_t InputReader::getStateLocked(int32_t deviceId, uint32_t sourceMask, int32_t code,
499 GetStateFunc getStateFunc) {
500 int32_t result = AKEY_STATE_UNKNOWN;
501 if (deviceId >= 0) {
502 InputDevice* device = findInputDevice(deviceId);
503 if (device && !device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
504 result = (device->*getStateFunc)(sourceMask, code);
505 }
506 } else {
507 for (auto& devicePair : mDevices) {
508 std::shared_ptr<InputDevice>& device = devicePair.second;
509 if (!device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
510 // If any device reports AKEY_STATE_DOWN or AKEY_STATE_VIRTUAL, return that
511 // value. Otherwise, return AKEY_STATE_UP as long as one device reports it.
512 int32_t currentResult = (device.get()->*getStateFunc)(sourceMask, code);
513 if (currentResult >= AKEY_STATE_DOWN) {
514 return currentResult;
515 } else if (currentResult == AKEY_STATE_UP) {
516 result = currentResult;
517 }
518 }
519 }
520 }
521 return result;
522 }
523
toggleCapsLockState(int32_t deviceId)524 void InputReader::toggleCapsLockState(int32_t deviceId) {
525 InputDevice* device = findInputDevice(deviceId);
526 if (!device) {
527 ALOGW("Ignoring toggleCapsLock for unknown deviceId %" PRId32 ".", deviceId);
528 return;
529 }
530
531 if (device->isIgnored()) {
532 return;
533 }
534
535 device->updateMetaState(AKEYCODE_CAPS_LOCK);
536 }
537
hasKeys(int32_t deviceId,uint32_t sourceMask,size_t numCodes,const int32_t * keyCodes,uint8_t * outFlags)538 bool InputReader::hasKeys(int32_t deviceId, uint32_t sourceMask, size_t numCodes,
539 const int32_t* keyCodes, uint8_t* outFlags) {
540 AutoMutex _l(mLock);
541
542 memset(outFlags, 0, numCodes);
543 return markSupportedKeyCodesLocked(deviceId, sourceMask, numCodes, keyCodes, outFlags);
544 }
545
markSupportedKeyCodesLocked(int32_t deviceId,uint32_t sourceMask,size_t numCodes,const int32_t * keyCodes,uint8_t * outFlags)546 bool InputReader::markSupportedKeyCodesLocked(int32_t deviceId, uint32_t sourceMask,
547 size_t numCodes, const int32_t* keyCodes,
548 uint8_t* outFlags) {
549 bool result = false;
550 if (deviceId >= 0) {
551 InputDevice* device = findInputDevice(deviceId);
552 if (device && !device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
553 result = device->markSupportedKeyCodes(sourceMask, numCodes, keyCodes, outFlags);
554 }
555 } else {
556 for (auto& devicePair : mDevices) {
557 std::shared_ptr<InputDevice>& device = devicePair.second;
558 if (!device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
559 result |= device->markSupportedKeyCodes(sourceMask, numCodes, keyCodes, outFlags);
560 }
561 }
562 }
563 return result;
564 }
565
requestRefreshConfiguration(uint32_t changes)566 void InputReader::requestRefreshConfiguration(uint32_t changes) {
567 AutoMutex _l(mLock);
568
569 if (changes) {
570 bool needWake = !mConfigurationChangesToRefresh;
571 mConfigurationChangesToRefresh |= changes;
572
573 if (needWake) {
574 mEventHub->wake();
575 }
576 }
577 }
578
vibrate(int32_t deviceId,const nsecs_t * pattern,size_t patternSize,ssize_t repeat,int32_t token)579 void InputReader::vibrate(int32_t deviceId, const nsecs_t* pattern, size_t patternSize,
580 ssize_t repeat, int32_t token) {
581 AutoMutex _l(mLock);
582 InputDevice* device = findInputDevice(deviceId);
583 if (device) {
584 device->vibrate(pattern, patternSize, repeat, token);
585 }
586 }
587
cancelVibrate(int32_t deviceId,int32_t token)588 void InputReader::cancelVibrate(int32_t deviceId, int32_t token) {
589 AutoMutex _l(mLock);
590
591 InputDevice* device = findInputDevice(deviceId);
592 if (device) {
593 device->cancelVibrate(token);
594 }
595 }
596
isInputDeviceEnabled(int32_t deviceId)597 bool InputReader::isInputDeviceEnabled(int32_t deviceId) {
598 AutoMutex _l(mLock);
599
600 InputDevice* device = findInputDevice(deviceId);
601 if (device) {
602 return device->isEnabled();
603 }
604 ALOGW("Ignoring invalid device id %" PRId32 ".", deviceId);
605 return false;
606 }
607
canDispatchToDisplay(int32_t deviceId,int32_t displayId)608 bool InputReader::canDispatchToDisplay(int32_t deviceId, int32_t displayId) {
609 AutoMutex _l(mLock);
610
611 InputDevice* device = findInputDevice(deviceId);
612 if (!device) {
613 ALOGW("Ignoring invalid device id %" PRId32 ".", deviceId);
614 return false;
615 }
616
617 if (!device->isEnabled()) {
618 ALOGW("Ignoring disabled device %s", device->getName().c_str());
619 return false;
620 }
621
622 std::optional<int32_t> associatedDisplayId = device->getAssociatedDisplayId();
623 // No associated display. By default, can dispatch to all displays.
624 if (!associatedDisplayId) {
625 return true;
626 }
627
628 if (*associatedDisplayId == ADISPLAY_ID_NONE) {
629 ALOGW("Device %s is associated with display ADISPLAY_ID_NONE.", device->getName().c_str());
630 return true;
631 }
632
633 return *associatedDisplayId == displayId;
634 }
635
dump(std::string & dump)636 void InputReader::dump(std::string& dump) {
637 AutoMutex _l(mLock);
638
639 mEventHub->dump(dump);
640 dump += "\n";
641
642 dump += StringPrintf("Input Reader State (Nums of device: %zu):\n",
643 mDeviceToEventHubIdsMap.size());
644
645 for (const auto& devicePair : mDeviceToEventHubIdsMap) {
646 const std::shared_ptr<InputDevice>& device = devicePair.first;
647 std::string eventHubDevStr = INDENT "EventHub Devices: [ ";
648 for (const auto& eId : devicePair.second) {
649 eventHubDevStr += StringPrintf("%d ", eId);
650 }
651 eventHubDevStr += "] \n";
652 device->dump(dump, eventHubDevStr);
653 }
654
655 dump += INDENT "Configuration:\n";
656 dump += INDENT2 "ExcludedDeviceNames: [";
657 for (size_t i = 0; i < mConfig.excludedDeviceNames.size(); i++) {
658 if (i != 0) {
659 dump += ", ";
660 }
661 dump += mConfig.excludedDeviceNames[i];
662 }
663 dump += "]\n";
664 dump += StringPrintf(INDENT2 "VirtualKeyQuietTime: %0.1fms\n",
665 mConfig.virtualKeyQuietTime * 0.000001f);
666
667 dump += StringPrintf(INDENT2 "PointerVelocityControlParameters: "
668 "scale=%0.3f, lowThreshold=%0.3f, highThreshold=%0.3f, "
669 "acceleration=%0.3f\n",
670 mConfig.pointerVelocityControlParameters.scale,
671 mConfig.pointerVelocityControlParameters.lowThreshold,
672 mConfig.pointerVelocityControlParameters.highThreshold,
673 mConfig.pointerVelocityControlParameters.acceleration);
674
675 dump += StringPrintf(INDENT2 "WheelVelocityControlParameters: "
676 "scale=%0.3f, lowThreshold=%0.3f, highThreshold=%0.3f, "
677 "acceleration=%0.3f\n",
678 mConfig.wheelVelocityControlParameters.scale,
679 mConfig.wheelVelocityControlParameters.lowThreshold,
680 mConfig.wheelVelocityControlParameters.highThreshold,
681 mConfig.wheelVelocityControlParameters.acceleration);
682
683 dump += StringPrintf(INDENT2 "PointerGesture:\n");
684 dump += StringPrintf(INDENT3 "Enabled: %s\n", toString(mConfig.pointerGesturesEnabled));
685 dump += StringPrintf(INDENT3 "QuietInterval: %0.1fms\n",
686 mConfig.pointerGestureQuietInterval * 0.000001f);
687 dump += StringPrintf(INDENT3 "DragMinSwitchSpeed: %0.1fpx/s\n",
688 mConfig.pointerGestureDragMinSwitchSpeed);
689 dump += StringPrintf(INDENT3 "TapInterval: %0.1fms\n",
690 mConfig.pointerGestureTapInterval * 0.000001f);
691 dump += StringPrintf(INDENT3 "TapDragInterval: %0.1fms\n",
692 mConfig.pointerGestureTapDragInterval * 0.000001f);
693 dump += StringPrintf(INDENT3 "TapSlop: %0.1fpx\n", mConfig.pointerGestureTapSlop);
694 dump += StringPrintf(INDENT3 "MultitouchSettleInterval: %0.1fms\n",
695 mConfig.pointerGestureMultitouchSettleInterval * 0.000001f);
696 dump += StringPrintf(INDENT3 "MultitouchMinDistance: %0.1fpx\n",
697 mConfig.pointerGestureMultitouchMinDistance);
698 dump += StringPrintf(INDENT3 "SwipeTransitionAngleCosine: %0.1f\n",
699 mConfig.pointerGestureSwipeTransitionAngleCosine);
700 dump += StringPrintf(INDENT3 "SwipeMaxWidthRatio: %0.1f\n",
701 mConfig.pointerGestureSwipeMaxWidthRatio);
702 dump += StringPrintf(INDENT3 "MovementSpeedRatio: %0.1f\n",
703 mConfig.pointerGestureMovementSpeedRatio);
704 dump += StringPrintf(INDENT3 "ZoomSpeedRatio: %0.1f\n", mConfig.pointerGestureZoomSpeedRatio);
705
706 dump += INDENT3 "Viewports:\n";
707 mConfig.dump(dump);
708 }
709
monitor()710 void InputReader::monitor() {
711 // Acquire and release the lock to ensure that the reader has not deadlocked.
712 mLock.lock();
713 mEventHub->wake();
714 mReaderIsAliveCondition.wait(mLock);
715 mLock.unlock();
716
717 // Check the EventHub
718 mEventHub->monitor();
719 }
720
721 // --- InputReader::ContextImpl ---
722
ContextImpl(InputReader * reader)723 InputReader::ContextImpl::ContextImpl(InputReader* reader)
724 : mReader(reader), mIdGenerator(IdGenerator::Source::INPUT_READER) {}
725
updateGlobalMetaState()726 void InputReader::ContextImpl::updateGlobalMetaState() {
727 // lock is already held by the input loop
728 mReader->updateGlobalMetaStateLocked();
729 }
730
getGlobalMetaState()731 int32_t InputReader::ContextImpl::getGlobalMetaState() {
732 // lock is already held by the input loop
733 return mReader->getGlobalMetaStateLocked();
734 }
735
disableVirtualKeysUntil(nsecs_t time)736 void InputReader::ContextImpl::disableVirtualKeysUntil(nsecs_t time) {
737 // lock is already held by the input loop
738 mReader->disableVirtualKeysUntilLocked(time);
739 }
740
shouldDropVirtualKey(nsecs_t now,int32_t keyCode,int32_t scanCode)741 bool InputReader::ContextImpl::shouldDropVirtualKey(nsecs_t now, int32_t keyCode,
742 int32_t scanCode) {
743 // lock is already held by the input loop
744 return mReader->shouldDropVirtualKeyLocked(now, keyCode, scanCode);
745 }
746
fadePointer()747 void InputReader::ContextImpl::fadePointer() {
748 // lock is already held by the input loop
749 mReader->fadePointerLocked();
750 }
751
getPointerController(int32_t deviceId)752 sp<PointerControllerInterface> InputReader::ContextImpl::getPointerController(int32_t deviceId) {
753 // lock is already held by the input loop
754 return mReader->getPointerControllerLocked(deviceId);
755 }
756
requestTimeoutAtTime(nsecs_t when)757 void InputReader::ContextImpl::requestTimeoutAtTime(nsecs_t when) {
758 // lock is already held by the input loop
759 mReader->requestTimeoutAtTimeLocked(when);
760 }
761
bumpGeneration()762 int32_t InputReader::ContextImpl::bumpGeneration() {
763 // lock is already held by the input loop
764 return mReader->bumpGenerationLocked();
765 }
766
getExternalStylusDevices(std::vector<InputDeviceInfo> & outDevices)767 void InputReader::ContextImpl::getExternalStylusDevices(std::vector<InputDeviceInfo>& outDevices) {
768 // lock is already held by whatever called refreshConfigurationLocked
769 mReader->getExternalStylusDevicesLocked(outDevices);
770 }
771
dispatchExternalStylusState(const StylusState & state)772 void InputReader::ContextImpl::dispatchExternalStylusState(const StylusState& state) {
773 mReader->dispatchExternalStylusState(state);
774 }
775
getPolicy()776 InputReaderPolicyInterface* InputReader::ContextImpl::getPolicy() {
777 return mReader->mPolicy.get();
778 }
779
getListener()780 InputListenerInterface* InputReader::ContextImpl::getListener() {
781 return mReader->mQueuedListener.get();
782 }
783
getEventHub()784 EventHubInterface* InputReader::ContextImpl::getEventHub() {
785 return mReader->mEventHub.get();
786 }
787
getNextId()788 int32_t InputReader::ContextImpl::getNextId() {
789 return mIdGenerator.nextId();
790 }
791
792 } // namespace android
793