1 /*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #include "Macros.h"
18
19 #include "InputReader.h"
20
21 #include <android-base/stringprintf.h>
22 #include <errno.h>
23 #include <input/Keyboard.h>
24 #include <input/VirtualKeyMap.h>
25 #include <inttypes.h>
26 #include <limits.h>
27 #include <log/log.h>
28 #include <math.h>
29 #include <stddef.h>
30 #include <stdlib.h>
31 #include <unistd.h>
32 #include <utils/Errors.h>
33 #include <utils/Thread.h>
34
35 #include "InputDevice.h"
36
37 using android::base::StringPrintf;
38
39 namespace android {
40
41 // --- InputReader ---
42
InputReader(std::shared_ptr<EventHubInterface> eventHub,const sp<InputReaderPolicyInterface> & policy,const sp<InputListenerInterface> & listener)43 InputReader::InputReader(std::shared_ptr<EventHubInterface> eventHub,
44 const sp<InputReaderPolicyInterface>& policy,
45 const sp<InputListenerInterface>& listener)
46 : mContext(this),
47 mEventHub(eventHub),
48 mPolicy(policy),
49 mGlobalMetaState(0),
50 mLedMetaState(AMETA_NUM_LOCK_ON),
51 mGeneration(1),
52 mNextInputDeviceId(END_RESERVED_ID),
53 mDisableVirtualKeysTimeout(LLONG_MIN),
54 mNextTimeout(LLONG_MAX),
55 mConfigurationChangesToRefresh(0) {
56 mQueuedListener = new QueuedInputListener(listener);
57
58 { // acquire lock
59 std::scoped_lock _l(mLock);
60
61 refreshConfigurationLocked(0);
62 updateGlobalMetaStateLocked();
63 } // release lock
64 }
65
~InputReader()66 InputReader::~InputReader() {}
67
start()68 status_t InputReader::start() {
69 if (mThread) {
70 return ALREADY_EXISTS;
71 }
72 mThread = std::make_unique<InputThread>(
73 "InputReader", [this]() { loopOnce(); }, [this]() { mEventHub->wake(); });
74 return OK;
75 }
76
stop()77 status_t InputReader::stop() {
78 if (mThread && mThread->isCallingThread()) {
79 ALOGE("InputReader cannot be stopped from its own thread!");
80 return INVALID_OPERATION;
81 }
82 mThread.reset();
83 return OK;
84 }
85
loopOnce()86 void InputReader::loopOnce() {
87 int32_t oldGeneration;
88 int32_t timeoutMillis;
89 bool inputDevicesChanged = false;
90 std::vector<InputDeviceInfo> inputDevices;
91 { // acquire lock
92 std::scoped_lock _l(mLock);
93
94 oldGeneration = mGeneration;
95 timeoutMillis = -1;
96
97 uint32_t changes = mConfigurationChangesToRefresh;
98 if (changes) {
99 mConfigurationChangesToRefresh = 0;
100 timeoutMillis = 0;
101 refreshConfigurationLocked(changes);
102 } else if (mNextTimeout != LLONG_MAX) {
103 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
104 timeoutMillis = toMillisecondTimeoutDelay(now, mNextTimeout);
105 }
106 } // release lock
107
108 size_t count = mEventHub->getEvents(timeoutMillis, mEventBuffer, EVENT_BUFFER_SIZE);
109
110 { // acquire lock
111 std::scoped_lock _l(mLock);
112 mReaderIsAliveCondition.notify_all();
113
114 if (count) {
115 processEventsLocked(mEventBuffer, count);
116 }
117
118 if (mNextTimeout != LLONG_MAX) {
119 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
120 if (now >= mNextTimeout) {
121 #if DEBUG_RAW_EVENTS
122 ALOGD("Timeout expired, latency=%0.3fms", (now - mNextTimeout) * 0.000001f);
123 #endif
124 mNextTimeout = LLONG_MAX;
125 timeoutExpiredLocked(now);
126 }
127 }
128
129 if (oldGeneration != mGeneration) {
130 inputDevicesChanged = true;
131 inputDevices = getInputDevicesLocked();
132 }
133 } // release lock
134
135 // Send out a message that the describes the changed input devices.
136 if (inputDevicesChanged) {
137 mPolicy->notifyInputDevicesChanged(inputDevices);
138 }
139
140 // Flush queued events out to the listener.
141 // This must happen outside of the lock because the listener could potentially call
142 // back into the InputReader's methods, such as getScanCodeState, or become blocked
143 // on another thread similarly waiting to acquire the InputReader lock thereby
144 // resulting in a deadlock. This situation is actually quite plausible because the
145 // listener is actually the input dispatcher, which calls into the window manager,
146 // which occasionally calls into the input reader.
147 mQueuedListener->flush();
148 }
149
processEventsLocked(const RawEvent * rawEvents,size_t count)150 void InputReader::processEventsLocked(const RawEvent* rawEvents, size_t count) {
151 for (const RawEvent* rawEvent = rawEvents; count;) {
152 int32_t type = rawEvent->type;
153 size_t batchSize = 1;
154 if (type < EventHubInterface::FIRST_SYNTHETIC_EVENT) {
155 int32_t deviceId = rawEvent->deviceId;
156 while (batchSize < count) {
157 if (rawEvent[batchSize].type >= EventHubInterface::FIRST_SYNTHETIC_EVENT ||
158 rawEvent[batchSize].deviceId != deviceId) {
159 break;
160 }
161 batchSize += 1;
162 }
163 #if DEBUG_RAW_EVENTS
164 ALOGD("BatchSize: %zu Count: %zu", batchSize, count);
165 #endif
166 processEventsForDeviceLocked(deviceId, rawEvent, batchSize);
167 } else {
168 switch (rawEvent->type) {
169 case EventHubInterface::DEVICE_ADDED:
170 addDeviceLocked(rawEvent->when, rawEvent->deviceId);
171 break;
172 case EventHubInterface::DEVICE_REMOVED:
173 removeDeviceLocked(rawEvent->when, rawEvent->deviceId);
174 break;
175 case EventHubInterface::FINISHED_DEVICE_SCAN:
176 handleConfigurationChangedLocked(rawEvent->when);
177 break;
178 default:
179 ALOG_ASSERT(false); // can't happen
180 break;
181 }
182 }
183 count -= batchSize;
184 rawEvent += batchSize;
185 }
186 }
187
addDeviceLocked(nsecs_t when,int32_t eventHubId)188 void InputReader::addDeviceLocked(nsecs_t when, int32_t eventHubId) {
189 if (mDevices.find(eventHubId) != mDevices.end()) {
190 ALOGW("Ignoring spurious device added event for eventHubId %d.", eventHubId);
191 return;
192 }
193
194 InputDeviceIdentifier identifier = mEventHub->getDeviceIdentifier(eventHubId);
195 std::shared_ptr<InputDevice> device = createDeviceLocked(eventHubId, identifier);
196 device->configure(when, &mConfig, 0);
197 device->reset(when);
198
199 if (device->isIgnored()) {
200 ALOGI("Device added: id=%d, eventHubId=%d, name='%s', descriptor='%s' "
201 "(ignored non-input device)",
202 device->getId(), eventHubId, identifier.name.c_str(), identifier.descriptor.c_str());
203 } else {
204 ALOGI("Device added: id=%d, eventHubId=%d, name='%s', descriptor='%s',sources=0x%08x",
205 device->getId(), eventHubId, identifier.name.c_str(), identifier.descriptor.c_str(),
206 device->getSources());
207 }
208
209 mDevices.emplace(eventHubId, device);
210 // Add device to device to EventHub ids map.
211 const auto mapIt = mDeviceToEventHubIdsMap.find(device);
212 if (mapIt == mDeviceToEventHubIdsMap.end()) {
213 std::vector<int32_t> ids = {eventHubId};
214 mDeviceToEventHubIdsMap.emplace(device, ids);
215 } else {
216 mapIt->second.push_back(eventHubId);
217 }
218 bumpGenerationLocked();
219
220 if (device->getClasses().test(InputDeviceClass::EXTERNAL_STYLUS)) {
221 notifyExternalStylusPresenceChangedLocked();
222 }
223
224 // Sensor input device is noisy, to save power disable it by default.
225 // Input device is classified as SENSOR when any sub device is a SENSOR device, check Eventhub
226 // device class to disable SENSOR sub device only.
227 if (mEventHub->getDeviceClasses(eventHubId).test(InputDeviceClass::SENSOR)) {
228 mEventHub->disableDevice(eventHubId);
229 }
230 }
231
removeDeviceLocked(nsecs_t when,int32_t eventHubId)232 void InputReader::removeDeviceLocked(nsecs_t when, int32_t eventHubId) {
233 auto deviceIt = mDevices.find(eventHubId);
234 if (deviceIt == mDevices.end()) {
235 ALOGW("Ignoring spurious device removed event for eventHubId %d.", eventHubId);
236 return;
237 }
238
239 std::shared_ptr<InputDevice> device = std::move(deviceIt->second);
240 mDevices.erase(deviceIt);
241 // Erase device from device to EventHub ids map.
242 auto mapIt = mDeviceToEventHubIdsMap.find(device);
243 if (mapIt != mDeviceToEventHubIdsMap.end()) {
244 std::vector<int32_t>& eventHubIds = mapIt->second;
245 eventHubIds.erase(std::remove_if(eventHubIds.begin(), eventHubIds.end(),
246 [eventHubId](int32_t eId) { return eId == eventHubId; }),
247 eventHubIds.end());
248 if (eventHubIds.size() == 0) {
249 mDeviceToEventHubIdsMap.erase(mapIt);
250 }
251 }
252 bumpGenerationLocked();
253
254 if (device->isIgnored()) {
255 ALOGI("Device removed: id=%d, eventHubId=%d, name='%s', descriptor='%s' "
256 "(ignored non-input device)",
257 device->getId(), eventHubId, device->getName().c_str(),
258 device->getDescriptor().c_str());
259 } else {
260 ALOGI("Device removed: id=%d, eventHubId=%d, name='%s', descriptor='%s', sources=0x%08x",
261 device->getId(), eventHubId, device->getName().c_str(),
262 device->getDescriptor().c_str(), device->getSources());
263 }
264
265 device->removeEventHubDevice(eventHubId);
266
267 if (device->getClasses().test(InputDeviceClass::EXTERNAL_STYLUS)) {
268 notifyExternalStylusPresenceChangedLocked();
269 }
270
271 if (device->hasEventHubDevices()) {
272 device->configure(when, &mConfig, 0);
273 }
274 device->reset(when);
275 }
276
createDeviceLocked(int32_t eventHubId,const InputDeviceIdentifier & identifier)277 std::shared_ptr<InputDevice> InputReader::createDeviceLocked(
278 int32_t eventHubId, const InputDeviceIdentifier& identifier) {
279 auto deviceIt = std::find_if(mDevices.begin(), mDevices.end(), [identifier](auto& devicePair) {
280 return devicePair.second->getDescriptor().size() && identifier.descriptor.size() &&
281 devicePair.second->getDescriptor() == identifier.descriptor;
282 });
283
284 std::shared_ptr<InputDevice> device;
285 if (deviceIt != mDevices.end()) {
286 device = deviceIt->second;
287 } else {
288 int32_t deviceId = (eventHubId < END_RESERVED_ID) ? eventHubId : nextInputDeviceIdLocked();
289 device = std::make_shared<InputDevice>(&mContext, deviceId, bumpGenerationLocked(),
290 identifier);
291 }
292 device->addEventHubDevice(eventHubId);
293 return device;
294 }
295
processEventsForDeviceLocked(int32_t eventHubId,const RawEvent * rawEvents,size_t count)296 void InputReader::processEventsForDeviceLocked(int32_t eventHubId, const RawEvent* rawEvents,
297 size_t count) {
298 auto deviceIt = mDevices.find(eventHubId);
299 if (deviceIt == mDevices.end()) {
300 ALOGW("Discarding event for unknown eventHubId %d.", eventHubId);
301 return;
302 }
303
304 std::shared_ptr<InputDevice>& device = deviceIt->second;
305 if (device->isIgnored()) {
306 // ALOGD("Discarding event for ignored deviceId %d.", deviceId);
307 return;
308 }
309
310 device->process(rawEvents, count);
311 }
312
findInputDeviceLocked(int32_t deviceId)313 InputDevice* InputReader::findInputDeviceLocked(int32_t deviceId) {
314 auto deviceIt =
315 std::find_if(mDevices.begin(), mDevices.end(), [deviceId](const auto& devicePair) {
316 return devicePair.second->getId() == deviceId;
317 });
318 if (deviceIt != mDevices.end()) {
319 return deviceIt->second.get();
320 }
321 return nullptr;
322 }
323
timeoutExpiredLocked(nsecs_t when)324 void InputReader::timeoutExpiredLocked(nsecs_t when) {
325 for (auto& devicePair : mDevices) {
326 std::shared_ptr<InputDevice>& device = devicePair.second;
327 if (!device->isIgnored()) {
328 device->timeoutExpired(when);
329 }
330 }
331 }
332
nextInputDeviceIdLocked()333 int32_t InputReader::nextInputDeviceIdLocked() {
334 return ++mNextInputDeviceId;
335 }
336
handleConfigurationChangedLocked(nsecs_t when)337 void InputReader::handleConfigurationChangedLocked(nsecs_t when) {
338 // Reset global meta state because it depends on the list of all configured devices.
339 updateGlobalMetaStateLocked();
340
341 // Enqueue configuration changed.
342 NotifyConfigurationChangedArgs args(mContext.getNextId(), when);
343 mQueuedListener->notifyConfigurationChanged(&args);
344 }
345
refreshConfigurationLocked(uint32_t changes)346 void InputReader::refreshConfigurationLocked(uint32_t changes) {
347 mPolicy->getReaderConfiguration(&mConfig);
348 mEventHub->setExcludedDevices(mConfig.excludedDeviceNames);
349
350 if (!changes) return;
351
352 ALOGI("Reconfiguring input devices, changes=%s",
353 InputReaderConfiguration::changesToString(changes).c_str());
354 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
355
356 if (changes & InputReaderConfiguration::CHANGE_DISPLAY_INFO) {
357 updatePointerDisplayLocked();
358 }
359
360 if (changes & InputReaderConfiguration::CHANGE_MUST_REOPEN) {
361 mEventHub->requestReopenDevices();
362 } else {
363 for (auto& devicePair : mDevices) {
364 std::shared_ptr<InputDevice>& device = devicePair.second;
365 device->configure(now, &mConfig, changes);
366 }
367 }
368
369 if (changes & InputReaderConfiguration::CHANGE_POINTER_CAPTURE) {
370 const NotifyPointerCaptureChangedArgs args(mContext.getNextId(), now,
371 mConfig.pointerCapture);
372 mQueuedListener->notifyPointerCaptureChanged(&args);
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 return;
559 }
560
561 device->updateMetaState(AKEYCODE_CAPS_LOCK);
562 }
563
hasKeys(int32_t deviceId,uint32_t sourceMask,size_t numCodes,const int32_t * keyCodes,uint8_t * outFlags)564 bool InputReader::hasKeys(int32_t deviceId, uint32_t sourceMask, size_t numCodes,
565 const int32_t* keyCodes, uint8_t* outFlags) {
566 std::scoped_lock _l(mLock);
567
568 memset(outFlags, 0, numCodes);
569 return markSupportedKeyCodesLocked(deviceId, sourceMask, numCodes, keyCodes, outFlags);
570 }
571
markSupportedKeyCodesLocked(int32_t deviceId,uint32_t sourceMask,size_t numCodes,const int32_t * keyCodes,uint8_t * outFlags)572 bool InputReader::markSupportedKeyCodesLocked(int32_t deviceId, uint32_t sourceMask,
573 size_t numCodes, const int32_t* keyCodes,
574 uint8_t* outFlags) {
575 bool result = false;
576 if (deviceId >= 0) {
577 InputDevice* device = findInputDeviceLocked(deviceId);
578 if (device && !device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
579 result = device->markSupportedKeyCodes(sourceMask, numCodes, keyCodes, outFlags);
580 }
581 } else {
582 for (auto& devicePair : mDevices) {
583 std::shared_ptr<InputDevice>& device = devicePair.second;
584 if (!device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
585 result |= device->markSupportedKeyCodes(sourceMask, numCodes, keyCodes, outFlags);
586 }
587 }
588 }
589 return result;
590 }
591
requestRefreshConfiguration(uint32_t changes)592 void InputReader::requestRefreshConfiguration(uint32_t changes) {
593 std::scoped_lock _l(mLock);
594
595 if (changes) {
596 bool needWake = !mConfigurationChangesToRefresh;
597 mConfigurationChangesToRefresh |= changes;
598
599 if (needWake) {
600 mEventHub->wake();
601 }
602 }
603 }
604
vibrate(int32_t deviceId,const VibrationSequence & sequence,ssize_t repeat,int32_t token)605 void InputReader::vibrate(int32_t deviceId, const VibrationSequence& sequence, ssize_t repeat,
606 int32_t token) {
607 std::scoped_lock _l(mLock);
608
609 InputDevice* device = findInputDeviceLocked(deviceId);
610 if (device) {
611 device->vibrate(sequence, repeat, token);
612 }
613 }
614
cancelVibrate(int32_t deviceId,int32_t token)615 void InputReader::cancelVibrate(int32_t deviceId, int32_t token) {
616 std::scoped_lock _l(mLock);
617
618 InputDevice* device = findInputDeviceLocked(deviceId);
619 if (device) {
620 device->cancelVibrate(token);
621 }
622 }
623
isVibrating(int32_t deviceId)624 bool InputReader::isVibrating(int32_t deviceId) {
625 std::scoped_lock _l(mLock);
626
627 InputDevice* device = findInputDeviceLocked(deviceId);
628 if (device) {
629 return device->isVibrating();
630 }
631 return false;
632 }
633
getVibratorIds(int32_t deviceId)634 std::vector<int32_t> InputReader::getVibratorIds(int32_t deviceId) {
635 std::scoped_lock _l(mLock);
636
637 InputDevice* device = findInputDeviceLocked(deviceId);
638 if (device) {
639 return device->getVibratorIds();
640 }
641 return {};
642 }
643
disableSensor(int32_t deviceId,InputDeviceSensorType sensorType)644 void InputReader::disableSensor(int32_t deviceId, InputDeviceSensorType sensorType) {
645 std::scoped_lock _l(mLock);
646
647 InputDevice* device = findInputDeviceLocked(deviceId);
648 if (device) {
649 device->disableSensor(sensorType);
650 }
651 }
652
enableSensor(int32_t deviceId,InputDeviceSensorType sensorType,std::chrono::microseconds samplingPeriod,std::chrono::microseconds maxBatchReportLatency)653 bool InputReader::enableSensor(int32_t deviceId, InputDeviceSensorType sensorType,
654 std::chrono::microseconds samplingPeriod,
655 std::chrono::microseconds maxBatchReportLatency) {
656 std::scoped_lock _l(mLock);
657
658 InputDevice* device = findInputDeviceLocked(deviceId);
659 if (device) {
660 return device->enableSensor(sensorType, samplingPeriod, maxBatchReportLatency);
661 }
662 return false;
663 }
664
flushSensor(int32_t deviceId,InputDeviceSensorType sensorType)665 void InputReader::flushSensor(int32_t deviceId, InputDeviceSensorType sensorType) {
666 std::scoped_lock _l(mLock);
667
668 InputDevice* device = findInputDeviceLocked(deviceId);
669 if (device) {
670 device->flushSensor(sensorType);
671 }
672 }
673
getBatteryCapacity(int32_t deviceId)674 std::optional<int32_t> InputReader::getBatteryCapacity(int32_t deviceId) {
675 std::scoped_lock _l(mLock);
676
677 InputDevice* device = findInputDeviceLocked(deviceId);
678 if (device) {
679 return device->getBatteryCapacity();
680 }
681 return std::nullopt;
682 }
683
getBatteryStatus(int32_t deviceId)684 std::optional<int32_t> InputReader::getBatteryStatus(int32_t deviceId) {
685 std::scoped_lock _l(mLock);
686
687 InputDevice* device = findInputDeviceLocked(deviceId);
688 if (device) {
689 return device->getBatteryStatus();
690 }
691 return std::nullopt;
692 }
693
getLights(int32_t deviceId)694 std::vector<InputDeviceLightInfo> InputReader::getLights(int32_t deviceId) {
695 std::scoped_lock _l(mLock);
696
697 InputDevice* device = findInputDeviceLocked(deviceId);
698 if (device == nullptr) {
699 return {};
700 }
701
702 return device->getDeviceInfo().getLights();
703 }
704
getSensors(int32_t deviceId)705 std::vector<InputDeviceSensorInfo> InputReader::getSensors(int32_t deviceId) {
706 std::scoped_lock _l(mLock);
707
708 InputDevice* device = findInputDeviceLocked(deviceId);
709 if (device == nullptr) {
710 return {};
711 }
712
713 return device->getDeviceInfo().getSensors();
714 }
715
setLightColor(int32_t deviceId,int32_t lightId,int32_t color)716 bool InputReader::setLightColor(int32_t deviceId, int32_t lightId, int32_t color) {
717 std::scoped_lock _l(mLock);
718
719 InputDevice* device = findInputDeviceLocked(deviceId);
720 if (device) {
721 return device->setLightColor(lightId, color);
722 }
723 return false;
724 }
725
setLightPlayerId(int32_t deviceId,int32_t lightId,int32_t playerId)726 bool InputReader::setLightPlayerId(int32_t deviceId, int32_t lightId, int32_t playerId) {
727 std::scoped_lock _l(mLock);
728
729 InputDevice* device = findInputDeviceLocked(deviceId);
730 if (device) {
731 return device->setLightPlayerId(lightId, playerId);
732 }
733 return false;
734 }
735
getLightColor(int32_t deviceId,int32_t lightId)736 std::optional<int32_t> InputReader::getLightColor(int32_t deviceId, int32_t lightId) {
737 std::scoped_lock _l(mLock);
738
739 InputDevice* device = findInputDeviceLocked(deviceId);
740 if (device) {
741 return device->getLightColor(lightId);
742 }
743 return std::nullopt;
744 }
745
getLightPlayerId(int32_t deviceId,int32_t lightId)746 std::optional<int32_t> InputReader::getLightPlayerId(int32_t deviceId, int32_t lightId) {
747 std::scoped_lock _l(mLock);
748
749 InputDevice* device = findInputDeviceLocked(deviceId);
750 if (device) {
751 return device->getLightPlayerId(lightId);
752 }
753 return std::nullopt;
754 }
755
isInputDeviceEnabled(int32_t deviceId)756 bool InputReader::isInputDeviceEnabled(int32_t deviceId) {
757 std::scoped_lock _l(mLock);
758
759 InputDevice* device = findInputDeviceLocked(deviceId);
760 if (device) {
761 return device->isEnabled();
762 }
763 ALOGW("Ignoring invalid device id %" PRId32 ".", deviceId);
764 return false;
765 }
766
canDispatchToDisplay(int32_t deviceId,int32_t displayId)767 bool InputReader::canDispatchToDisplay(int32_t deviceId, int32_t displayId) {
768 std::scoped_lock _l(mLock);
769
770 InputDevice* device = findInputDeviceLocked(deviceId);
771 if (!device) {
772 ALOGW("Ignoring invalid device id %" PRId32 ".", deviceId);
773 return false;
774 }
775
776 if (!device->isEnabled()) {
777 ALOGW("Ignoring disabled device %s", device->getName().c_str());
778 return false;
779 }
780
781 std::optional<int32_t> associatedDisplayId = device->getAssociatedDisplayId();
782 // No associated display. By default, can dispatch to all displays.
783 if (!associatedDisplayId) {
784 return true;
785 }
786
787 if (*associatedDisplayId == ADISPLAY_ID_NONE) {
788 ALOGW("Device %s is associated with display ADISPLAY_ID_NONE.", device->getName().c_str());
789 return true;
790 }
791
792 return *associatedDisplayId == displayId;
793 }
794
dump(std::string & dump)795 void InputReader::dump(std::string& dump) {
796 std::scoped_lock _l(mLock);
797
798 mEventHub->dump(dump);
799 dump += "\n";
800
801 dump += StringPrintf("Input Reader State (Nums of device: %zu):\n",
802 mDeviceToEventHubIdsMap.size());
803
804 for (const auto& devicePair : mDeviceToEventHubIdsMap) {
805 const std::shared_ptr<InputDevice>& device = devicePair.first;
806 std::string eventHubDevStr = INDENT "EventHub Devices: [ ";
807 for (const auto& eId : devicePair.second) {
808 eventHubDevStr += StringPrintf("%d ", eId);
809 }
810 eventHubDevStr += "] \n";
811 device->dump(dump, eventHubDevStr);
812 }
813
814 dump += INDENT "Configuration:\n";
815 dump += INDENT2 "ExcludedDeviceNames: [";
816 for (size_t i = 0; i < mConfig.excludedDeviceNames.size(); i++) {
817 if (i != 0) {
818 dump += ", ";
819 }
820 dump += mConfig.excludedDeviceNames[i];
821 }
822 dump += "]\n";
823 dump += StringPrintf(INDENT2 "VirtualKeyQuietTime: %0.1fms\n",
824 mConfig.virtualKeyQuietTime * 0.000001f);
825
826 dump += StringPrintf(INDENT2 "PointerVelocityControlParameters: "
827 "scale=%0.3f, lowThreshold=%0.3f, highThreshold=%0.3f, "
828 "acceleration=%0.3f\n",
829 mConfig.pointerVelocityControlParameters.scale,
830 mConfig.pointerVelocityControlParameters.lowThreshold,
831 mConfig.pointerVelocityControlParameters.highThreshold,
832 mConfig.pointerVelocityControlParameters.acceleration);
833
834 dump += StringPrintf(INDENT2 "WheelVelocityControlParameters: "
835 "scale=%0.3f, lowThreshold=%0.3f, highThreshold=%0.3f, "
836 "acceleration=%0.3f\n",
837 mConfig.wheelVelocityControlParameters.scale,
838 mConfig.wheelVelocityControlParameters.lowThreshold,
839 mConfig.wheelVelocityControlParameters.highThreshold,
840 mConfig.wheelVelocityControlParameters.acceleration);
841
842 dump += StringPrintf(INDENT2 "PointerGesture:\n");
843 dump += StringPrintf(INDENT3 "Enabled: %s\n", toString(mConfig.pointerGesturesEnabled));
844 dump += StringPrintf(INDENT3 "QuietInterval: %0.1fms\n",
845 mConfig.pointerGestureQuietInterval * 0.000001f);
846 dump += StringPrintf(INDENT3 "DragMinSwitchSpeed: %0.1fpx/s\n",
847 mConfig.pointerGestureDragMinSwitchSpeed);
848 dump += StringPrintf(INDENT3 "TapInterval: %0.1fms\n",
849 mConfig.pointerGestureTapInterval * 0.000001f);
850 dump += StringPrintf(INDENT3 "TapDragInterval: %0.1fms\n",
851 mConfig.pointerGestureTapDragInterval * 0.000001f);
852 dump += StringPrintf(INDENT3 "TapSlop: %0.1fpx\n", mConfig.pointerGestureTapSlop);
853 dump += StringPrintf(INDENT3 "MultitouchSettleInterval: %0.1fms\n",
854 mConfig.pointerGestureMultitouchSettleInterval * 0.000001f);
855 dump += StringPrintf(INDENT3 "MultitouchMinDistance: %0.1fpx\n",
856 mConfig.pointerGestureMultitouchMinDistance);
857 dump += StringPrintf(INDENT3 "SwipeTransitionAngleCosine: %0.1f\n",
858 mConfig.pointerGestureSwipeTransitionAngleCosine);
859 dump += StringPrintf(INDENT3 "SwipeMaxWidthRatio: %0.1f\n",
860 mConfig.pointerGestureSwipeMaxWidthRatio);
861 dump += StringPrintf(INDENT3 "MovementSpeedRatio: %0.1f\n",
862 mConfig.pointerGestureMovementSpeedRatio);
863 dump += StringPrintf(INDENT3 "ZoomSpeedRatio: %0.1f\n", mConfig.pointerGestureZoomSpeedRatio);
864
865 dump += INDENT3 "Viewports:\n";
866 mConfig.dump(dump);
867 }
868
monitor()869 void InputReader::monitor() {
870 // Acquire and release the lock to ensure that the reader has not deadlocked.
871 std::unique_lock<std::mutex> lock(mLock);
872 mEventHub->wake();
873 mReaderIsAliveCondition.wait(lock);
874 // Check the EventHub
875 mEventHub->monitor();
876 }
877
878 // --- InputReader::ContextImpl ---
879
ContextImpl(InputReader * reader)880 InputReader::ContextImpl::ContextImpl(InputReader* reader)
881 : mReader(reader), mIdGenerator(IdGenerator::Source::INPUT_READER) {}
882
updateGlobalMetaState()883 void InputReader::ContextImpl::updateGlobalMetaState() {
884 // lock is already held by the input loop
885 mReader->updateGlobalMetaStateLocked();
886 }
887
getGlobalMetaState()888 int32_t InputReader::ContextImpl::getGlobalMetaState() {
889 // lock is already held by the input loop
890 return mReader->getGlobalMetaStateLocked();
891 }
892
updateLedMetaState(int32_t metaState)893 void InputReader::ContextImpl::updateLedMetaState(int32_t metaState) {
894 // lock is already held by the input loop
895 mReader->updateLedMetaStateLocked(metaState);
896 }
897
getLedMetaState()898 int32_t InputReader::ContextImpl::getLedMetaState() {
899 // lock is already held by the input loop
900 return mReader->getLedMetaStateLocked();
901 }
902
disableVirtualKeysUntil(nsecs_t time)903 void InputReader::ContextImpl::disableVirtualKeysUntil(nsecs_t time) {
904 // lock is already held by the input loop
905 mReader->disableVirtualKeysUntilLocked(time);
906 }
907
shouldDropVirtualKey(nsecs_t now,int32_t keyCode,int32_t scanCode)908 bool InputReader::ContextImpl::shouldDropVirtualKey(nsecs_t now, int32_t keyCode,
909 int32_t scanCode) {
910 // lock is already held by the input loop
911 return mReader->shouldDropVirtualKeyLocked(now, keyCode, scanCode);
912 }
913
fadePointer()914 void InputReader::ContextImpl::fadePointer() {
915 // lock is already held by the input loop
916 mReader->fadePointerLocked();
917 }
918
getPointerController(int32_t deviceId)919 std::shared_ptr<PointerControllerInterface> InputReader::ContextImpl::getPointerController(
920 int32_t deviceId) {
921 // lock is already held by the input loop
922 return mReader->getPointerControllerLocked(deviceId);
923 }
924
requestTimeoutAtTime(nsecs_t when)925 void InputReader::ContextImpl::requestTimeoutAtTime(nsecs_t when) {
926 // lock is already held by the input loop
927 mReader->requestTimeoutAtTimeLocked(when);
928 }
929
bumpGeneration()930 int32_t InputReader::ContextImpl::bumpGeneration() {
931 // lock is already held by the input loop
932 return mReader->bumpGenerationLocked();
933 }
934
getExternalStylusDevices(std::vector<InputDeviceInfo> & outDevices)935 void InputReader::ContextImpl::getExternalStylusDevices(std::vector<InputDeviceInfo>& outDevices) {
936 // lock is already held by whatever called refreshConfigurationLocked
937 mReader->getExternalStylusDevicesLocked(outDevices);
938 }
939
dispatchExternalStylusState(const StylusState & state)940 void InputReader::ContextImpl::dispatchExternalStylusState(const StylusState& state) {
941 mReader->dispatchExternalStylusStateLocked(state);
942 }
943
getPolicy()944 InputReaderPolicyInterface* InputReader::ContextImpl::getPolicy() {
945 return mReader->mPolicy.get();
946 }
947
getListener()948 InputListenerInterface* InputReader::ContextImpl::getListener() {
949 return mReader->mQueuedListener.get();
950 }
951
getEventHub()952 EventHubInterface* InputReader::ContextImpl::getEventHub() {
953 return mReader->mEventHub.get();
954 }
955
getNextId()956 int32_t InputReader::ContextImpl::getNextId() {
957 return mIdGenerator.nextId();
958 }
959
960 } // namespace android
961