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