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