blob: b3558c6d65c4e3c9a1b23e5a0b51f114b7df8aec [file] [log] [blame]
Michael Wrightd02c5b62014-02-10 15:10:22 -08001/*
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#define LOG_TAG "InputDispatcher"
18#define ATRACE_TAG ATRACE_TAG_INPUT
19
John Recke0710582019-09-26 13:46:12 -070020#define LOG_NDEBUG 1
Michael Wrightd02c5b62014-02-10 15:10:22 -080021
22// Log detailed debug messages about each inbound event notification to the dispatcher.
23#define DEBUG_INBOUND_EVENT_DETAILS 0
24
25// Log detailed debug messages about each outbound event processed by the dispatcher.
26#define DEBUG_OUTBOUND_EVENT_DETAILS 0
27
28// Log debug messages about the dispatch cycle.
29#define DEBUG_DISPATCH_CYCLE 0
30
Garfield Tan15601662020-09-22 15:32:38 -070031// Log debug messages about channel creation
32#define DEBUG_CHANNEL_CREATION 0
Michael Wrightd02c5b62014-02-10 15:10:22 -080033
34// Log debug messages about input event injection.
35#define DEBUG_INJECTION 0
36
37// Log debug messages about input focus tracking.
Siarhei Vishniakou86587282019-09-09 18:20:15 +010038static constexpr bool DEBUG_FOCUS = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -080039
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +000040// Log debug messages about touch occlusion
41// STOPSHIP(b/169067926): Set to false
42static constexpr bool DEBUG_TOUCH_OCCLUSION = true;
43
Michael Wrightd02c5b62014-02-10 15:10:22 -080044// Log debug messages about the app switch latency optimization.
45#define DEBUG_APP_SWITCH 0
46
47// Log debug messages about hover events.
48#define DEBUG_HOVER 0
49
Michael Wright2b3c3302018-03-02 17:19:13 +000050#include <android-base/chrono_utils.h>
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080051#include <android-base/stringprintf.h>
Siarhei Vishniakou70622952020-07-30 11:17:23 -050052#include <android/os/IInputConstants.h>
Robert Carr4e670e52018-08-15 13:26:12 -070053#include <binder/Binder.h>
Siarhei Vishniakou2508b872020-12-03 16:33:53 -100054#include <binder/IServiceManager.h>
55#include <com/android/internal/compat/IPlatformCompatNative.h>
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -080056#include <input/InputDevice.h>
Michael Wright44753b12020-07-08 13:48:11 +010057#include <input/InputWindow.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070058#include <log/log.h>
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +000059#include <log/log_event_list.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070060#include <powermanager/PowerManager.h>
Michael Wright44753b12020-07-08 13:48:11 +010061#include <statslog.h>
62#include <unistd.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070063#include <utils/Trace.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080064
Michael Wright44753b12020-07-08 13:48:11 +010065#include <cerrno>
66#include <cinttypes>
67#include <climits>
68#include <cstddef>
69#include <ctime>
70#include <queue>
71#include <sstream>
72
73#include "Connection.h"
Chris Yef59a2f42020-10-16 12:55:26 -070074#include "InputDispatcher.h"
Michael Wright44753b12020-07-08 13:48:11 +010075
Michael Wrightd02c5b62014-02-10 15:10:22 -080076#define INDENT " "
77#define INDENT2 " "
78#define INDENT3 " "
79#define INDENT4 " "
80
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080081using android::base::StringPrintf;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -080082using android::os::BlockUntrustedTouchesMode;
Siarhei Vishniakou2508b872020-12-03 16:33:53 -100083using android::os::IInputConstants;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -080084using android::os::InputEventInjectionResult;
85using android::os::InputEventInjectionSync;
Siarhei Vishniakou2508b872020-12-03 16:33:53 -100086using com::android::internal::compat::IPlatformCompatNative;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080087
Garfield Tane84e6f92019-08-29 17:28:41 -070088namespace android::inputdispatcher {
Michael Wrightd02c5b62014-02-10 15:10:22 -080089
90// Default input dispatching timeout if there is no focused application or paused window
91// from which to determine an appropriate dispatching timeout.
Siarhei Vishniakou70622952020-07-30 11:17:23 -050092constexpr std::chrono::duration DEFAULT_INPUT_DISPATCHING_TIMEOUT =
93 std::chrono::milliseconds(android::os::IInputConstants::DEFAULT_DISPATCHING_TIMEOUT_MILLIS);
Michael Wrightd02c5b62014-02-10 15:10:22 -080094
95// Amount of time to allow for all pending events to be processed when an app switch
96// key is on the way. This is used to preempt input dispatch and drop input events
97// when an application takes too long to respond and the user has pressed an app switch key.
Michael Wright2b3c3302018-03-02 17:19:13 +000098constexpr nsecs_t APP_SWITCH_TIMEOUT = 500 * 1000000LL; // 0.5sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080099
100// Amount of time to allow for an event to be dispatched (measured since its eventTime)
101// before considering it stale and dropping it.
Michael Wright2b3c3302018-03-02 17:19:13 +0000102constexpr nsecs_t STALE_EVENT_TIMEOUT = 10000 * 1000000LL; // 10sec
Michael Wrightd02c5b62014-02-10 15:10:22 -0800103
Michael Wrightd02c5b62014-02-10 15:10:22 -0800104// Log a warning when an event takes longer than this to process, even if an ANR does not occur.
Michael Wright2b3c3302018-03-02 17:19:13 +0000105constexpr nsecs_t SLOW_EVENT_PROCESSING_WARNING_TIMEOUT = 2000 * 1000000LL; // 2sec
106
107// Log a warning when an interception call takes longer than this to process.
108constexpr std::chrono::milliseconds SLOW_INTERCEPTION_THRESHOLD = 50ms;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800109
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700110// Additional key latency in case a connection is still processing some motion events.
111// This will help with the case when a user touched a button that opens a new window,
112// and gives us the chance to dispatch the key to this new window.
113constexpr std::chrono::nanoseconds KEY_WAITING_FOR_EVENTS_TIMEOUT = 500ms;
114
Michael Wrightd02c5b62014-02-10 15:10:22 -0800115// Number of recent events to keep for debugging purposes.
Michael Wright2b3c3302018-03-02 17:19:13 +0000116constexpr size_t RECENT_QUEUE_MAX_SIZE = 10;
117
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +0000118// Event log tags. See EventLogTags.logtags for reference
119constexpr int LOGTAG_INPUT_INTERACTION = 62000;
120constexpr int LOGTAG_INPUT_FOCUS = 62001;
121
Michael Wrightd02c5b62014-02-10 15:10:22 -0800122static inline nsecs_t now() {
123 return systemTime(SYSTEM_TIME_MONOTONIC);
124}
125
126static inline const char* toString(bool value) {
127 return value ? "true" : "false";
128}
129
130static inline int32_t getMotionEventActionPointerIndex(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700131 return (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) >>
132 AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800133}
134
135static bool isValidKeyAction(int32_t action) {
136 switch (action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700137 case AKEY_EVENT_ACTION_DOWN:
138 case AKEY_EVENT_ACTION_UP:
139 return true;
140 default:
141 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800142 }
143}
144
145static bool validateKeyEvent(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700146 if (!isValidKeyAction(action)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800147 ALOGE("Key event has invalid action code 0x%x", action);
148 return false;
149 }
150 return true;
151}
152
Michael Wright7b159c92015-05-14 14:48:03 +0100153static bool isValidMotionAction(int32_t action, int32_t actionButton, int32_t pointerCount) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800154 switch (action & AMOTION_EVENT_ACTION_MASK) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700155 case AMOTION_EVENT_ACTION_DOWN:
156 case AMOTION_EVENT_ACTION_UP:
157 case AMOTION_EVENT_ACTION_CANCEL:
158 case AMOTION_EVENT_ACTION_MOVE:
159 case AMOTION_EVENT_ACTION_OUTSIDE:
160 case AMOTION_EVENT_ACTION_HOVER_ENTER:
161 case AMOTION_EVENT_ACTION_HOVER_MOVE:
162 case AMOTION_EVENT_ACTION_HOVER_EXIT:
163 case AMOTION_EVENT_ACTION_SCROLL:
164 return true;
165 case AMOTION_EVENT_ACTION_POINTER_DOWN:
166 case AMOTION_EVENT_ACTION_POINTER_UP: {
167 int32_t index = getMotionEventActionPointerIndex(action);
168 return index >= 0 && index < pointerCount;
169 }
170 case AMOTION_EVENT_ACTION_BUTTON_PRESS:
171 case AMOTION_EVENT_ACTION_BUTTON_RELEASE:
172 return actionButton != 0;
173 default:
174 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800175 }
176}
177
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -0500178static int64_t millis(std::chrono::nanoseconds t) {
179 return std::chrono::duration_cast<std::chrono::milliseconds>(t).count();
180}
181
Michael Wright7b159c92015-05-14 14:48:03 +0100182static bool validateMotionEvent(int32_t action, int32_t actionButton, size_t pointerCount,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700183 const PointerProperties* pointerProperties) {
184 if (!isValidMotionAction(action, actionButton, pointerCount)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800185 ALOGE("Motion event has invalid action code 0x%x", action);
186 return false;
187 }
188 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
Narayan Kamath37764c72014-03-27 14:21:09 +0000189 ALOGE("Motion event has invalid pointer count %zu; value must be between 1 and %d.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700190 pointerCount, MAX_POINTERS);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800191 return false;
192 }
193 BitSet32 pointerIdBits;
194 for (size_t i = 0; i < pointerCount; i++) {
195 int32_t id = pointerProperties[i].id;
196 if (id < 0 || id > MAX_POINTER_ID) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700197 ALOGE("Motion event has invalid pointer id %d; value must be between 0 and %d", id,
198 MAX_POINTER_ID);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800199 return false;
200 }
201 if (pointerIdBits.hasBit(id)) {
202 ALOGE("Motion event has duplicate pointer id %d", id);
203 return false;
204 }
205 pointerIdBits.markBit(id);
206 }
207 return true;
208}
209
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000210static std::string dumpRegion(const Region& region) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800211 if (region.isEmpty()) {
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000212 return "<empty>";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800213 }
214
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000215 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800216 bool first = true;
217 Region::const_iterator cur = region.begin();
218 Region::const_iterator const tail = region.end();
219 while (cur != tail) {
220 if (first) {
221 first = false;
222 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800223 dump += "|";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800224 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800225 dump += StringPrintf("[%d,%d][%d,%d]", cur->left, cur->top, cur->right, cur->bottom);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800226 cur++;
227 }
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000228 return dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800229}
230
Siarhei Vishniakou14411c92020-09-18 21:15:05 -0500231static std::string dumpQueue(const std::deque<DispatchEntry*>& queue, nsecs_t currentTime) {
232 constexpr size_t maxEntries = 50; // max events to print
233 constexpr size_t skipBegin = maxEntries / 2;
234 const size_t skipEnd = queue.size() - maxEntries / 2;
235 // skip from maxEntries / 2 ... size() - maxEntries/2
236 // only print from 0 .. skipBegin and then from skipEnd .. size()
237
238 std::string dump;
239 for (size_t i = 0; i < queue.size(); i++) {
240 const DispatchEntry& entry = *queue[i];
241 if (i >= skipBegin && i < skipEnd) {
242 dump += StringPrintf(INDENT4 "<skipped %zu entries>\n", skipEnd - skipBegin);
243 i = skipEnd - 1; // it will be incremented to "skipEnd" by 'continue'
244 continue;
245 }
246 dump.append(INDENT4);
247 dump += entry.eventEntry->getDescription();
248 dump += StringPrintf(", seq=%" PRIu32
249 ", targetFlags=0x%08x, resolvedAction=%d, age=%" PRId64 "ms",
250 entry.seq, entry.targetFlags, entry.resolvedAction,
251 ns2ms(currentTime - entry.eventEntry->eventTime));
252 if (entry.deliveryTime != 0) {
253 // This entry was delivered, so add information on how long we've been waiting
254 dump += StringPrintf(", wait=%" PRId64 "ms", ns2ms(currentTime - entry.deliveryTime));
255 }
256 dump.append("\n");
257 }
258 return dump;
259}
260
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700261/**
262 * Find the entry in std::unordered_map by key, and return it.
263 * If the entry is not found, return a default constructed entry.
264 *
265 * Useful when the entries are vectors, since an empty vector will be returned
266 * if the entry is not found.
267 * Also useful when the entries are sp<>. If an entry is not found, nullptr is returned.
268 */
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700269template <typename K, typename V>
270static V getValueByKey(const std::unordered_map<K, V>& map, K key) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700271 auto it = map.find(key);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700272 return it != map.end() ? it->second : V{};
Tiger Huang721e26f2018-07-24 22:26:19 +0800273}
274
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700275/**
276 * Find the entry in std::unordered_map by value, and remove it.
277 * If more than one entry has the same value, then all matching
278 * key-value pairs will be removed.
279 *
280 * Return true if at least one value has been removed.
281 */
282template <typename K, typename V>
283static bool removeByValue(std::unordered_map<K, V>& map, const V& value) {
284 bool removed = false;
285 for (auto it = map.begin(); it != map.end();) {
286 if (it->second == value) {
287 it = map.erase(it);
288 removed = true;
289 } else {
290 it++;
291 }
292 }
293 return removed;
294}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800295
Vishnu Nair958da932020-08-21 17:12:37 -0700296/**
297 * Find the entry in std::unordered_map by key and return the value as an optional.
298 */
299template <typename K, typename V>
300static std::optional<V> getOptionalValueByKey(const std::unordered_map<K, V>& map, K key) {
301 auto it = map.find(key);
302 return it != map.end() ? std::optional<V>{it->second} : std::nullopt;
303}
304
chaviwaf87b3e2019-10-01 16:59:28 -0700305static bool haveSameToken(const sp<InputWindowHandle>& first, const sp<InputWindowHandle>& second) {
306 if (first == second) {
307 return true;
308 }
309
310 if (first == nullptr || second == nullptr) {
311 return false;
312 }
313
314 return first->getToken() == second->getToken();
315}
316
Bernardo Rufino1ff9d592021-01-18 16:58:57 +0000317static bool haveSameApplicationToken(const InputWindowInfo* first, const InputWindowInfo* second) {
318 if (first == nullptr || second == nullptr) {
319 return false;
320 }
321 return first->applicationInfo.token != nullptr &&
322 first->applicationInfo.token == second->applicationInfo.token;
323}
324
Siarhei Vishniakouadfd4fa2019-12-20 11:02:58 -0800325static bool isStaleEvent(nsecs_t currentTime, const EventEntry& entry) {
326 return currentTime - entry.eventTime >= STALE_EVENT_TIMEOUT;
327}
328
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000329static std::unique_ptr<DispatchEntry> createDispatchEntry(const InputTarget& inputTarget,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700330 std::shared_ptr<EventEntry> eventEntry,
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000331 int32_t inputTargetFlags) {
yunho.shinf4a80b82020-11-16 21:13:57 +0900332 if (eventEntry->type == EventEntry::Type::MOTION) {
333 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
334 if (motionEntry.source & AINPUT_SOURCE_CLASS_JOYSTICK) {
335 const ui::Transform identityTransform;
336 // Use identity transform for joystick events events because they don't depend on
337 // the window info
338 return std::make_unique<DispatchEntry>(eventEntry, inputTargetFlags, identityTransform,
339 1.0f /*globalScaleFactor*/);
340 }
341 }
342
chaviw1ff3d1e2020-07-01 15:53:47 -0700343 if (inputTarget.useDefaultPointerTransform()) {
344 const ui::Transform& transform = inputTarget.getDefaultPointerTransform();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700345 return std::make_unique<DispatchEntry>(eventEntry, inputTargetFlags, transform,
chaviw1ff3d1e2020-07-01 15:53:47 -0700346 inputTarget.globalScaleFactor);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000347 }
348
349 ALOG_ASSERT(eventEntry->type == EventEntry::Type::MOTION);
350 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
351
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700352 std::vector<PointerCoords> pointerCoords;
353 pointerCoords.resize(motionEntry.pointerCount);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000354
355 // Use the first pointer information to normalize all other pointers. This could be any pointer
356 // as long as all other pointers are normalized to the same value and the final DispatchEntry
chaviw1ff3d1e2020-07-01 15:53:47 -0700357 // uses the transform for the normalized pointer.
358 const ui::Transform& firstPointerTransform =
359 inputTarget.pointerTransforms[inputTarget.pointerIds.firstMarkedBit()];
360 ui::Transform inverseFirstTransform = firstPointerTransform.inverse();
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000361
362 // Iterate through all pointers in the event to normalize against the first.
363 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.pointerCount; pointerIndex++) {
364 const PointerProperties& pointerProperties = motionEntry.pointerProperties[pointerIndex];
365 uint32_t pointerId = uint32_t(pointerProperties.id);
chaviw1ff3d1e2020-07-01 15:53:47 -0700366 const ui::Transform& currTransform = inputTarget.pointerTransforms[pointerId];
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000367
368 pointerCoords[pointerIndex].copyFrom(motionEntry.pointerCoords[pointerIndex]);
chaviw1ff3d1e2020-07-01 15:53:47 -0700369 // First, apply the current pointer's transform to update the coordinates into
370 // window space.
371 pointerCoords[pointerIndex].transform(currTransform);
372 // Next, apply the inverse transform of the normalized coordinates so the
373 // current coordinates are transformed into the normalized coordinate space.
374 pointerCoords[pointerIndex].transform(inverseFirstTransform);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000375 }
376
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700377 std::unique_ptr<MotionEntry> combinedMotionEntry =
378 std::make_unique<MotionEntry>(motionEntry.id, motionEntry.eventTime,
379 motionEntry.deviceId, motionEntry.source,
380 motionEntry.displayId, motionEntry.policyFlags,
381 motionEntry.action, motionEntry.actionButton,
382 motionEntry.flags, motionEntry.metaState,
383 motionEntry.buttonState, motionEntry.classification,
384 motionEntry.edgeFlags, motionEntry.xPrecision,
385 motionEntry.yPrecision, motionEntry.xCursorPosition,
386 motionEntry.yCursorPosition, motionEntry.downTime,
387 motionEntry.pointerCount, motionEntry.pointerProperties,
388 pointerCoords.data(), 0 /* xOffset */, 0 /* yOffset */);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000389
390 if (motionEntry.injectionState) {
391 combinedMotionEntry->injectionState = motionEntry.injectionState;
392 combinedMotionEntry->injectionState->refCount += 1;
393 }
394
395 std::unique_ptr<DispatchEntry> dispatchEntry =
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700396 std::make_unique<DispatchEntry>(std::move(combinedMotionEntry), inputTargetFlags,
397 firstPointerTransform, inputTarget.globalScaleFactor);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000398 return dispatchEntry;
399}
400
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -0700401static void addGestureMonitors(const std::vector<Monitor>& monitors,
402 std::vector<TouchedMonitor>& outTouchedMonitors, float xOffset = 0,
403 float yOffset = 0) {
404 if (monitors.empty()) {
405 return;
406 }
407 outTouchedMonitors.reserve(monitors.size() + outTouchedMonitors.size());
408 for (const Monitor& monitor : monitors) {
409 outTouchedMonitors.emplace_back(monitor, xOffset, yOffset);
410 }
411}
412
Garfield Tan15601662020-09-22 15:32:38 -0700413static status_t openInputChannelPair(const std::string& name,
414 std::shared_ptr<InputChannel>& serverChannel,
415 std::unique_ptr<InputChannel>& clientChannel) {
416 std::unique_ptr<InputChannel> uniqueServerChannel;
417 status_t result = InputChannel::openInputChannelPair(name, uniqueServerChannel, clientChannel);
418
419 serverChannel = std::move(uniqueServerChannel);
420 return result;
421}
422
Vishnu Nair958da932020-08-21 17:12:37 -0700423const char* InputDispatcher::typeToString(InputDispatcher::FocusResult result) {
424 switch (result) {
425 case InputDispatcher::FocusResult::OK:
426 return "Ok";
427 case InputDispatcher::FocusResult::NO_WINDOW:
428 return "Window not found";
429 case InputDispatcher::FocusResult::NOT_FOCUSABLE:
430 return "Window not focusable";
431 case InputDispatcher::FocusResult::NOT_VISIBLE:
432 return "Window not visible";
433 }
434}
435
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500436template <typename T>
437static bool sharedPointersEqual(const std::shared_ptr<T>& lhs, const std::shared_ptr<T>& rhs) {
438 if (lhs == nullptr && rhs == nullptr) {
439 return true;
440 }
441 if (lhs == nullptr || rhs == nullptr) {
442 return false;
443 }
444 return *lhs == *rhs;
445}
446
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000447static sp<IPlatformCompatNative> getCompatService() {
448 sp<IBinder> service(defaultServiceManager()->getService(String16("platform_compat_native")));
449 if (service == nullptr) {
450 ALOGE("Failed to link to compat service");
451 return nullptr;
452 }
453 return interface_cast<IPlatformCompatNative>(service);
454}
455
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +0000456static KeyEvent createKeyEvent(const KeyEntry& entry) {
457 KeyEvent event;
458 event.initialize(entry.id, entry.deviceId, entry.source, entry.displayId, INVALID_HMAC,
459 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
460 entry.repeatCount, entry.downTime, entry.eventTime);
461 return event;
462}
463
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000464static std::optional<int32_t> findMonitorPidByToken(
465 const std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay,
466 const sp<IBinder>& token) {
467 for (const auto& it : monitorsByDisplay) {
468 const std::vector<Monitor>& monitors = it.second;
469 for (const Monitor& monitor : monitors) {
470 if (monitor.inputChannel->getConnectionToken() == token) {
471 return monitor.pid;
472 }
473 }
474 }
475 return std::nullopt;
476}
477
Michael Wrightd02c5b62014-02-10 15:10:22 -0800478// --- InputDispatcher ---
479
Garfield Tan00f511d2019-06-12 16:55:40 -0700480InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy)
481 : mPolicy(policy),
482 mPendingEvent(nullptr),
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700483 mLastDropReason(DropReason::NOT_DROPPED),
Garfield Tanff1f1bb2020-01-28 13:24:04 -0800484 mIdGenerator(IdGenerator::Source::INPUT_DISPATCHER),
Garfield Tan00f511d2019-06-12 16:55:40 -0700485 mAppSwitchSawKeyDown(false),
486 mAppSwitchDueTime(LONG_LONG_MAX),
487 mNextUnblockedEvent(nullptr),
488 mDispatchEnabled(false),
489 mDispatchFrozen(false),
490 mInputFilterEnabled(false),
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -0800491 // mInTouchMode will be initialized by the WindowManager to the default device config.
492 // To avoid leaking stack in case that call never comes, and for tests,
493 // initialize it here anyways.
494 mInTouchMode(true),
Bernardo Rufinoea97d182020-08-19 14:43:14 +0100495 mMaximumObscuringOpacityForTouch(1.0f),
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000496 mFocusedDisplayId(ADISPLAY_ID_DEFAULT),
Prabir Pradhan99987712020-11-10 18:43:05 -0800497 mFocusedWindowRequestedPointerCapture(false),
498 mWindowTokenWithPointerCapture(nullptr),
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000499 mCompatService(getCompatService()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800500 mLooper = new Looper(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800501 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800502
Yi Kong9b14ac62018-07-17 13:48:38 -0700503 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800504
505 policy->getDispatcherConfiguration(&mConfig);
506}
507
508InputDispatcher::~InputDispatcher() {
509 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800510 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800511
512 resetKeyRepeatLocked();
513 releasePendingEventLocked();
514 drainInboundQueueLocked();
515 }
516
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700517 while (!mConnectionsByFd.empty()) {
518 sp<Connection> connection = mConnectionsByFd.begin()->second;
Garfield Tan15601662020-09-22 15:32:38 -0700519 removeInputChannel(connection->inputChannel->getConnectionToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800520 }
521}
522
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700523status_t InputDispatcher::start() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700524 if (mThread) {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700525 return ALREADY_EXISTS;
526 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700527 mThread = std::make_unique<InputThread>(
528 "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
529 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700530}
531
532status_t InputDispatcher::stop() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700533 if (mThread && mThread->isCallingThread()) {
534 ALOGE("InputDispatcher cannot be stopped from its own thread!");
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700535 return INVALID_OPERATION;
536 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700537 mThread.reset();
538 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700539}
540
Michael Wrightd02c5b62014-02-10 15:10:22 -0800541void InputDispatcher::dispatchOnce() {
542 nsecs_t nextWakeupTime = LONG_LONG_MAX;
543 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800544 std::scoped_lock _l(mLock);
545 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800546
547 // Run a dispatch loop if there are no pending commands.
548 // The dispatch loop might enqueue commands to run afterwards.
549 if (!haveCommandsLocked()) {
550 dispatchOnceInnerLocked(&nextWakeupTime);
551 }
552
553 // Run all pending commands if there are any.
554 // If any commands were run then force the next poll to wake up immediately.
555 if (runCommandsLockedInterruptible()) {
556 nextWakeupTime = LONG_LONG_MIN;
557 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800558
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700559 // If we are still waiting for ack on some events,
560 // we might have to wake up earlier to check if an app is anr'ing.
561 const nsecs_t nextAnrCheck = processAnrsLocked();
562 nextWakeupTime = std::min(nextWakeupTime, nextAnrCheck);
563
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800564 // We are about to enter an infinitely long sleep, because we have no commands or
565 // pending or queued events
566 if (nextWakeupTime == LONG_LONG_MAX) {
567 mDispatcherEnteredIdle.notify_all();
568 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800569 } // release lock
570
571 // Wait for callback or timeout or wake. (make sure we round up, not down)
572 nsecs_t currentTime = now();
573 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
574 mLooper->pollOnce(timeoutMillis);
575}
576
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700577/**
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500578 * Raise ANR if there is no focused window.
579 * Before the ANR is raised, do a final state check:
580 * 1. The currently focused application must be the same one we are waiting for.
581 * 2. Ensure we still don't have a focused window.
582 */
583void InputDispatcher::processNoFocusedWindowAnrLocked() {
584 // Check if the application that we are waiting for is still focused.
585 std::shared_ptr<InputApplicationHandle> focusedApplication =
586 getValueByKey(mFocusedApplicationHandlesByDisplay, mAwaitedApplicationDisplayId);
587 if (focusedApplication == nullptr ||
588 focusedApplication->getApplicationToken() !=
589 mAwaitedFocusedApplication->getApplicationToken()) {
590 // Unexpected because we should have reset the ANR timer when focused application changed
591 ALOGE("Waited for a focused window, but focused application has already changed to %s",
592 focusedApplication->getName().c_str());
593 return; // The focused application has changed.
594 }
595
596 const sp<InputWindowHandle>& focusedWindowHandle =
597 getFocusedWindowHandleLocked(mAwaitedApplicationDisplayId);
598 if (focusedWindowHandle != nullptr) {
599 return; // We now have a focused window. No need for ANR.
600 }
601 onAnrLocked(mAwaitedFocusedApplication);
602}
603
604/**
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700605 * Check if any of the connections' wait queues have events that are too old.
606 * If we waited for events to be ack'ed for more than the window timeout, raise an ANR.
607 * Return the time at which we should wake up next.
608 */
609nsecs_t InputDispatcher::processAnrsLocked() {
610 const nsecs_t currentTime = now();
611 nsecs_t nextAnrCheck = LONG_LONG_MAX;
612 // Check if we are waiting for a focused window to appear. Raise ANR if waited too long
613 if (mNoFocusedWindowTimeoutTime.has_value() && mAwaitedFocusedApplication != nullptr) {
614 if (currentTime >= *mNoFocusedWindowTimeoutTime) {
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500615 processNoFocusedWindowAnrLocked();
Chris Yea209fde2020-07-22 13:54:51 -0700616 mAwaitedFocusedApplication.reset();
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500617 mNoFocusedWindowTimeoutTime = std::nullopt;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700618 return LONG_LONG_MIN;
619 } else {
Siarhei Vishniakou38a6d272020-10-20 20:29:33 -0500620 // Keep waiting. We will drop the event when mNoFocusedWindowTimeoutTime comes.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700621 nextAnrCheck = *mNoFocusedWindowTimeoutTime;
622 }
623 }
624
625 // Check if any connection ANRs are due
626 nextAnrCheck = std::min(nextAnrCheck, mAnrTracker.firstTimeout());
627 if (currentTime < nextAnrCheck) { // most likely scenario
628 return nextAnrCheck; // everything is normal. Let's check again at nextAnrCheck
629 }
630
631 // If we reached here, we have an unresponsive connection.
632 sp<Connection> connection = getConnectionLocked(mAnrTracker.firstToken());
633 if (connection == nullptr) {
634 ALOGE("Could not find connection for entry %" PRId64, mAnrTracker.firstTimeout());
635 return nextAnrCheck;
636 }
637 connection->responsive = false;
638 // Stop waking up for this unresponsive connection
639 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000640 onAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700641 return LONG_LONG_MIN;
642}
643
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500644std::chrono::nanoseconds InputDispatcher::getDispatchingTimeoutLocked(const sp<IBinder>& token) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700645 sp<InputWindowHandle> window = getWindowHandleLocked(token);
646 if (window != nullptr) {
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500647 return window->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700648 }
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500649 return DEFAULT_INPUT_DISPATCHING_TIMEOUT;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700650}
651
Michael Wrightd02c5b62014-02-10 15:10:22 -0800652void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
653 nsecs_t currentTime = now();
654
Jeff Browndc5992e2014-04-11 01:27:26 -0700655 // Reset the key repeat timer whenever normal dispatch is suspended while the
656 // device is in a non-interactive state. This is to ensure that we abort a key
657 // repeat if the device is just coming out of sleep.
658 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800659 resetKeyRepeatLocked();
660 }
661
662 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
663 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +0100664 if (DEBUG_FOCUS) {
665 ALOGD("Dispatch frozen. Waiting some more.");
666 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800667 return;
668 }
669
670 // Optimize latency of app switches.
671 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
672 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
673 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
674 if (mAppSwitchDueTime < *nextWakeupTime) {
675 *nextWakeupTime = mAppSwitchDueTime;
676 }
677
678 // Ready to start a new event.
679 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700680 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700681 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800682 if (isAppSwitchDue) {
683 // The inbound queue is empty so the app switch key we were waiting
684 // for will never arrive. Stop waiting for it.
685 resetPendingAppSwitchLocked(false);
686 isAppSwitchDue = false;
687 }
688
689 // Synthesize a key repeat if appropriate.
690 if (mKeyRepeatState.lastKeyEntry) {
691 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
692 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
693 } else {
694 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
695 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
696 }
697 }
698 }
699
700 // Nothing to do if there is no pending event.
701 if (!mPendingEvent) {
702 return;
703 }
704 } else {
705 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700706 mPendingEvent = mInboundQueue.front();
707 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800708 traceInboundQueueLengthLocked();
709 }
710
711 // Poke user activity for this event.
712 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700713 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800714 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800715 }
716
717 // Now we have an event to dispatch.
718 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700719 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800720 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700721 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800722 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700723 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800724 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700725 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800726 }
727
728 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700729 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800730 }
731
732 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700733 case EventEntry::Type::CONFIGURATION_CHANGED: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700734 const ConfigurationChangedEntry& typedEntry =
735 static_cast<const ConfigurationChangedEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700736 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700737 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700738 break;
739 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800740
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700741 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700742 const DeviceResetEntry& typedEntry =
743 static_cast<const DeviceResetEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700744 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700745 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700746 break;
747 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800748
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100749 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700750 std::shared_ptr<FocusEntry> typedEntry =
751 std::static_pointer_cast<FocusEntry>(mPendingEvent);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100752 dispatchFocusLocked(currentTime, typedEntry);
753 done = true;
754 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
755 break;
756 }
757
Prabir Pradhan99987712020-11-10 18:43:05 -0800758 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
759 const auto typedEntry =
760 std::static_pointer_cast<PointerCaptureChangedEntry>(mPendingEvent);
761 dispatchPointerCaptureChangedLocked(currentTime, typedEntry, dropReason);
762 done = true;
763 break;
764 }
765
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700766 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700767 std::shared_ptr<KeyEntry> keyEntry = std::static_pointer_cast<KeyEntry>(mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700768 if (isAppSwitchDue) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700769 if (isAppSwitchKeyEvent(*keyEntry)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700770 resetPendingAppSwitchLocked(true);
771 isAppSwitchDue = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700772 } else if (dropReason == DropReason::NOT_DROPPED) {
773 dropReason = DropReason::APP_SWITCH;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700774 }
775 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700776 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *keyEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700777 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700778 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700779 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
780 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700781 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700782 done = dispatchKeyLocked(currentTime, keyEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700783 break;
784 }
785
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700786 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700787 std::shared_ptr<MotionEntry> motionEntry =
788 std::static_pointer_cast<MotionEntry>(mPendingEvent);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700789 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
790 dropReason = DropReason::APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800791 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700792 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *motionEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700793 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700794 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700795 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
796 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700797 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700798 done = dispatchMotionLocked(currentTime, motionEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700799 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800800 }
Chris Yef59a2f42020-10-16 12:55:26 -0700801
802 case EventEntry::Type::SENSOR: {
803 std::shared_ptr<SensorEntry> sensorEntry =
804 std::static_pointer_cast<SensorEntry>(mPendingEvent);
805 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
806 dropReason = DropReason::APP_SWITCH;
807 }
808 // Sensor timestamps use SYSTEM_TIME_BOOTTIME time base, so we can't use
809 // 'currentTime' here, get SYSTEM_TIME_BOOTTIME instead.
810 nsecs_t bootTime = systemTime(SYSTEM_TIME_BOOTTIME);
811 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(bootTime, *sensorEntry)) {
812 dropReason = DropReason::STALE;
813 }
814 dispatchSensorLocked(currentTime, sensorEntry, &dropReason, nextWakeupTime);
815 done = true;
816 break;
817 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800818 }
819
820 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700821 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700822 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800823 }
Michael Wright3a981722015-06-10 15:26:13 +0100824 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800825
826 releasePendingEventLocked();
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700827 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -0800828 }
829}
830
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700831/**
832 * Return true if the events preceding this incoming motion event should be dropped
833 * Return false otherwise (the default behaviour)
834 */
835bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700836 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700837 (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700838
839 // Optimize case where the current application is unresponsive and the user
840 // decides to touch a window in a different application.
841 // If the application takes too long to catch up then we drop all events preceding
842 // the touch into the other window.
843 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700844 int32_t displayId = motionEntry.displayId;
845 int32_t x = static_cast<int32_t>(
846 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
847 int32_t y = static_cast<int32_t>(
848 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
849 sp<InputWindowHandle> touchedWindowHandle =
850 findTouchedWindowAtLocked(displayId, x, y, nullptr);
851 if (touchedWindowHandle != nullptr &&
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700852 touchedWindowHandle->getApplicationToken() !=
853 mAwaitedFocusedApplication->getApplicationToken()) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700854 // User touched a different application than the one we are waiting on.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700855 ALOGI("Pruning input queue because user touched a different application while waiting "
856 "for %s",
857 mAwaitedFocusedApplication->getName().c_str());
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700858 return true;
859 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700860
861 // Alternatively, maybe there's a gesture monitor that could handle this event
862 std::vector<TouchedMonitor> gestureMonitors =
863 findTouchedGestureMonitorsLocked(displayId, {});
864 for (TouchedMonitor& gestureMonitor : gestureMonitors) {
865 sp<Connection> connection =
866 getConnectionLocked(gestureMonitor.monitor.inputChannel->getConnectionToken());
Siarhei Vishniakou34ed4d42020-06-18 00:43:02 +0000867 if (connection != nullptr && connection->responsive) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700868 // This monitor could take more input. Drop all events preceding this
869 // event, so that gesture monitor could get a chance to receive the stream
870 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
871 "responsive gesture monitor that may handle the event",
872 mAwaitedFocusedApplication->getName().c_str());
873 return true;
874 }
875 }
876 }
877
878 // Prevent getting stuck: if we have a pending key event, and some motion events that have not
879 // yet been processed by some connections, the dispatcher will wait for these motion
880 // events to be processed before dispatching the key event. This is because these motion events
881 // may cause a new window to be launched, which the user might expect to receive focus.
882 // To prevent waiting forever for such events, just send the key to the currently focused window
883 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
884 ALOGD("Received a new pointer down event, stop waiting for events to process and "
885 "just send the pending key event to the focused window.");
886 mKeyIsWaitingForEventsTimeout = now();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700887 }
888 return false;
889}
890
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700891bool InputDispatcher::enqueueInboundEventLocked(std::unique_ptr<EventEntry> newEntry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700892 bool needWake = mInboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700893 mInboundQueue.push_back(std::move(newEntry));
894 EventEntry& entry = *(mInboundQueue.back());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800895 traceInboundQueueLengthLocked();
896
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700897 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700898 case EventEntry::Type::KEY: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700899 // Optimize app switch latency.
900 // If the application takes too long to catch up then we drop all events preceding
901 // the app switch key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700902 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700903 if (isAppSwitchKeyEvent(keyEntry)) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700904 if (keyEntry.action == AKEY_EVENT_ACTION_DOWN) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700905 mAppSwitchSawKeyDown = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700906 } else if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700907 if (mAppSwitchSawKeyDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800908#if DEBUG_APP_SWITCH
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700909 ALOGD("App switch is pending!");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800910#endif
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700911 mAppSwitchDueTime = keyEntry.eventTime + APP_SWITCH_TIMEOUT;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700912 mAppSwitchSawKeyDown = false;
913 needWake = true;
914 }
915 }
916 }
917 break;
918 }
919
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700920 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700921 if (shouldPruneInboundQueueLocked(static_cast<MotionEntry&>(entry))) {
922 mNextUnblockedEvent = mInboundQueue.back();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700923 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800924 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700925 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800926 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100927 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700928 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
929 break;
930 }
931 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -0800932 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -0700933 case EventEntry::Type::SENSOR:
Prabir Pradhan99987712020-11-10 18:43:05 -0800934 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700935 // nothing to do
936 break;
937 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800938 }
939
940 return needWake;
941}
942
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700943void InputDispatcher::addRecentEventLocked(std::shared_ptr<EventEntry> entry) {
Chris Yef59a2f42020-10-16 12:55:26 -0700944 // Do not store sensor event in recent queue to avoid flooding the queue.
945 if (entry->type != EventEntry::Type::SENSOR) {
946 mRecentQueue.push_back(entry);
947 }
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700948 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700949 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800950 }
951}
952
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700953sp<InputWindowHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, int32_t x,
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700954 int32_t y, TouchState* touchState,
955 bool addOutsideTargets,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700956 bool addPortalWindows) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700957 if ((addPortalWindows || addOutsideTargets) && touchState == nullptr) {
958 LOG_ALWAYS_FATAL(
959 "Must provide a valid touch state if adding portal windows or outside targets");
960 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800961 // Traverse windows from front to back to find touched window.
Vishnu Nairad321cd2020-08-20 16:40:21 -0700962 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800963 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800964 const InputWindowInfo* windowInfo = windowHandle->getInfo();
965 if (windowInfo->displayId == displayId) {
Michael Wright44753b12020-07-08 13:48:11 +0100966 auto flags = windowInfo->flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800967
968 if (windowInfo->visible) {
Michael Wright44753b12020-07-08 13:48:11 +0100969 if (!flags.test(InputWindowInfo::Flag::NOT_TOUCHABLE)) {
970 bool isTouchModal = !flags.test(InputWindowInfo::Flag::NOT_FOCUSABLE) &&
971 !flags.test(InputWindowInfo::Flag::NOT_TOUCH_MODAL);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800972 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800973 int32_t portalToDisplayId = windowInfo->portalToDisplayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700974 if (portalToDisplayId != ADISPLAY_ID_NONE &&
975 portalToDisplayId != displayId) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800976 if (addPortalWindows) {
977 // For the monitoring channels of the display.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700978 touchState->addPortalWindow(windowHandle);
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800979 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700980 return findTouchedWindowAtLocked(portalToDisplayId, x, y, touchState,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700981 addOutsideTargets, addPortalWindows);
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800982 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800983 // Found window.
984 return windowHandle;
985 }
986 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800987
Michael Wright44753b12020-07-08 13:48:11 +0100988 if (addOutsideTargets && flags.test(InputWindowInfo::Flag::WATCH_OUTSIDE_TOUCH)) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700989 touchState->addOrUpdateWindow(windowHandle,
990 InputTarget::FLAG_DISPATCH_AS_OUTSIDE,
991 BitSet32(0));
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800992 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800993 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800994 }
995 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700996 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800997}
998
Garfield Tane84e6f92019-08-29 17:28:41 -0700999std::vector<TouchedMonitor> InputDispatcher::findTouchedGestureMonitorsLocked(
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001000 int32_t displayId, const std::vector<sp<InputWindowHandle>>& portalWindows) const {
Michael Wright3dd60e22019-03-27 22:06:44 +00001001 std::vector<TouchedMonitor> touchedMonitors;
1002
1003 std::vector<Monitor> monitors = getValueByKey(mGestureMonitorsByDisplay, displayId);
1004 addGestureMonitors(monitors, touchedMonitors);
1005 for (const sp<InputWindowHandle>& portalWindow : portalWindows) {
1006 const InputWindowInfo* windowInfo = portalWindow->getInfo();
1007 monitors = getValueByKey(mGestureMonitorsByDisplay, windowInfo->portalToDisplayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001008 addGestureMonitors(monitors, touchedMonitors, -windowInfo->frameLeft,
1009 -windowInfo->frameTop);
Michael Wright3dd60e22019-03-27 22:06:44 +00001010 }
1011 return touchedMonitors;
1012}
1013
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001014void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001015 const char* reason;
1016 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001017 case DropReason::POLICY:
Michael Wrightd02c5b62014-02-10 15:10:22 -08001018#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001019 ALOGD("Dropped event because policy consumed it.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001020#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001021 reason = "inbound event was dropped because the policy consumed it";
1022 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001023 case DropReason::DISABLED:
1024 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001025 ALOGI("Dropped event because input dispatch is disabled.");
1026 }
1027 reason = "inbound event was dropped because input dispatch is disabled";
1028 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001029 case DropReason::APP_SWITCH:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001030 ALOGI("Dropped event because of pending overdue app switch.");
1031 reason = "inbound event was dropped because of pending overdue app switch";
1032 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001033 case DropReason::BLOCKED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001034 ALOGI("Dropped event because the current application is not responding and the user "
1035 "has started interacting with a different application.");
1036 reason = "inbound event was dropped because the current application is not responding "
1037 "and the user has started interacting with a different application";
1038 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001039 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001040 ALOGI("Dropped event because it is stale.");
1041 reason = "inbound event was dropped because it is stale";
1042 break;
Prabir Pradhan99987712020-11-10 18:43:05 -08001043 case DropReason::NO_POINTER_CAPTURE:
1044 ALOGI("Dropped event because there is no window with Pointer Capture.");
1045 reason = "inbound event was dropped because there is no window with Pointer Capture";
1046 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001047 case DropReason::NOT_DROPPED: {
1048 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001049 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001050 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001051 }
1052
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001053 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001054 case EventEntry::Type::KEY: {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001055 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
1056 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001057 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001058 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001059 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001060 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1061 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001062 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
1063 synthesizeCancelationEventsForAllConnectionsLocked(options);
1064 } else {
1065 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
1066 synthesizeCancelationEventsForAllConnectionsLocked(options);
1067 }
1068 break;
1069 }
Chris Yef59a2f42020-10-16 12:55:26 -07001070 case EventEntry::Type::SENSOR: {
1071 break;
1072 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001073 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
1074 break;
1075 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001076 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001077 case EventEntry::Type::CONFIGURATION_CHANGED:
1078 case EventEntry::Type::DEVICE_RESET: {
Chris Yef59a2f42020-10-16 12:55:26 -07001079 LOG_ALWAYS_FATAL("Should not drop %s events", NamedEnum::string(entry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001080 break;
1081 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001082 }
1083}
1084
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001085static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001086 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
1087 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001088}
1089
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001090bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
1091 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
1092 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
1093 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001094}
1095
1096bool InputDispatcher::isAppSwitchPendingLocked() {
1097 return mAppSwitchDueTime != LONG_LONG_MAX;
1098}
1099
1100void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
1101 mAppSwitchDueTime = LONG_LONG_MAX;
1102
1103#if DEBUG_APP_SWITCH
1104 if (handled) {
1105 ALOGD("App switch has arrived.");
1106 } else {
1107 ALOGD("App switch was abandoned.");
1108 }
1109#endif
1110}
1111
Michael Wrightd02c5b62014-02-10 15:10:22 -08001112bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001113 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001114}
1115
1116bool InputDispatcher::runCommandsLockedInterruptible() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001117 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001118 return false;
1119 }
1120
1121 do {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001122 std::unique_ptr<CommandEntry> commandEntry = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001123 mCommandQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001124 Command command = commandEntry->command;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001125 command(*this, commandEntry.get()); // commands are implicitly 'LockedInterruptible'
Michael Wrightd02c5b62014-02-10 15:10:22 -08001126
1127 commandEntry->connection.clear();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001128 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001129 return true;
1130}
1131
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001132void InputDispatcher::postCommandLocked(std::unique_ptr<CommandEntry> commandEntry) {
1133 mCommandQueue.push_back(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001134}
1135
1136void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001137 while (!mInboundQueue.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001138 std::shared_ptr<EventEntry> entry = mInboundQueue.front();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001139 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001140 releaseInboundEventLocked(entry);
1141 }
1142 traceInboundQueueLengthLocked();
1143}
1144
1145void InputDispatcher::releasePendingEventLocked() {
1146 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001147 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -07001148 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001149 }
1150}
1151
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001152void InputDispatcher::releaseInboundEventLocked(std::shared_ptr<EventEntry> entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001153 InjectionState* injectionState = entry->injectionState;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001154 if (injectionState && injectionState->injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001155#if DEBUG_DISPATCH_CYCLE
1156 ALOGD("Injected inbound event was dropped.");
1157#endif
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001158 setInjectionResult(*entry, InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001159 }
1160 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001161 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001162 }
1163 addRecentEventLocked(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001164}
1165
1166void InputDispatcher::resetKeyRepeatLocked() {
1167 if (mKeyRepeatState.lastKeyEntry) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001168 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001169 }
1170}
1171
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001172std::shared_ptr<KeyEntry> InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
1173 std::shared_ptr<KeyEntry> entry = mKeyRepeatState.lastKeyEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001174
Michael Wright2e732952014-09-24 13:26:59 -07001175 uint32_t policyFlags = entry->policyFlags &
1176 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001177
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001178 std::shared_ptr<KeyEntry> newEntry =
1179 std::make_unique<KeyEntry>(mIdGenerator.nextId(), currentTime, entry->deviceId,
1180 entry->source, entry->displayId, policyFlags, entry->action,
1181 entry->flags, entry->keyCode, entry->scanCode,
1182 entry->metaState, entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001183
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001184 newEntry->syntheticRepeat = true;
1185 mKeyRepeatState.lastKeyEntry = newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001186 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001187 return newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001188}
1189
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001190bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001191 const ConfigurationChangedEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001192#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001193 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry.eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001194#endif
1195
1196 // Reset key repeating in case a keyboard device was added or removed or something.
1197 resetKeyRepeatLocked();
1198
1199 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001200 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
1201 &InputDispatcher::doNotifyConfigurationChangedLockedInterruptible);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001202 commandEntry->eventTime = entry.eventTime;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001203 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001204 return true;
1205}
1206
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001207bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime,
1208 const DeviceResetEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001209#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001210 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry.eventTime,
1211 entry.deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001212#endif
1213
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001214 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, "device was reset");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001215 options.deviceId = entry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001216 synthesizeCancelationEventsForAllConnectionsLocked(options);
1217 return true;
1218}
1219
Vishnu Nairad321cd2020-08-20 16:40:21 -07001220void InputDispatcher::enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus,
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001221 std::string_view reason) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001222 if (mPendingEvent != nullptr) {
1223 // Move the pending event to the front of the queue. This will give the chance
1224 // for the pending event to get dispatched to the newly focused window
1225 mInboundQueue.push_front(mPendingEvent);
1226 mPendingEvent = nullptr;
1227 }
1228
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001229 std::unique_ptr<FocusEntry> focusEntry =
1230 std::make_unique<FocusEntry>(mIdGenerator.nextId(), now(), windowToken, hasFocus,
1231 reason);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001232
1233 // This event should go to the front of the queue, but behind all other focus events
1234 // Find the last focus event, and insert right after it
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001235 std::deque<std::shared_ptr<EventEntry>>::reverse_iterator it =
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001236 std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001237 [](const std::shared_ptr<EventEntry>& event) {
1238 return event->type == EventEntry::Type::FOCUS;
1239 });
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001240
1241 // Maintain the order of focus events. Insert the entry after all other focus events.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001242 mInboundQueue.insert(it.base(), std::move(focusEntry));
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001243}
1244
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001245void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime, std::shared_ptr<FocusEntry> entry) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05001246 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001247 if (channel == nullptr) {
1248 return; // Window has gone away
1249 }
1250 InputTarget target;
1251 target.inputChannel = channel;
1252 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1253 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001254 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
1255 channel->getName();
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001256 std::string reason = std::string("reason=").append(entry->reason);
1257 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001258 dispatchEventLocked(currentTime, entry, {target});
1259}
1260
Prabir Pradhan99987712020-11-10 18:43:05 -08001261void InputDispatcher::dispatchPointerCaptureChangedLocked(
1262 nsecs_t currentTime, const std::shared_ptr<PointerCaptureChangedEntry>& entry,
1263 DropReason& dropReason) {
1264 const bool haveWindowWithPointerCapture = mWindowTokenWithPointerCapture != nullptr;
1265 if (entry->pointerCaptureEnabled == haveWindowWithPointerCapture) {
1266 LOG_ALWAYS_FATAL_IF(mFocusedWindowRequestedPointerCapture,
1267 "The Pointer Capture state has already been dispatched to the window.");
1268 // Pointer capture was already forcefully disabled because of focus change.
1269 dropReason = DropReason::NOT_DROPPED;
1270 return;
1271 }
1272
1273 // Set drop reason for early returns
1274 dropReason = DropReason::NO_POINTER_CAPTURE;
1275
1276 sp<IBinder> token;
1277 if (entry->pointerCaptureEnabled) {
1278 // Enable Pointer Capture
1279 if (!mFocusedWindowRequestedPointerCapture) {
1280 // This can happen if a window requests capture and immediately releases capture.
1281 ALOGW("No window requested Pointer Capture.");
1282 return;
1283 }
1284 token = getValueByKey(mFocusedWindowTokenByDisplay, mFocusedDisplayId);
1285 LOG_ALWAYS_FATAL_IF(!token, "Cannot find focused window for Pointer Capture.");
1286 mWindowTokenWithPointerCapture = token;
1287 } else {
1288 // Disable Pointer Capture
1289 token = mWindowTokenWithPointerCapture;
1290 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan7d030382020-12-21 07:58:35 -08001291 if (mFocusedWindowRequestedPointerCapture) {
1292 mFocusedWindowRequestedPointerCapture = false;
1293 setPointerCaptureLocked(false);
1294 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001295 }
1296
1297 auto channel = getInputChannelLocked(token);
1298 if (channel == nullptr) {
1299 // Window has gone away, clean up Pointer Capture state.
1300 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan7d030382020-12-21 07:58:35 -08001301 if (mFocusedWindowRequestedPointerCapture) {
1302 mFocusedWindowRequestedPointerCapture = false;
1303 setPointerCaptureLocked(false);
1304 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001305 return;
1306 }
1307 InputTarget target;
1308 target.inputChannel = channel;
1309 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1310 entry->dispatchInProgress = true;
1311 dispatchEventLocked(currentTime, entry, {target});
1312
1313 dropReason = DropReason::NOT_DROPPED;
1314}
1315
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001316bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, std::shared_ptr<KeyEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001317 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001318 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001319 if (!entry->dispatchInProgress) {
1320 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1321 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1322 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1323 if (mKeyRepeatState.lastKeyEntry &&
Chris Ye2ad95392020-09-01 13:44:44 -07001324 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode &&
Michael Wrightd02c5b62014-02-10 15:10:22 -08001325 // We have seen two identical key downs in a row which indicates that the device
1326 // driver is automatically generating key repeats itself. We take note of the
1327 // repeat here, but we disable our own next key repeat timer since it is clear that
1328 // we will not need to synthesize key repeats ourselves.
Chris Ye2ad95392020-09-01 13:44:44 -07001329 mKeyRepeatState.lastKeyEntry->deviceId == entry->deviceId) {
1330 // Make sure we don't get key down from a different device. If a different
1331 // device Id has same key pressed down, the new device Id will replace the
1332 // current one to hold the key repeat with repeat count reset.
1333 // In the future when got a KEY_UP on the device id, drop it and do not
1334 // stop the key repeat on current device.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001335 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1336 resetKeyRepeatLocked();
1337 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
1338 } else {
1339 // Not a repeat. Save key down state in case we do see a repeat later.
1340 resetKeyRepeatLocked();
1341 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1342 }
1343 mKeyRepeatState.lastKeyEntry = entry;
Chris Ye2ad95392020-09-01 13:44:44 -07001344 } else if (entry->action == AKEY_EVENT_ACTION_UP && mKeyRepeatState.lastKeyEntry &&
1345 mKeyRepeatState.lastKeyEntry->deviceId != entry->deviceId) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001346 // The key on device 'deviceId' is still down, do not stop key repeat
Chris Ye2ad95392020-09-01 13:44:44 -07001347#if DEBUG_INBOUND_EVENT_DETAILS
1348 ALOGD("deviceId=%d got KEY_UP as stale", entry->deviceId);
1349#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001350 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001351 resetKeyRepeatLocked();
1352 }
1353
1354 if (entry->repeatCount == 1) {
1355 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1356 } else {
1357 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1358 }
1359
1360 entry->dispatchInProgress = true;
1361
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001362 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001363 }
1364
1365 // Handle case where the policy asked us to try again later last time.
1366 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
1367 if (currentTime < entry->interceptKeyWakeupTime) {
1368 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1369 *nextWakeupTime = entry->interceptKeyWakeupTime;
1370 }
1371 return false; // wait until next wakeup
1372 }
1373 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
1374 entry->interceptKeyWakeupTime = 0;
1375 }
1376
1377 // Give the policy a chance to intercept the key.
1378 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
1379 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001380 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
Siarhei Vishniakou49a350a2019-07-26 18:44:23 -07001381 &InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible);
Vishnu Nairad321cd2020-08-20 16:40:21 -07001382 sp<IBinder> focusedWindowToken =
1383 getValueByKey(mFocusedWindowTokenByDisplay, getTargetDisplayId(*entry));
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06001384 commandEntry->connectionToken = focusedWindowToken;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001385 commandEntry->keyEntry = entry;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001386 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001387 return false; // wait for the command to run
1388 } else {
1389 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
1390 }
1391 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001392 if (*dropReason == DropReason::NOT_DROPPED) {
1393 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001394 }
1395 }
1396
1397 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001398 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001399 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001400 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1401 : InputEventInjectionResult::FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001402 mReporter->reportDroppedKey(entry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001403 return true;
1404 }
1405
1406 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001407 std::vector<InputTarget> inputTargets;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001408 InputEventInjectionResult injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001409 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001410 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001411 return false;
1412 }
1413
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001414 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001415 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001416 return true;
1417 }
1418
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001419 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001420 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001421
1422 // Dispatch the key.
1423 dispatchEventLocked(currentTime, entry, inputTargets);
1424 return true;
1425}
1426
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001427void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001428#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01001429 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001430 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1431 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001432 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1433 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
1434 entry.repeatCount, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001435#endif
1436}
1437
Chris Yef59a2f42020-10-16 12:55:26 -07001438void InputDispatcher::doNotifySensorLockedInterruptible(CommandEntry* commandEntry) {
1439 mLock.unlock();
1440
1441 const std::shared_ptr<SensorEntry>& entry = commandEntry->sensorEntry;
1442 if (entry->accuracyChanged) {
1443 mPolicy->notifySensorAccuracy(entry->deviceId, entry->sensorType, entry->accuracy);
1444 }
1445 mPolicy->notifySensorEvent(entry->deviceId, entry->sensorType, entry->accuracy,
1446 entry->hwTimestamp, entry->values);
1447 mLock.lock();
1448}
1449
1450void InputDispatcher::dispatchSensorLocked(nsecs_t currentTime, std::shared_ptr<SensorEntry> entry,
1451 DropReason* dropReason, nsecs_t* nextWakeupTime) {
1452#if DEBUG_OUTBOUND_EVENT_DETAILS
1453 ALOGD("notifySensorEvent eventTime=%" PRId64 ", hwTimestamp=%" PRId64 ", deviceId=%d, "
1454 "source=0x%x, sensorType=%s",
1455 entry->eventTime, entry->hwTimestamp, entry->deviceId, entry->source,
1456 NamedEnum::string(sensorType).c_str());
1457#endif
1458 std::unique_ptr<CommandEntry> commandEntry =
1459 std::make_unique<CommandEntry>(&InputDispatcher::doNotifySensorLockedInterruptible);
1460 commandEntry->sensorEntry = entry;
1461 postCommandLocked(std::move(commandEntry));
1462}
1463
1464bool InputDispatcher::flushSensor(int deviceId, InputDeviceSensorType sensorType) {
1465#if DEBUG_OUTBOUND_EVENT_DETAILS
1466 ALOGD("flushSensor deviceId=%d, sensorType=%s", deviceId,
1467 NamedEnum::string(sensorType).c_str());
1468#endif
1469 { // acquire lock
1470 std::scoped_lock _l(mLock);
1471
1472 for (auto it = mInboundQueue.begin(); it != mInboundQueue.end(); it++) {
1473 std::shared_ptr<EventEntry> entry = *it;
1474 if (entry->type == EventEntry::Type::SENSOR) {
1475 it = mInboundQueue.erase(it);
1476 releaseInboundEventLocked(entry);
1477 }
1478 }
1479 }
1480 return true;
1481}
1482
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001483bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, std::shared_ptr<MotionEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001484 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001485 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001486 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001487 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001488 entry->dispatchInProgress = true;
1489
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001490 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001491 }
1492
1493 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001494 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001495 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001496 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1497 : InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001498 return true;
1499 }
1500
1501 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
1502
1503 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001504 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001505
1506 bool conflictingPointerActions = false;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001507 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001508 if (isPointerEvent) {
1509 // Pointer event. (eg. touchscreen)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001510 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001511 findTouchedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001512 &conflictingPointerActions);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001513 } else {
1514 // Non touch event. (eg. trackball)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001515 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001516 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001517 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001518 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001519 return false;
1520 }
1521
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001522 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001523 if (injectionResult == InputEventInjectionResult::PERMISSION_DENIED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001524 ALOGW("Permission denied, dropping the motion (isPointer=%s)", toString(isPointerEvent));
1525 return true;
1526 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001527 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001528 CancelationOptions::Mode mode(isPointerEvent
1529 ? CancelationOptions::CANCEL_POINTER_EVENTS
1530 : CancelationOptions::CANCEL_NON_POINTER_EVENTS);
1531 CancelationOptions options(mode, "input event injection failed");
1532 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001533 return true;
1534 }
1535
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001536 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001537 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001538
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001539 if (isPointerEvent) {
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07001540 std::unordered_map<int32_t, TouchState>::iterator it =
1541 mTouchStatesByDisplay.find(entry->displayId);
1542 if (it != mTouchStatesByDisplay.end()) {
1543 const TouchState& state = it->second;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001544 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001545 // The event has gone through these portal windows, so we add monitoring targets of
1546 // the corresponding displays as well.
1547 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001548 const InputWindowInfo* windowInfo = state.portalWindows[i]->getInfo();
Michael Wright3dd60e22019-03-27 22:06:44 +00001549 addGlobalMonitoringTargetsLocked(inputTargets, windowInfo->portalToDisplayId,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001550 -windowInfo->frameLeft, -windowInfo->frameTop);
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001551 }
1552 }
1553 }
1554 }
1555
Michael Wrightd02c5b62014-02-10 15:10:22 -08001556 // Dispatch the motion.
1557 if (conflictingPointerActions) {
1558 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001559 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001560 synthesizeCancelationEventsForAllConnectionsLocked(options);
1561 }
1562 dispatchEventLocked(currentTime, entry, inputTargets);
1563 return true;
1564}
1565
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001566void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001567#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08001568 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001569 ", policyFlags=0x%x, "
1570 "action=0x%x, actionButton=0x%x, flags=0x%x, "
1571 "metaState=0x%x, buttonState=0x%x,"
1572 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001573 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1574 entry.action, entry.actionButton, entry.flags, entry.metaState, entry.buttonState,
1575 entry.edgeFlags, entry.xPrecision, entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001576
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001577 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001578 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001579 "x=%f, y=%f, pressure=%f, size=%f, "
1580 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1581 "orientation=%f",
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001582 i, entry.pointerProperties[i].id, entry.pointerProperties[i].toolType,
1583 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1584 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1585 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1586 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1587 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1588 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1589 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1590 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1591 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001592 }
1593#endif
1594}
1595
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001596void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
1597 std::shared_ptr<EventEntry> eventEntry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001598 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001599 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001600#if DEBUG_DISPATCH_CYCLE
1601 ALOGD("dispatchEventToCurrentInputTargets");
1602#endif
1603
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001604 updateInteractionTokensLocked(*eventEntry, inputTargets);
1605
Michael Wrightd02c5b62014-02-10 15:10:22 -08001606 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1607
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001608 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001609
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001610 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001611 sp<Connection> connection =
1612 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001613 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08001614 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001615 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001616 if (DEBUG_FOCUS) {
1617 ALOGD("Dropping event delivery to target with channel '%s' because it "
1618 "is no longer registered with the input dispatcher.",
1619 inputTarget.inputChannel->getName().c_str());
1620 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001621 }
1622 }
1623}
1624
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001625void InputDispatcher::cancelEventsForAnrLocked(const sp<Connection>& connection) {
1626 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
1627 // If the policy decides to close the app, we will get a channel removal event via
1628 // unregisterInputChannel, and will clean up the connection that way. We are already not
1629 // sending new pointers to the connection when it blocked, but focused events will continue to
1630 // pile up.
1631 ALOGW("Canceling events for %s because it is unresponsive",
1632 connection->inputChannel->getName().c_str());
1633 if (connection->status == Connection::STATUS_NORMAL) {
1634 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1635 "application not responding");
1636 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001637 }
1638}
1639
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001640void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001641 if (DEBUG_FOCUS) {
1642 ALOGD("Resetting ANR timeouts.");
1643 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001644
1645 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001646 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07001647 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001648}
1649
Tiger Huang721e26f2018-07-24 22:26:19 +08001650/**
1651 * Get the display id that the given event should go to. If this event specifies a valid display id,
1652 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1653 * Focused display is the display that the user most recently interacted with.
1654 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001655int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001656 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001657 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001658 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001659 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1660 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001661 break;
1662 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001663 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001664 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1665 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001666 break;
1667 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001668 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001669 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001670 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07001671 case EventEntry::Type::DEVICE_RESET:
1672 case EventEntry::Type::SENSOR: {
1673 ALOGE("%s events do not have a target display", NamedEnum::string(entry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001674 return ADISPLAY_ID_NONE;
1675 }
Tiger Huang721e26f2018-07-24 22:26:19 +08001676 }
1677 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1678}
1679
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001680bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
1681 const char* focusedWindowName) {
1682 if (mAnrTracker.empty()) {
1683 // already processed all events that we waited for
1684 mKeyIsWaitingForEventsTimeout = std::nullopt;
1685 return false;
1686 }
1687
1688 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
1689 // Start the timer
1690 ALOGD("Waiting to send key to %s because there are unprocessed events that may cause "
1691 "focus to change",
1692 focusedWindowName);
Siarhei Vishniakou70622952020-07-30 11:17:23 -05001693 mKeyIsWaitingForEventsTimeout = currentTime +
1694 std::chrono::duration_cast<std::chrono::nanoseconds>(KEY_WAITING_FOR_EVENTS_TIMEOUT)
1695 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001696 return true;
1697 }
1698
1699 // We still have pending events, and already started the timer
1700 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
1701 return true; // Still waiting
1702 }
1703
1704 // Waited too long, and some connection still hasn't processed all motions
1705 // Just send the key to the focused window
1706 ALOGW("Dispatching key to %s even though there are other unprocessed events",
1707 focusedWindowName);
1708 mKeyIsWaitingForEventsTimeout = std::nullopt;
1709 return false;
1710}
1711
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001712InputEventInjectionResult InputDispatcher::findFocusedWindowTargetsLocked(
1713 nsecs_t currentTime, const EventEntry& entry, std::vector<InputTarget>& inputTargets,
1714 nsecs_t* nextWakeupTime) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001715 std::string reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001716
Tiger Huang721e26f2018-07-24 22:26:19 +08001717 int32_t displayId = getTargetDisplayId(entry);
Vishnu Nairad321cd2020-08-20 16:40:21 -07001718 sp<InputWindowHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07001719 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08001720 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1721
Michael Wrightd02c5b62014-02-10 15:10:22 -08001722 // If there is no currently focused window and no focused application
1723 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001724 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
1725 ALOGI("Dropping %s event because there is no focused window or focused application in "
1726 "display %" PRId32 ".",
Chris Yef59a2f42020-10-16 12:55:26 -07001727 NamedEnum::string(entry.type).c_str(), displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001728 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001729 }
1730
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001731 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
1732 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
1733 // start interacting with another application via touch (app switch). This code can be removed
1734 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
1735 // an app is expected to have a focused window.
1736 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
1737 if (!mNoFocusedWindowTimeoutTime.has_value()) {
1738 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001739 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
1740 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
1741 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001742 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05001743 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001744 ALOGW("Waiting because no window has focus but %s may eventually add a "
1745 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001746 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001747 *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001748 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001749 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
1750 // Already raised ANR. Drop the event
1751 ALOGE("Dropping %s event because there is no focused window",
Chris Yef59a2f42020-10-16 12:55:26 -07001752 NamedEnum::string(entry.type).c_str());
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001753 return InputEventInjectionResult::FAILED;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001754 } else {
1755 // Still waiting for the focused window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001756 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001757 }
1758 }
1759
1760 // we have a valid, non-null focused window
1761 resetNoFocusedWindowTimeoutLocked();
1762
Michael Wrightd02c5b62014-02-10 15:10:22 -08001763 // Check permissions.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001764 if (!checkInjectionPermission(focusedWindowHandle, entry.injectionState)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001765 return InputEventInjectionResult::PERMISSION_DENIED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001766 }
1767
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001768 if (focusedWindowHandle->getInfo()->paused) {
1769 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001770 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001771 }
1772
1773 // If the event is a key event, then we must wait for all previous events to
1774 // complete before delivering it because previous events may have the
1775 // side-effect of transferring focus to a different window and we want to
1776 // ensure that the following keys are sent to the new window.
1777 //
1778 // Suppose the user touches a button in a window then immediately presses "A".
1779 // If the button causes a pop-up window to appear then we want to ensure that
1780 // the "A" key is delivered to the new pop-up window. This is because users
1781 // often anticipate pending UI changes when typing on a keyboard.
1782 // To obtain this behavior, we must serialize key events with respect to all
1783 // prior input events.
1784 if (entry.type == EventEntry::Type::KEY) {
1785 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
1786 *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001787 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001788 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001789 }
1790
1791 // Success! Output targets.
Tiger Huang721e26f2018-07-24 22:26:19 +08001792 addWindowTargetLocked(focusedWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001793 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS,
1794 BitSet32(0), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001795
1796 // Done.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001797 return InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001798}
1799
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001800/**
1801 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
1802 * that are currently unresponsive.
1803 */
1804std::vector<TouchedMonitor> InputDispatcher::selectResponsiveMonitorsLocked(
1805 const std::vector<TouchedMonitor>& monitors) const {
1806 std::vector<TouchedMonitor> responsiveMonitors;
1807 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
1808 [this](const TouchedMonitor& monitor) REQUIRES(mLock) {
1809 sp<Connection> connection = getConnectionLocked(
1810 monitor.monitor.inputChannel->getConnectionToken());
1811 if (connection == nullptr) {
1812 ALOGE("Could not find connection for monitor %s",
1813 monitor.monitor.inputChannel->getName().c_str());
1814 return false;
1815 }
1816 if (!connection->responsive) {
1817 ALOGW("Unresponsive monitor %s will not get the new gesture",
1818 connection->inputChannel->getName().c_str());
1819 return false;
1820 }
1821 return true;
1822 });
1823 return responsiveMonitors;
1824}
1825
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001826InputEventInjectionResult InputDispatcher::findTouchedWindowTargetsLocked(
1827 nsecs_t currentTime, const MotionEntry& entry, std::vector<InputTarget>& inputTargets,
1828 nsecs_t* nextWakeupTime, bool* outConflictingPointerActions) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001829 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001830 enum InjectionPermission {
1831 INJECTION_PERMISSION_UNKNOWN,
1832 INJECTION_PERMISSION_GRANTED,
1833 INJECTION_PERMISSION_DENIED
1834 };
1835
Michael Wrightd02c5b62014-02-10 15:10:22 -08001836 // For security reasons, we defer updating the touch state until we are sure that
1837 // event injection will be allowed.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001838 int32_t displayId = entry.displayId;
1839 int32_t action = entry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001840 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
1841
1842 // Update the touch state as needed based on the properties of the touch event.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001843 InputEventInjectionResult injectionResult = InputEventInjectionResult::PENDING;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001844 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
Garfield Tandf26e862020-07-01 20:18:19 -07001845 sp<InputWindowHandle> newHoverWindowHandle(mLastHoverWindowHandle);
1846 sp<InputWindowHandle> newTouchedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001847
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001848 // Copy current touch state into tempTouchState.
1849 // This state will be used to update mTouchStatesByDisplay at the end of this function.
1850 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07001851 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001852 TouchState tempTouchState;
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07001853 std::unordered_map<int32_t, TouchState>::iterator oldStateIt =
1854 mTouchStatesByDisplay.find(displayId);
1855 if (oldStateIt != mTouchStatesByDisplay.end()) {
1856 oldState = &(oldStateIt->second);
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001857 tempTouchState.copyFrom(*oldState);
Jeff Brownf086ddb2014-02-11 14:28:48 -08001858 }
1859
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001860 bool isSplit = tempTouchState.split;
1861 bool switchedDevice = tempTouchState.deviceId >= 0 && tempTouchState.displayId >= 0 &&
1862 (tempTouchState.deviceId != entry.deviceId || tempTouchState.source != entry.source ||
1863 tempTouchState.displayId != displayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001864 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
1865 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
1866 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
1867 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN ||
1868 maskedAction == AMOTION_EVENT_ACTION_SCROLL || isHoverAction);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001869 const bool isFromMouse = entry.source == AINPUT_SOURCE_MOUSE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001870 bool wrongDevice = false;
1871 if (newGesture) {
1872 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001873 if (switchedDevice && tempTouchState.down && !down && !isHoverAction) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001874 ALOGI("Dropping event because a pointer for a different device is already down "
1875 "in display %" PRId32,
1876 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001877 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001878 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001879 switchedDevice = false;
1880 wrongDevice = true;
1881 goto Failed;
1882 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001883 tempTouchState.reset();
1884 tempTouchState.down = down;
1885 tempTouchState.deviceId = entry.deviceId;
1886 tempTouchState.source = entry.source;
1887 tempTouchState.displayId = displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001888 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001889 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001890 ALOGI("Dropping move event because a pointer for a different device is already active "
1891 "in display %" PRId32,
1892 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001893 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001894 injectionResult = InputEventInjectionResult::PERMISSION_DENIED;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001895 switchedDevice = false;
1896 wrongDevice = true;
1897 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001898 }
1899
1900 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
1901 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
1902
Garfield Tan00f511d2019-06-12 16:55:40 -07001903 int32_t x;
1904 int32_t y;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001905 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Garfield Tan00f511d2019-06-12 16:55:40 -07001906 // Always dispatch mouse events to cursor position.
1907 if (isFromMouse) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001908 x = int32_t(entry.xCursorPosition);
1909 y = int32_t(entry.yCursorPosition);
Garfield Tan00f511d2019-06-12 16:55:40 -07001910 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001911 x = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X));
1912 y = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y));
Garfield Tan00f511d2019-06-12 16:55:40 -07001913 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001914 bool isDown = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Garfield Tandf26e862020-07-01 20:18:19 -07001915 newTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001916 findTouchedWindowAtLocked(displayId, x, y, &tempTouchState,
1917 isDown /*addOutsideTargets*/, true /*addPortalWindows*/);
Michael Wright3dd60e22019-03-27 22:06:44 +00001918
1919 std::vector<TouchedMonitor> newGestureMonitors = isDown
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001920 ? findTouchedGestureMonitorsLocked(displayId, tempTouchState.portalWindows)
Michael Wright3dd60e22019-03-27 22:06:44 +00001921 : std::vector<TouchedMonitor>{};
Michael Wrightd02c5b62014-02-10 15:10:22 -08001922
Michael Wrightd02c5b62014-02-10 15:10:22 -08001923 // Figure out whether splitting will be allowed for this window.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001924 if (newTouchedWindowHandle != nullptr &&
1925 newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Garfield Tanaddb02b2019-06-25 16:36:13 -07001926 // New window supports splitting, but we should never split mouse events.
1927 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001928 } else if (isSplit) {
1929 // New window does not support splitting but we have already split events.
1930 // Ignore the new window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001931 newTouchedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001932 }
1933
1934 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001935 if (newTouchedWindowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001936 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001937 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001938 }
1939
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001940 if (newTouchedWindowHandle != nullptr && newTouchedWindowHandle->getInfo()->paused) {
1941 ALOGI("Not sending touch event to %s because it is paused",
1942 newTouchedWindowHandle->getName().c_str());
1943 newTouchedWindowHandle = nullptr;
1944 }
1945
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001946 // Ensure the window has a connection and the connection is responsive
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001947 if (newTouchedWindowHandle != nullptr) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001948 const bool isResponsive = hasResponsiveConnectionLocked(*newTouchedWindowHandle);
1949 if (!isResponsive) {
1950 ALOGW("%s will not receive the new gesture at %" PRIu64,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001951 newTouchedWindowHandle->getName().c_str(), entry.eventTime);
1952 newTouchedWindowHandle = nullptr;
1953 }
1954 }
1955
Bernardo Rufinoea97d182020-08-19 14:43:14 +01001956 // Drop events that can't be trusted due to occlusion
1957 if (newTouchedWindowHandle != nullptr &&
1958 mBlockUntrustedTouchesMode != BlockUntrustedTouchesMode::DISABLED) {
1959 TouchOcclusionInfo occlusionInfo =
1960 computeTouchOcclusionInfoLocked(newTouchedWindowHandle, x, y);
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00001961 if (!isTouchTrustedLocked(occlusionInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00001962 if (DEBUG_TOUCH_OCCLUSION) {
1963 ALOGD("Stack of obscuring windows during untrusted touch (%d, %d):", x, y);
1964 for (const auto& log : occlusionInfo.debugInfo) {
1965 ALOGD("%s", log.c_str());
1966 }
1967 }
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00001968 onUntrustedTouchLocked(occlusionInfo.obscuringPackage);
1969 if (mBlockUntrustedTouchesMode == BlockUntrustedTouchesMode::BLOCK) {
1970 ALOGW("Dropping untrusted touch event due to %s/%d",
1971 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid);
1972 newTouchedWindowHandle = nullptr;
1973 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01001974 }
1975 }
1976
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001977 // Also don't send the new touch event to unresponsive gesture monitors
1978 newGestureMonitors = selectResponsiveMonitorsLocked(newGestureMonitors);
1979
Michael Wright3dd60e22019-03-27 22:06:44 +00001980 if (newTouchedWindowHandle == nullptr && newGestureMonitors.empty()) {
1981 ALOGI("Dropping event because there is no touchable window or gesture monitor at "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001982 "(%d, %d) in display %" PRId32 ".",
1983 x, y, displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001984 injectionResult = InputEventInjectionResult::FAILED;
Michael Wright3dd60e22019-03-27 22:06:44 +00001985 goto Failed;
1986 }
1987
1988 if (newTouchedWindowHandle != nullptr) {
1989 // Set target flags.
1990 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
1991 if (isSplit) {
1992 targetFlags |= InputTarget::FLAG_SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001993 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001994 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1995 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1996 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
1997 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1998 }
1999
2000 // Update hover state.
Garfield Tandf26e862020-07-01 20:18:19 -07002001 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
2002 newHoverWindowHandle = nullptr;
2003 } else if (isHoverAction) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002004 newHoverWindowHandle = newTouchedWindowHandle;
Michael Wright3dd60e22019-03-27 22:06:44 +00002005 }
2006
2007 // Update the temporary touch state.
2008 BitSet32 pointerIds;
2009 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002010 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wright3dd60e22019-03-27 22:06:44 +00002011 pointerIds.markBit(pointerId);
2012 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002013 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002014 }
2015
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002016 tempTouchState.addGestureMonitors(newGestureMonitors);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002017 } else {
2018 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
2019
2020 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002021 if (!tempTouchState.down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002022 if (DEBUG_FOCUS) {
2023 ALOGD("Dropping event because the pointer is not down or we previously "
2024 "dropped the pointer down event in display %" PRId32,
2025 displayId);
2026 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002027 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002028 goto Failed;
2029 }
2030
2031 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002032 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002033 tempTouchState.isSlippery()) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002034 int32_t x = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
2035 int32_t y = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002036
2037 sp<InputWindowHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002038 tempTouchState.getFirstForegroundWindowHandle();
Garfield Tandf26e862020-07-01 20:18:19 -07002039 newTouchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y, &tempTouchState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002040 if (oldTouchedWindowHandle != newTouchedWindowHandle &&
2041 oldTouchedWindowHandle != nullptr && newTouchedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002042 if (DEBUG_FOCUS) {
2043 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
2044 oldTouchedWindowHandle->getName().c_str(),
2045 newTouchedWindowHandle->getName().c_str(), displayId);
2046 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002047 // Make a slippery exit from the old window.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002048 tempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
2049 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT,
2050 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002051
2052 // Make a slippery entrance into the new window.
2053 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
2054 isSplit = true;
2055 }
2056
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002057 int32_t targetFlags =
2058 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002059 if (isSplit) {
2060 targetFlags |= InputTarget::FLAG_SPLIT;
2061 }
2062 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
2063 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002064 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
2065 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002066 }
2067
2068 BitSet32 pointerIds;
2069 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002070 pointerIds.markBit(entry.pointerProperties[0].id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002071 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002072 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002073 }
2074 }
2075 }
2076
2077 if (newHoverWindowHandle != mLastHoverWindowHandle) {
Garfield Tandf26e862020-07-01 20:18:19 -07002078 // Let the previous window know that the hover sequence is over, unless we already did it
2079 // when dispatching it as is to newTouchedWindowHandle.
2080 if (mLastHoverWindowHandle != nullptr &&
2081 (maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT ||
2082 mLastHoverWindowHandle != newTouchedWindowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002083#if DEBUG_HOVER
2084 ALOGD("Sending hover exit event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002085 mLastHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002086#endif
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002087 tempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
2088 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002089 }
2090
Garfield Tandf26e862020-07-01 20:18:19 -07002091 // Let the new window know that the hover sequence is starting, unless we already did it
2092 // when dispatching it as is to newTouchedWindowHandle.
2093 if (newHoverWindowHandle != nullptr &&
2094 (maskedAction != AMOTION_EVENT_ACTION_HOVER_ENTER ||
2095 newHoverWindowHandle != newTouchedWindowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002096#if DEBUG_HOVER
2097 ALOGD("Sending hover enter event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002098 newHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002099#endif
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002100 tempTouchState.addOrUpdateWindow(newHoverWindowHandle,
2101 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER,
2102 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002103 }
2104 }
2105
2106 // Check permission to inject into all touched foreground windows and ensure there
2107 // is at least one touched foreground window.
2108 {
2109 bool haveForegroundWindow = false;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002110 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002111 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
2112 haveForegroundWindow = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002113 if (!checkInjectionPermission(touchedWindow.windowHandle, entry.injectionState)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002114 injectionResult = InputEventInjectionResult::PERMISSION_DENIED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002115 injectionPermission = INJECTION_PERMISSION_DENIED;
2116 goto Failed;
2117 }
2118 }
2119 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002120 bool hasGestureMonitor = !tempTouchState.gestureMonitors.empty();
Michael Wright3dd60e22019-03-27 22:06:44 +00002121 if (!haveForegroundWindow && !hasGestureMonitor) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002122 ALOGI("Dropping event because there is no touched foreground window in display "
2123 "%" PRId32 " or gesture monitor to receive it.",
2124 displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002125 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002126 goto Failed;
2127 }
2128
2129 // Permission granted to injection into all touched foreground windows.
2130 injectionPermission = INJECTION_PERMISSION_GRANTED;
2131 }
2132
2133 // Check whether windows listening for outside touches are owned by the same UID. If it is
2134 // set the policy flag that we will not reveal coordinate information to this window.
2135 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2136 sp<InputWindowHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002137 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002138 if (foregroundWindowHandle) {
2139 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002140 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002141 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2142 sp<InputWindowHandle> inputWindowHandle = touchedWindow.windowHandle;
2143 if (inputWindowHandle->getInfo()->ownerUid != foregroundWindowUid) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002144 tempTouchState.addOrUpdateWindow(inputWindowHandle,
2145 InputTarget::FLAG_ZERO_COORDS,
2146 BitSet32(0));
Michael Wright3dd60e22019-03-27 22:06:44 +00002147 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002148 }
2149 }
2150 }
2151 }
2152
Michael Wrightd02c5b62014-02-10 15:10:22 -08002153 // If this is the first pointer going down and the touched window has a wallpaper
2154 // then also add the touched wallpaper windows so they are locked in for the duration
2155 // of the touch gesture.
2156 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
2157 // engine only supports touch events. We would need to add a mechanism similar
2158 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
2159 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2160 sp<InputWindowHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002161 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002162 if (foregroundWindowHandle && foregroundWindowHandle->getInfo()->hasWallpaper) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07002163 const std::vector<sp<InputWindowHandle>>& windowHandles =
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002164 getWindowHandlesLocked(displayId);
2165 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002166 const InputWindowInfo* info = windowHandle->getInfo();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002167 if (info->displayId == displayId &&
Michael Wright44753b12020-07-08 13:48:11 +01002168 windowHandle->getInfo()->type == InputWindowInfo::Type::WALLPAPER) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002169 tempTouchState
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002170 .addOrUpdateWindow(windowHandle,
2171 InputTarget::FLAG_WINDOW_IS_OBSCURED |
2172 InputTarget::
2173 FLAG_WINDOW_IS_PARTIALLY_OBSCURED |
2174 InputTarget::FLAG_DISPATCH_AS_IS,
2175 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002176 }
2177 }
2178 }
2179 }
2180
2181 // Success! Output targets.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002182 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002183
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002184 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002185 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002186 touchedWindow.pointerIds, inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002187 }
2188
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002189 for (const TouchedMonitor& touchedMonitor : tempTouchState.gestureMonitors) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002190 addMonitoringTargetLocked(touchedMonitor.monitor, touchedMonitor.xOffset,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002191 touchedMonitor.yOffset, inputTargets);
Michael Wright3dd60e22019-03-27 22:06:44 +00002192 }
2193
Michael Wrightd02c5b62014-02-10 15:10:22 -08002194 // Drop the outside or hover touch windows since we will not care about them
2195 // in the next iteration.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002196 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002197
2198Failed:
2199 // Check injection permission once and for all.
2200 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002201 if (checkInjectionPermission(nullptr, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002202 injectionPermission = INJECTION_PERMISSION_GRANTED;
2203 } else {
2204 injectionPermission = INJECTION_PERMISSION_DENIED;
2205 }
2206 }
2207
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002208 if (injectionPermission != INJECTION_PERMISSION_GRANTED) {
2209 return injectionResult;
2210 }
2211
Michael Wrightd02c5b62014-02-10 15:10:22 -08002212 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002213 if (!wrongDevice) {
2214 if (switchedDevice) {
2215 if (DEBUG_FOCUS) {
2216 ALOGD("Conflicting pointer actions: Switched to a different device.");
2217 }
2218 *outConflictingPointerActions = true;
2219 }
2220
2221 if (isHoverAction) {
2222 // Started hovering, therefore no longer down.
2223 if (oldState && oldState->down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002224 if (DEBUG_FOCUS) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002225 ALOGD("Conflicting pointer actions: Hover received while pointer was "
2226 "down.");
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002227 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002228 *outConflictingPointerActions = true;
2229 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002230 tempTouchState.reset();
2231 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2232 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
2233 tempTouchState.deviceId = entry.deviceId;
2234 tempTouchState.source = entry.source;
2235 tempTouchState.displayId = displayId;
2236 }
2237 } else if (maskedAction == AMOTION_EVENT_ACTION_UP ||
2238 maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
2239 // All pointers up or canceled.
2240 tempTouchState.reset();
2241 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2242 // First pointer went down.
2243 if (oldState && oldState->down) {
2244 if (DEBUG_FOCUS) {
2245 ALOGD("Conflicting pointer actions: Down received while already down.");
2246 }
2247 *outConflictingPointerActions = true;
2248 }
2249 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2250 // One pointer went up.
2251 if (isSplit) {
2252 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2253 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002254
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002255 for (size_t i = 0; i < tempTouchState.windows.size();) {
2256 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2257 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
2258 touchedWindow.pointerIds.clearBit(pointerId);
2259 if (touchedWindow.pointerIds.isEmpty()) {
2260 tempTouchState.windows.erase(tempTouchState.windows.begin() + i);
2261 continue;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002262 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002263 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002264 i += 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002265 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002266 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002267 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002268
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002269 // Save changes unless the action was scroll in which case the temporary touch
2270 // state was only valid for this one action.
2271 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
2272 if (tempTouchState.displayId >= 0) {
2273 mTouchStatesByDisplay[displayId] = tempTouchState;
2274 } else {
2275 mTouchStatesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002276 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002277 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002278
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002279 // Update hover state.
2280 mLastHoverWindowHandle = newHoverWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002281 }
2282
Michael Wrightd02c5b62014-02-10 15:10:22 -08002283 return injectionResult;
2284}
2285
2286void InputDispatcher::addWindowTargetLocked(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002287 int32_t targetFlags, BitSet32 pointerIds,
2288 std::vector<InputTarget>& inputTargets) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002289 std::vector<InputTarget>::iterator it =
2290 std::find_if(inputTargets.begin(), inputTargets.end(),
2291 [&windowHandle](const InputTarget& inputTarget) {
2292 return inputTarget.inputChannel->getConnectionToken() ==
2293 windowHandle->getToken();
2294 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002295
Chavi Weingarten114b77f2020-01-15 22:35:10 +00002296 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002297
2298 if (it == inputTargets.end()) {
2299 InputTarget inputTarget;
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05002300 std::shared_ptr<InputChannel> inputChannel =
2301 getInputChannelLocked(windowHandle->getToken());
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002302 if (inputChannel == nullptr) {
2303 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
2304 return;
2305 }
2306 inputTarget.inputChannel = inputChannel;
2307 inputTarget.flags = targetFlags;
2308 inputTarget.globalScaleFactor = windowInfo->globalScaleFactor;
2309 inputTargets.push_back(inputTarget);
2310 it = inputTargets.end() - 1;
2311 }
2312
2313 ALOG_ASSERT(it->flags == targetFlags);
2314 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
2315
chaviw1ff3d1e2020-07-01 15:53:47 -07002316 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002317}
2318
Michael Wright3dd60e22019-03-27 22:06:44 +00002319void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002320 int32_t displayId, float xOffset,
2321 float yOffset) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002322 std::unordered_map<int32_t, std::vector<Monitor>>::const_iterator it =
2323 mGlobalMonitorsByDisplay.find(displayId);
2324
2325 if (it != mGlobalMonitorsByDisplay.end()) {
2326 const std::vector<Monitor>& monitors = it->second;
2327 for (const Monitor& monitor : monitors) {
2328 addMonitoringTargetLocked(monitor, xOffset, yOffset, inputTargets);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002329 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002330 }
2331}
2332
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002333void InputDispatcher::addMonitoringTargetLocked(const Monitor& monitor, float xOffset,
2334 float yOffset,
2335 std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002336 InputTarget target;
2337 target.inputChannel = monitor.inputChannel;
2338 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
chaviw1ff3d1e2020-07-01 15:53:47 -07002339 ui::Transform t;
2340 t.set(xOffset, yOffset);
2341 target.setDefaultPointerTransform(t);
Michael Wright3dd60e22019-03-27 22:06:44 +00002342 inputTargets.push_back(target);
2343}
2344
Michael Wrightd02c5b62014-02-10 15:10:22 -08002345bool InputDispatcher::checkInjectionPermission(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002346 const InjectionState* injectionState) {
2347 if (injectionState &&
2348 (windowHandle == nullptr ||
2349 windowHandle->getInfo()->ownerUid != injectionState->injectorUid) &&
2350 !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002351 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002352 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002353 "owned by uid %d",
2354 injectionState->injectorPid, injectionState->injectorUid,
2355 windowHandle->getName().c_str(), windowHandle->getInfo()->ownerUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002356 } else {
2357 ALOGW("Permission denied: injecting event from pid %d uid %d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002358 injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002359 }
2360 return false;
2361 }
2362 return true;
2363}
2364
Robert Carrc9bf1d32020-04-13 17:21:08 -07002365/**
2366 * Indicate whether one window handle should be considered as obscuring
2367 * another window handle. We only check a few preconditions. Actually
2368 * checking the bounds is left to the caller.
2369 */
2370static bool canBeObscuredBy(const sp<InputWindowHandle>& windowHandle,
2371 const sp<InputWindowHandle>& otherHandle) {
2372 // Compare by token so cloned layers aren't counted
2373 if (haveSameToken(windowHandle, otherHandle)) {
2374 return false;
2375 }
2376 auto info = windowHandle->getInfo();
2377 auto otherInfo = otherHandle->getInfo();
2378 if (!otherInfo->visible) {
2379 return false;
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002380 } else if (otherInfo->alpha == 0 &&
2381 otherInfo->flags.test(InputWindowInfo::Flag::NOT_TOUCHABLE)) {
2382 // Those act as if they were invisible, so we don't need to flag them.
2383 // We do want to potentially flag touchable windows even if they have 0
2384 // opacity, since they can consume touches and alter the effects of the
2385 // user interaction (eg. apps that rely on
2386 // FLAG_WINDOW_IS_PARTIALLY_OBSCURED should still be told about those
2387 // windows), hence we also check for FLAG_NOT_TOUCHABLE.
2388 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00002389 } else if (info->ownerUid == otherInfo->ownerUid) {
2390 // If ownerUid is the same we don't generate occlusion events as there
2391 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002392 return false;
Chris Yefcdff3e2020-05-10 15:16:04 -07002393 } else if (otherInfo->trustedOverlay) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002394 return false;
2395 } else if (otherInfo->displayId != info->displayId) {
2396 return false;
2397 }
2398 return true;
2399}
2400
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002401/**
2402 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
2403 * untrusted, one should check:
2404 *
2405 * 1. If result.hasBlockingOcclusion is true.
2406 * If it's, it means the touch should be blocked due to a window with occlusion mode of
2407 * BLOCK_UNTRUSTED.
2408 *
2409 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
2410 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
2411 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
2412 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
2413 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
2414 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
2415 *
2416 * If neither of those is true, then it means the touch can be allowed.
2417 */
2418InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
2419 const sp<InputWindowHandle>& windowHandle, int32_t x, int32_t y) const {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002420 const InputWindowInfo* windowInfo = windowHandle->getInfo();
2421 int32_t displayId = windowInfo->displayId;
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002422 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2423 TouchOcclusionInfo info;
2424 info.hasBlockingOcclusion = false;
2425 info.obscuringOpacity = 0;
2426 info.obscuringUid = -1;
2427 std::map<int32_t, float> opacityByUid;
2428 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
2429 if (windowHandle == otherHandle) {
2430 break; // All future windows are below us. Exit early.
2431 }
2432 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Bernardo Rufino1ff9d592021-01-18 16:58:57 +00002433 if (canBeObscuredBy(windowHandle, otherHandle) && otherInfo->frameContainsPoint(x, y) &&
2434 !haveSameApplicationToken(windowInfo, otherInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002435 if (DEBUG_TOUCH_OCCLUSION) {
2436 info.debugInfo.push_back(
2437 dumpWindowForTouchOcclusion(otherInfo, /* isTouchedWindow */ false));
2438 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002439 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
2440 // we perform the checks below to see if the touch can be propagated or not based on the
2441 // window's touch occlusion mode
2442 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
2443 info.hasBlockingOcclusion = true;
2444 info.obscuringUid = otherInfo->ownerUid;
2445 info.obscuringPackage = otherInfo->packageName;
2446 break;
2447 }
2448 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
2449 uint32_t uid = otherInfo->ownerUid;
2450 float opacity =
2451 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
2452 // Given windows A and B:
2453 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
2454 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
2455 opacityByUid[uid] = opacity;
2456 if (opacity > info.obscuringOpacity) {
2457 info.obscuringOpacity = opacity;
2458 info.obscuringUid = uid;
2459 info.obscuringPackage = otherInfo->packageName;
2460 }
2461 }
2462 }
2463 }
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002464 if (DEBUG_TOUCH_OCCLUSION) {
2465 info.debugInfo.push_back(
2466 dumpWindowForTouchOcclusion(windowInfo, /* isTouchedWindow */ true));
2467 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002468 return info;
2469}
2470
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002471std::string InputDispatcher::dumpWindowForTouchOcclusion(const InputWindowInfo* info,
2472 bool isTouchedWindow) const {
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00002473 return StringPrintf(INDENT2 "* %stype=%s, package=%s/%" PRId32 ", id=%" PRId32
2474 ", mode=%s, alpha=%.2f, "
Bernardo Rufinoc2f1fad2020-11-04 17:30:57 +00002475 "frame=[%" PRId32 ",%" PRId32 "][%" PRId32 ",%" PRId32
2476 "], touchableRegion=%s, window={%s}, applicationInfo=%s, "
2477 "flags={%s}, inputFeatures={%s}, hasToken=%s\n",
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002478 (isTouchedWindow) ? "[TOUCHED] " : "",
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00002479 NamedEnum::string(info->type, "%" PRId32).c_str(),
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00002480 info->packageName.c_str(), info->ownerUid, info->id,
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00002481 toString(info->touchOcclusionMode).c_str(), info->alpha, info->frameLeft,
2482 info->frameTop, info->frameRight, info->frameBottom,
2483 dumpRegion(info->touchableRegion).c_str(), info->name.c_str(),
Bernardo Rufinoc2f1fad2020-11-04 17:30:57 +00002484 info->applicationInfo.name.c_str(), info->flags.string().c_str(),
2485 info->inputFeatures.string().c_str(), toString(info->token != nullptr));
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002486}
2487
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002488bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
2489 if (occlusionInfo.hasBlockingOcclusion) {
2490 ALOGW("Untrusted touch due to occlusion by %s/%d", occlusionInfo.obscuringPackage.c_str(),
2491 occlusionInfo.obscuringUid);
2492 return false;
2493 }
2494 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
2495 ALOGW("Untrusted touch due to occlusion by %s/%d (obscuring opacity = "
2496 "%.2f, maximum allowed = %.2f)",
2497 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid,
2498 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
2499 return false;
2500 }
2501 return true;
2502}
2503
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002504bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<InputWindowHandle>& windowHandle,
2505 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002506 int32_t displayId = windowHandle->getInfo()->displayId;
Vishnu Nairad321cd2020-08-20 16:40:21 -07002507 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002508 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002509 if (windowHandle == otherHandle) {
2510 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002511 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002512 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002513 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002514 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002515 return true;
2516 }
2517 }
2518 return false;
2519}
2520
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002521bool InputDispatcher::isWindowObscuredLocked(const sp<InputWindowHandle>& windowHandle) const {
2522 int32_t displayId = windowHandle->getInfo()->displayId;
Vishnu Nairad321cd2020-08-20 16:40:21 -07002523 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002524 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002525 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002526 if (windowHandle == otherHandle) {
2527 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002528 }
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002529 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002530 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002531 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002532 return true;
2533 }
2534 }
2535 return false;
2536}
2537
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002538std::string InputDispatcher::getApplicationWindowLabel(
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05002539 const InputApplicationHandle* applicationHandle,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002540 const sp<InputWindowHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002541 if (applicationHandle != nullptr) {
2542 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002543 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002544 } else {
2545 return applicationHandle->getName();
2546 }
Yi Kong9b14ac62018-07-17 13:48:38 -07002547 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002548 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002549 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002550 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002551 }
2552}
2553
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002554void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Prabir Pradhan99987712020-11-10 18:43:05 -08002555 if (eventEntry.type == EventEntry::Type::FOCUS ||
2556 eventEntry.type == EventEntry::Type::POINTER_CAPTURE_CHANGED) {
2557 // Focus or pointer capture changed events are passed to apps, but do not represent user
2558 // activity.
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002559 return;
2560 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002561 int32_t displayId = getTargetDisplayId(eventEntry);
Vishnu Nairad321cd2020-08-20 16:40:21 -07002562 sp<InputWindowHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Tiger Huang721e26f2018-07-24 22:26:19 +08002563 if (focusedWindowHandle != nullptr) {
2564 const InputWindowInfo* info = focusedWindowHandle->getInfo();
Michael Wright44753b12020-07-08 13:48:11 +01002565 if (info->inputFeatures.test(InputWindowInfo::Feature::DISABLE_USER_ACTIVITY)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002566#if DEBUG_DISPATCH_CYCLE
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002567 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002568#endif
2569 return;
2570 }
2571 }
2572
2573 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002574 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002575 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002576 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
2577 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002578 return;
2579 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002580
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002581 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002582 eventType = USER_ACTIVITY_EVENT_TOUCH;
2583 }
2584 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002585 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002586 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002587 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
2588 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002589 return;
2590 }
2591 eventType = USER_ACTIVITY_EVENT_BUTTON;
2592 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002593 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002594 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002595 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08002596 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07002597 case EventEntry::Type::SENSOR:
Prabir Pradhan99987712020-11-10 18:43:05 -08002598 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002599 LOG_ALWAYS_FATAL("%s events are not user activity",
Chris Yef59a2f42020-10-16 12:55:26 -07002600 NamedEnum::string(eventEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002601 break;
2602 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002603 }
2604
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002605 std::unique_ptr<CommandEntry> commandEntry =
2606 std::make_unique<CommandEntry>(&InputDispatcher::doPokeUserActivityLockedInterruptible);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002607 commandEntry->eventTime = eventEntry.eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002608 commandEntry->userActivityEventType = eventType;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002609 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002610}
2611
2612void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002613 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002614 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002615 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002616 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002617 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002618 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002619 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002620 ATRACE_NAME(message.c_str());
2621 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002622#if DEBUG_DISPATCH_CYCLE
2623 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002624 "globalScaleFactor=%f, pointerIds=0x%x %s",
2625 connection->getInputChannelName().c_str(), inputTarget.flags,
2626 inputTarget.globalScaleFactor, inputTarget.pointerIds.value,
2627 inputTarget.getPointerInfoString().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002628#endif
2629
2630 // Skip this event if the connection status is not normal.
2631 // We don't want to enqueue additional outbound events if the connection is broken.
2632 if (connection->status != Connection::STATUS_NORMAL) {
2633#if DEBUG_DISPATCH_CYCLE
2634 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002635 connection->getInputChannelName().c_str(), connection->getStatusLabel());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002636#endif
2637 return;
2638 }
2639
2640 // Split a motion event if needed.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002641 if (inputTarget.flags & InputTarget::FLAG_SPLIT) {
2642 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
2643 "Entry type %s should not have FLAG_SPLIT",
Chris Yef59a2f42020-10-16 12:55:26 -07002644 NamedEnum::string(eventEntry->type).c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002645
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002646 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002647 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002648 std::unique_ptr<MotionEntry> splitMotionEntry =
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002649 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002650 if (!splitMotionEntry) {
2651 return; // split event was dropped
2652 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002653 if (DEBUG_FOCUS) {
2654 ALOGD("channel '%s' ~ Split motion event.",
2655 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002656 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002657 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002658 enqueueDispatchEntriesLocked(currentTime, connection, std::move(splitMotionEntry),
2659 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002660 return;
2661 }
2662 }
2663
2664 // Not splitting. Enqueue dispatch entries for the event as is.
2665 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
2666}
2667
2668void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002669 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002670 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002671 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002672 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002673 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002674 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002675 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002676 ATRACE_NAME(message.c_str());
2677 }
2678
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002679 bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002680
2681 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07002682 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002683 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002684 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002685 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07002686 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002687 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07002688 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002689 InputTarget::FLAG_DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07002690 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002691 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002692 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002693 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002694
2695 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002696 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002697 startDispatchCycleLocked(currentTime, connection);
2698 }
2699}
2700
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002701void InputDispatcher::enqueueDispatchEntryLocked(const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002702 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002703 const InputTarget& inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002704 int32_t dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002705 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002706 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
2707 connection->getInputChannelName().c_str(),
2708 dispatchModeToString(dispatchMode).c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002709 ATRACE_NAME(message.c_str());
2710 }
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002711 int32_t inputTargetFlags = inputTarget.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002712 if (!(inputTargetFlags & dispatchMode)) {
2713 return;
2714 }
2715 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
2716
2717 // This is a new event.
2718 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002719 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002720 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002721
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002722 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
2723 // different EventEntry than what was passed in.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002724 EventEntry& newEntry = *(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002725 // Apply target flags and update the connection's input state.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002726 switch (newEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002727 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002728 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002729 dispatchEntry->resolvedEventId = keyEntry.id;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002730 dispatchEntry->resolvedAction = keyEntry.action;
2731 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002732
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002733 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
2734 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002735#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002736 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key event",
2737 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002738#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002739 return; // skip the inconsistent event
2740 }
2741 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002742 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002743
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002744 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002745 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002746 // Assign a default value to dispatchEntry that will never be generated by InputReader,
2747 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
2748 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
2749 static_cast<int32_t>(IdGenerator::Source::OTHER);
2750 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002751 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2752 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
2753 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
2754 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
2755 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
2756 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2757 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
2758 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
2759 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
2760 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
2761 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002762 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002763 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002764 }
2765 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002766 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
2767 motionEntry.displayId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002768#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002769 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover enter "
2770 "event",
2771 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002772#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002773 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2774 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002775
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002776 dispatchEntry->resolvedFlags = motionEntry.flags;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002777 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
2778 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
2779 }
2780 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
2781 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2782 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002783
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002784 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
2785 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002786#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002787 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
2788 "event",
2789 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002790#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002791 return; // skip the inconsistent event
2792 }
2793
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002794 dispatchEntry->resolvedEventId =
2795 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
2796 ? mIdGenerator.nextId()
2797 : motionEntry.id;
2798 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
2799 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
2800 ") to MotionEvent(id=0x%" PRIx32 ").",
2801 motionEntry.id, dispatchEntry->resolvedEventId);
2802 ATRACE_NAME(message.c_str());
2803 }
2804
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002805 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002806 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002807
2808 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002809 }
Prabir Pradhan99987712020-11-10 18:43:05 -08002810 case EventEntry::Type::FOCUS:
2811 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002812 break;
2813 }
Chris Yef59a2f42020-10-16 12:55:26 -07002814 case EventEntry::Type::SENSOR: {
2815 LOG_ALWAYS_FATAL("SENSOR events should not go to apps via input channel");
2816 break;
2817 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002818 case EventEntry::Type::CONFIGURATION_CHANGED:
2819 case EventEntry::Type::DEVICE_RESET: {
2820 LOG_ALWAYS_FATAL("%s events should not go to apps",
Chris Yef59a2f42020-10-16 12:55:26 -07002821 NamedEnum::string(newEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002822 break;
2823 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002824 }
2825
2826 // Remember that we are waiting for this dispatch to complete.
2827 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002828 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002829 }
2830
2831 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002832 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002833 traceOutboundQueueLength(connection);
chaviw8c9cf542019-03-25 13:02:48 -07002834}
2835
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00002836/**
2837 * This function is purely for debugging. It helps us understand where the user interaction
2838 * was taking place. For example, if user is touching launcher, we will see a log that user
2839 * started interacting with launcher. In that example, the event would go to the wallpaper as well.
2840 * We will see both launcher and wallpaper in that list.
2841 * Once the interaction with a particular set of connections starts, no new logs will be printed
2842 * until the set of interacted connections changes.
2843 *
2844 * The following items are skipped, to reduce the logspam:
2845 * ACTION_OUTSIDE: any windows that are receiving ACTION_OUTSIDE are not logged
2846 * ACTION_UP: any windows that receive ACTION_UP are not logged (for both keys and motions).
2847 * This includes situations like the soft BACK button key. When the user releases (lifts up the
2848 * finger) the back button, then navigation bar will inject KEYCODE_BACK with ACTION_UP.
2849 * Both of those ACTION_UP events would not be logged
2850 * Monitors (both gesture and global): any gesture monitors or global monitors receiving events
2851 * will not be logged. This is omitted to reduce the amount of data printed.
2852 * If you see <none>, it's likely that one of the gesture monitors pilfered the event, and therefore
2853 * gesture monitor is the only connection receiving the remainder of the gesture.
2854 */
2855void InputDispatcher::updateInteractionTokensLocked(const EventEntry& entry,
2856 const std::vector<InputTarget>& targets) {
2857 // Skip ACTION_UP events, and all events other than keys and motions
2858 if (entry.type == EventEntry::Type::KEY) {
2859 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
2860 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
2861 return;
2862 }
2863 } else if (entry.type == EventEntry::Type::MOTION) {
2864 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
2865 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
2866 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
2867 return;
2868 }
2869 } else {
2870 return; // Not a key or a motion
2871 }
2872
2873 std::unordered_set<sp<IBinder>, IBinderHash> newConnectionTokens;
2874 std::vector<sp<Connection>> newConnections;
2875 for (const InputTarget& target : targets) {
2876 if ((target.flags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) ==
2877 InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2878 continue; // Skip windows that receive ACTION_OUTSIDE
2879 }
2880
2881 sp<IBinder> token = target.inputChannel->getConnectionToken();
2882 sp<Connection> connection = getConnectionLocked(token);
2883 if (connection == nullptr || connection->monitor) {
2884 continue; // We only need to keep track of the non-monitor connections.
2885 }
2886 newConnectionTokens.insert(std::move(token));
2887 newConnections.emplace_back(connection);
2888 }
2889 if (newConnectionTokens == mInteractionConnectionTokens) {
2890 return; // no change
2891 }
2892 mInteractionConnectionTokens = newConnectionTokens;
2893
2894 std::string windowList;
2895 for (const sp<Connection>& connection : newConnections) {
2896 windowList += connection->getWindowName() + ", ";
2897 }
2898 std::string message = "Interaction with windows: " + windowList;
2899 if (windowList.empty()) {
2900 message += "<none>";
2901 }
2902 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
2903}
2904
chaviwfd6d3512019-03-25 13:23:49 -07002905void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07002906 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07002907 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07002908 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
2909 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07002910 return;
2911 }
2912
Vishnu Nairad321cd2020-08-20 16:40:21 -07002913 sp<IBinder> focusedToken = getValueByKey(mFocusedWindowTokenByDisplay, mFocusedDisplayId);
2914 if (focusedToken == token) {
2915 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07002916 return;
2917 }
2918
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002919 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
2920 &InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible);
Vishnu Nairad321cd2020-08-20 16:40:21 -07002921 commandEntry->newToken = token;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002922 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002923}
2924
2925void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002926 const sp<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002927 if (ATRACE_ENABLED()) {
2928 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002929 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002930 ATRACE_NAME(message.c_str());
2931 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002932#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002933 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002934#endif
2935
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002936 while (connection->status == Connection::STATUS_NORMAL && !connection->outboundQueue.empty()) {
2937 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002938 dispatchEntry->deliveryTime = currentTime;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05002939 const std::chrono::nanoseconds timeout =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002940 getDispatchingTimeoutLocked(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou70622952020-07-30 11:17:23 -05002941 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002942
2943 // Publish the event.
2944 status_t status;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002945 const EventEntry& eventEntry = *(dispatchEntry->eventEntry);
2946 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002947 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002948 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
2949 std::array<uint8_t, 32> hmac = getSignature(keyEntry, *dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002950
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002951 // Publish the key event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002952 status = connection->inputPublisher
2953 .publishKeyEvent(dispatchEntry->seq,
2954 dispatchEntry->resolvedEventId, keyEntry.deviceId,
2955 keyEntry.source, keyEntry.displayId,
2956 std::move(hmac), dispatchEntry->resolvedAction,
2957 dispatchEntry->resolvedFlags, keyEntry.keyCode,
2958 keyEntry.scanCode, keyEntry.metaState,
2959 keyEntry.repeatCount, keyEntry.downTime,
2960 keyEntry.eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002961 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002962 }
2963
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002964 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002965 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002966
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002967 PointerCoords scaledCoords[MAX_POINTERS];
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002968 const PointerCoords* usingCoords = motionEntry.pointerCoords;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002969
chaviw82357092020-01-28 13:13:06 -08002970 // Set the X and Y offset and X and Y scale depending on the input source.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002971 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) &&
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002972 !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
2973 float globalScaleFactor = dispatchEntry->globalScaleFactor;
chaviw82357092020-01-28 13:13:06 -08002974 if (globalScaleFactor != 1.0f) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002975 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
2976 scaledCoords[i] = motionEntry.pointerCoords[i];
chaviw82357092020-01-28 13:13:06 -08002977 // Don't apply window scale here since we don't want scale to affect raw
2978 // coordinates. The scale will be sent back to the client and applied
2979 // later when requesting relative coordinates.
2980 scaledCoords[i].scale(globalScaleFactor, 1 /* windowXScale */,
2981 1 /* windowYScale */);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002982 }
2983 usingCoords = scaledCoords;
2984 }
2985 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002986 // We don't want the dispatch target to know.
2987 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002988 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002989 scaledCoords[i].clear();
2990 }
2991 usingCoords = scaledCoords;
2992 }
2993 }
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07002994
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002995 std::array<uint8_t, 32> hmac = getSignature(motionEntry, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002996
2997 // Publish the motion event.
2998 status = connection->inputPublisher
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002999 .publishMotionEvent(dispatchEntry->seq,
3000 dispatchEntry->resolvedEventId,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003001 motionEntry.deviceId, motionEntry.source,
3002 motionEntry.displayId, std::move(hmac),
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003003 dispatchEntry->resolvedAction,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003004 motionEntry.actionButton,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003005 dispatchEntry->resolvedFlags,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003006 motionEntry.edgeFlags, motionEntry.metaState,
3007 motionEntry.buttonState,
3008 motionEntry.classification,
chaviw9eaa22c2020-07-01 16:21:27 -07003009 dispatchEntry->transform,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003010 motionEntry.xPrecision, motionEntry.yPrecision,
3011 motionEntry.xCursorPosition,
3012 motionEntry.yCursorPosition,
3013 motionEntry.downTime, motionEntry.eventTime,
3014 motionEntry.pointerCount,
3015 motionEntry.pointerProperties, usingCoords);
3016 reportTouchEventForStatistics(motionEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003017 break;
3018 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003019
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003020 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003021 const FocusEntry& focusEntry = static_cast<const FocusEntry&>(eventEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003022 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003023 focusEntry.id,
3024 focusEntry.hasFocus,
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003025 mInTouchMode);
3026 break;
3027 }
3028
Prabir Pradhan99987712020-11-10 18:43:05 -08003029 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3030 const auto& captureEntry =
3031 static_cast<const PointerCaptureChangedEntry&>(eventEntry);
3032 status = connection->inputPublisher
3033 .publishCaptureEvent(dispatchEntry->seq, captureEntry.id,
3034 captureEntry.pointerCaptureEnabled);
3035 break;
3036 }
3037
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003038 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003039 case EventEntry::Type::DEVICE_RESET:
3040 case EventEntry::Type::SENSOR: {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003041 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
Chris Yef59a2f42020-10-16 12:55:26 -07003042 NamedEnum::string(eventEntry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003043 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003044 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003045 }
3046
3047 // Check the result.
3048 if (status) {
3049 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003050 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003051 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003052 "This is unexpected because the wait queue is empty, so the pipe "
3053 "should be empty and we shouldn't have any problems writing an "
3054 "event to it, status=%d",
3055 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003056 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3057 } else {
3058 // Pipe is full and we are waiting for the app to finish process some events
3059 // before sending more events to it.
3060#if DEBUG_DISPATCH_CYCLE
3061 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003062 "waiting for the application to catch up",
3063 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003064#endif
Michael Wrightd02c5b62014-02-10 15:10:22 -08003065 }
3066 } else {
3067 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003068 "status=%d",
3069 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003070 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3071 }
3072 return;
3073 }
3074
3075 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003076 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
3077 connection->outboundQueue.end(),
3078 dispatchEntry));
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003079 traceOutboundQueueLength(connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003080 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003081 if (connection->responsive) {
3082 mAnrTracker.insert(dispatchEntry->timeoutTime,
3083 connection->inputChannel->getConnectionToken());
3084 }
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003085 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003086 }
3087}
3088
chaviw09c8d2d2020-08-24 15:48:26 -07003089std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
3090 size_t size;
3091 switch (event.type) {
3092 case VerifiedInputEvent::Type::KEY: {
3093 size = sizeof(VerifiedKeyEvent);
3094 break;
3095 }
3096 case VerifiedInputEvent::Type::MOTION: {
3097 size = sizeof(VerifiedMotionEvent);
3098 break;
3099 }
3100 }
3101 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
3102 return mHmacKeyManager.sign(start, size);
3103}
3104
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003105const std::array<uint8_t, 32> InputDispatcher::getSignature(
3106 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
3107 int32_t actionMasked = dispatchEntry.resolvedAction & AMOTION_EVENT_ACTION_MASK;
3108 if ((actionMasked == AMOTION_EVENT_ACTION_UP) || (actionMasked == AMOTION_EVENT_ACTION_DOWN)) {
3109 // Only sign events up and down events as the purely move events
3110 // are tied to their up/down counterparts so signing would be redundant.
3111 VerifiedMotionEvent verifiedEvent = verifiedMotionEventFromMotionEntry(motionEntry);
3112 verifiedEvent.actionMasked = actionMasked;
3113 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
chaviw09c8d2d2020-08-24 15:48:26 -07003114 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003115 }
3116 return INVALID_HMAC;
3117}
3118
3119const std::array<uint8_t, 32> InputDispatcher::getSignature(
3120 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
3121 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
3122 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
3123 verifiedEvent.action = dispatchEntry.resolvedAction;
chaviw09c8d2d2020-08-24 15:48:26 -07003124 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003125}
3126
Michael Wrightd02c5b62014-02-10 15:10:22 -08003127void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003128 const sp<Connection>& connection, uint32_t seq,
3129 bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003130#if DEBUG_DISPATCH_CYCLE
3131 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003132 connection->getInputChannelName().c_str(), seq, toString(handled));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003133#endif
3134
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003135 if (connection->status == Connection::STATUS_BROKEN ||
3136 connection->status == Connection::STATUS_ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003137 return;
3138 }
3139
3140 // Notify other system components and prepare to start the next dispatch cycle.
3141 onDispatchCycleFinishedLocked(currentTime, connection, seq, handled);
3142}
3143
3144void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003145 const sp<Connection>& connection,
3146 bool notify) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003147#if DEBUG_DISPATCH_CYCLE
3148 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003149 connection->getInputChannelName().c_str(), toString(notify));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003150#endif
3151
3152 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003153 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003154 traceOutboundQueueLength(connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003155 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003156 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003157
3158 // The connection appears to be unrecoverably broken.
3159 // Ignore already broken or zombie connections.
3160 if (connection->status == Connection::STATUS_NORMAL) {
3161 connection->status = Connection::STATUS_BROKEN;
3162
3163 if (notify) {
3164 // Notify other system components.
3165 onDispatchCycleBrokenLocked(currentTime, connection);
3166 }
3167 }
3168}
3169
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003170void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
3171 while (!queue.empty()) {
3172 DispatchEntry* dispatchEntry = queue.front();
3173 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003174 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003175 }
3176}
3177
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003178void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003179 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003180 decrementPendingForegroundDispatches(*(dispatchEntry->eventEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003181 }
3182 delete dispatchEntry;
3183}
3184
3185int InputDispatcher::handleReceiveCallback(int fd, int events, void* data) {
3186 InputDispatcher* d = static_cast<InputDispatcher*>(data);
3187
3188 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003189 std::scoped_lock _l(d->mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003190
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003191 if (d->mConnectionsByFd.find(fd) == d->mConnectionsByFd.end()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003192 ALOGE("Received spurious receive callback for unknown input channel. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003193 "fd=%d, events=0x%x",
3194 fd, events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003195 return 0; // remove the callback
3196 }
3197
3198 bool notify;
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003199 sp<Connection> connection = d->mConnectionsByFd[fd];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003200 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
3201 if (!(events & ALOOPER_EVENT_INPUT)) {
3202 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003203 "events=0x%x",
3204 connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003205 return 1;
3206 }
3207
3208 nsecs_t currentTime = now();
3209 bool gotOne = false;
3210 status_t status;
3211 for (;;) {
3212 uint32_t seq;
3213 bool handled;
3214 status = connection->inputPublisher.receiveFinishedSignal(&seq, &handled);
3215 if (status) {
3216 break;
3217 }
3218 d->finishDispatchCycleLocked(currentTime, connection, seq, handled);
3219 gotOne = true;
3220 }
3221 if (gotOne) {
3222 d->runCommandsLockedInterruptible();
3223 if (status == WOULD_BLOCK) {
3224 return 1;
3225 }
3226 }
3227
3228 notify = status != DEAD_OBJECT || !connection->monitor;
3229 if (notify) {
3230 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003231 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003232 }
3233 } else {
3234 // Monitor channels are never explicitly unregistered.
3235 // We do it automatically when the remote endpoint is closed so don't warn
3236 // about them.
arthurhungd352cb32020-04-28 17:09:28 +08003237 const bool stillHaveWindowHandle =
3238 d->getWindowHandleLocked(connection->inputChannel->getConnectionToken()) !=
3239 nullptr;
3240 notify = !connection->monitor && stillHaveWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003241 if (notify) {
3242 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003243 "events=0x%x",
3244 connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003245 }
3246 }
3247
Garfield Tan15601662020-09-22 15:32:38 -07003248 // Remove the channel.
3249 d->removeInputChannelLocked(connection->inputChannel->getConnectionToken(), notify);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003250 return 0; // remove the callback
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003251 } // release lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08003252}
3253
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003254void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08003255 const CancelationOptions& options) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +00003256 for (const auto& [fd, connection] : mConnectionsByFd) {
3257 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003258 }
3259}
3260
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003261void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003262 const CancelationOptions& options) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003263 synthesizeCancelationEventsForMonitorsLocked(options, mGlobalMonitorsByDisplay);
3264 synthesizeCancelationEventsForMonitorsLocked(options, mGestureMonitorsByDisplay);
3265}
3266
3267void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
3268 const CancelationOptions& options,
3269 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
3270 for (const auto& it : monitorsByDisplay) {
3271 const std::vector<Monitor>& monitors = it.second;
3272 for (const Monitor& monitor : monitors) {
3273 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003274 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003275 }
3276}
3277
Michael Wrightd02c5b62014-02-10 15:10:22 -08003278void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003279 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07003280 sp<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003281 if (connection == nullptr) {
3282 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003283 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003284
3285 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003286}
3287
3288void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
3289 const sp<Connection>& connection, const CancelationOptions& options) {
3290 if (connection->status == Connection::STATUS_BROKEN) {
3291 return;
3292 }
3293
3294 nsecs_t currentTime = now();
3295
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003296 std::vector<std::unique_ptr<EventEntry>> cancelationEvents =
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07003297 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003298
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003299 if (cancelationEvents.empty()) {
3300 return;
3301 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003302#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003303 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
3304 "with reality: %s, mode=%d.",
3305 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
3306 options.mode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003307#endif
Svet Ganov5d3bc372020-01-26 23:11:07 -08003308
3309 InputTarget target;
3310 sp<InputWindowHandle> windowHandle =
3311 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3312 if (windowHandle != nullptr) {
3313 const InputWindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003314 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003315 target.globalScaleFactor = windowInfo->globalScaleFactor;
3316 }
3317 target.inputChannel = connection->inputChannel;
3318 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3319
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003320 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003321 std::unique_ptr<EventEntry> cancelationEventEntry = std::move(cancelationEvents[i]);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003322 switch (cancelationEventEntry->type) {
3323 case EventEntry::Type::KEY: {
3324 logOutboundKeyDetails("cancel - ",
3325 static_cast<const KeyEntry&>(*cancelationEventEntry));
3326 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003327 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003328 case EventEntry::Type::MOTION: {
3329 logOutboundMotionDetails("cancel - ",
3330 static_cast<const MotionEntry&>(*cancelationEventEntry));
3331 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003332 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003333 case EventEntry::Type::FOCUS:
3334 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3335 LOG_ALWAYS_FATAL("Canceling %s events is not supported",
Chris Yef59a2f42020-10-16 12:55:26 -07003336 NamedEnum::string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003337 break;
3338 }
3339 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003340 case EventEntry::Type::DEVICE_RESET:
3341 case EventEntry::Type::SENSOR: {
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003342 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Chris Yef59a2f42020-10-16 12:55:26 -07003343 NamedEnum::string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003344 break;
3345 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003346 }
3347
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003348 enqueueDispatchEntryLocked(connection, std::move(cancelationEventEntry), target,
3349 InputTarget::FLAG_DISPATCH_AS_IS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003350 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003351
3352 startDispatchCycleLocked(currentTime, connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003353}
3354
Svet Ganov5d3bc372020-01-26 23:11:07 -08003355void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
3356 const sp<Connection>& connection) {
3357 if (connection->status == Connection::STATUS_BROKEN) {
3358 return;
3359 }
3360
3361 nsecs_t currentTime = now();
3362
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003363 std::vector<std::unique_ptr<EventEntry>> downEvents =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003364 connection->inputState.synthesizePointerDownEvents(currentTime);
3365
3366 if (downEvents.empty()) {
3367 return;
3368 }
3369
3370#if DEBUG_OUTBOUND_EVENT_DETAILS
3371 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
3372 connection->getInputChannelName().c_str(), downEvents.size());
3373#endif
3374
3375 InputTarget target;
3376 sp<InputWindowHandle> windowHandle =
3377 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3378 if (windowHandle != nullptr) {
3379 const InputWindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003380 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003381 target.globalScaleFactor = windowInfo->globalScaleFactor;
3382 }
3383 target.inputChannel = connection->inputChannel;
3384 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3385
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003386 for (std::unique_ptr<EventEntry>& downEventEntry : downEvents) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003387 switch (downEventEntry->type) {
3388 case EventEntry::Type::MOTION: {
3389 logOutboundMotionDetails("down - ",
3390 static_cast<const MotionEntry&>(*downEventEntry));
3391 break;
3392 }
3393
3394 case EventEntry::Type::KEY:
3395 case EventEntry::Type::FOCUS:
3396 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08003397 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07003398 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3399 case EventEntry::Type::SENSOR: {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003400 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Chris Yef59a2f42020-10-16 12:55:26 -07003401 NamedEnum::string(downEventEntry->type).c_str());
Svet Ganov5d3bc372020-01-26 23:11:07 -08003402 break;
3403 }
3404 }
3405
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003406 enqueueDispatchEntryLocked(connection, std::move(downEventEntry), target,
3407 InputTarget::FLAG_DISPATCH_AS_IS);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003408 }
3409
3410 startDispatchCycleLocked(currentTime, connection);
3411}
3412
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003413std::unique_ptr<MotionEntry> InputDispatcher::splitMotionEvent(
3414 const MotionEntry& originalMotionEntry, BitSet32 pointerIds) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003415 ALOG_ASSERT(pointerIds.value != 0);
3416
3417 uint32_t splitPointerIndexMap[MAX_POINTERS];
3418 PointerProperties splitPointerProperties[MAX_POINTERS];
3419 PointerCoords splitPointerCoords[MAX_POINTERS];
3420
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003421 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003422 uint32_t splitPointerCount = 0;
3423
3424 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003425 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003426 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003427 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003428 uint32_t pointerId = uint32_t(pointerProperties.id);
3429 if (pointerIds.hasBit(pointerId)) {
3430 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
3431 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
3432 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003433 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003434 splitPointerCount += 1;
3435 }
3436 }
3437
3438 if (splitPointerCount != pointerIds.count()) {
3439 // This is bad. We are missing some of the pointers that we expected to deliver.
3440 // Most likely this indicates that we received an ACTION_MOVE events that has
3441 // different pointer ids than we expected based on the previous ACTION_DOWN
3442 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
3443 // in this way.
3444 ALOGW("Dropping split motion event because the pointer count is %d but "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003445 "we expected there to be %d pointers. This probably means we received "
3446 "a broken sequence of pointer ids from the input device.",
3447 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07003448 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003449 }
3450
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003451 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003452 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003453 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
3454 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003455 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
3456 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003457 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003458 uint32_t pointerId = uint32_t(pointerProperties.id);
3459 if (pointerIds.hasBit(pointerId)) {
3460 if (pointerIds.count() == 1) {
3461 // The first/last pointer went down/up.
3462 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003463 ? AMOTION_EVENT_ACTION_DOWN
arthurhungea3f4fc2020-12-21 23:18:53 +08003464 : (originalMotionEntry.flags & AMOTION_EVENT_FLAG_CANCELED) != 0
3465 ? AMOTION_EVENT_ACTION_CANCEL
3466 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003467 } else {
3468 // A secondary pointer went down/up.
3469 uint32_t splitPointerIndex = 0;
3470 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
3471 splitPointerIndex += 1;
3472 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003473 action = maskedAction |
3474 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003475 }
3476 } else {
3477 // An unrelated pointer changed.
3478 action = AMOTION_EVENT_ACTION_MOVE;
3479 }
3480 }
3481
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003482 int32_t newId = mIdGenerator.nextId();
3483 if (ATRACE_ENABLED()) {
3484 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
3485 ") to MotionEvent(id=0x%" PRIx32 ").",
3486 originalMotionEntry.id, newId);
3487 ATRACE_NAME(message.c_str());
3488 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003489 std::unique_ptr<MotionEntry> splitMotionEntry =
3490 std::make_unique<MotionEntry>(newId, originalMotionEntry.eventTime,
3491 originalMotionEntry.deviceId, originalMotionEntry.source,
3492 originalMotionEntry.displayId,
3493 originalMotionEntry.policyFlags, action,
3494 originalMotionEntry.actionButton,
3495 originalMotionEntry.flags, originalMotionEntry.metaState,
3496 originalMotionEntry.buttonState,
3497 originalMotionEntry.classification,
3498 originalMotionEntry.edgeFlags,
3499 originalMotionEntry.xPrecision,
3500 originalMotionEntry.yPrecision,
3501 originalMotionEntry.xCursorPosition,
3502 originalMotionEntry.yCursorPosition,
3503 originalMotionEntry.downTime, splitPointerCount,
3504 splitPointerProperties, splitPointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003505
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003506 if (originalMotionEntry.injectionState) {
3507 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003508 splitMotionEntry->injectionState->refCount += 1;
3509 }
3510
3511 return splitMotionEntry;
3512}
3513
3514void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
3515#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003516 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003517#endif
3518
3519 bool needWake;
3520 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003521 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003522
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003523 std::unique_ptr<ConfigurationChangedEntry> newEntry =
3524 std::make_unique<ConfigurationChangedEntry>(args->id, args->eventTime);
3525 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003526 } // release lock
3527
3528 if (needWake) {
3529 mLooper->wake();
3530 }
3531}
3532
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003533/**
3534 * If one of the meta shortcuts is detected, process them here:
3535 * Meta + Backspace -> generate BACK
3536 * Meta + Enter -> generate HOME
3537 * This will potentially overwrite keyCode and metaState.
3538 */
3539void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003540 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003541 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
3542 int32_t newKeyCode = AKEYCODE_UNKNOWN;
3543 if (keyCode == AKEYCODE_DEL) {
3544 newKeyCode = AKEYCODE_BACK;
3545 } else if (keyCode == AKEYCODE_ENTER) {
3546 newKeyCode = AKEYCODE_HOME;
3547 }
3548 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003549 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003550 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003551 mReplacedKeys[replacement] = newKeyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003552 keyCode = newKeyCode;
3553 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3554 }
3555 } else if (action == AKEY_EVENT_ACTION_UP) {
3556 // In order to maintain a consistent stream of up and down events, check to see if the key
3557 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
3558 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003559 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003560 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003561 auto replacementIt = mReplacedKeys.find(replacement);
3562 if (replacementIt != mReplacedKeys.end()) {
3563 keyCode = replacementIt->second;
3564 mReplacedKeys.erase(replacementIt);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003565 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3566 }
3567 }
3568}
3569
Michael Wrightd02c5b62014-02-10 15:10:22 -08003570void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
3571#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003572 ALOGD("notifyKey - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
3573 "policyFlags=0x%x, action=0x%x, "
3574 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
3575 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
3576 args->action, args->flags, args->keyCode, args->scanCode, args->metaState,
3577 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003578#endif
3579 if (!validateKeyEvent(args->action)) {
3580 return;
3581 }
3582
3583 uint32_t policyFlags = args->policyFlags;
3584 int32_t flags = args->flags;
3585 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07003586 // InputDispatcher tracks and generates key repeats on behalf of
3587 // whatever notifies it, so repeatCount should always be set to 0
3588 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003589 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
3590 policyFlags |= POLICY_FLAG_VIRTUAL;
3591 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
3592 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003593 if (policyFlags & POLICY_FLAG_FUNCTION) {
3594 metaState |= AMETA_FUNCTION_ON;
3595 }
3596
3597 policyFlags |= POLICY_FLAG_TRUSTED;
3598
Michael Wright78f24442014-08-06 15:55:28 -07003599 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003600 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07003601
Michael Wrightd02c5b62014-02-10 15:10:22 -08003602 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003603 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08003604 args->action, flags, keyCode, args->scanCode, metaState, repeatCount,
3605 args->downTime, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003606
Michael Wright2b3c3302018-03-02 17:19:13 +00003607 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003608 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003609 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3610 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003611 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003612 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003613
Michael Wrightd02c5b62014-02-10 15:10:22 -08003614 bool needWake;
3615 { // acquire lock
3616 mLock.lock();
3617
3618 if (shouldSendKeyToInputFilterLocked(args)) {
3619 mLock.unlock();
3620
3621 policyFlags |= POLICY_FLAG_FILTERED;
3622 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3623 return; // event was consumed by the filter
3624 }
3625
3626 mLock.lock();
3627 }
3628
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003629 std::unique_ptr<KeyEntry> newEntry =
3630 std::make_unique<KeyEntry>(args->id, args->eventTime, args->deviceId, args->source,
3631 args->displayId, policyFlags, args->action, flags,
3632 keyCode, args->scanCode, metaState, repeatCount,
3633 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003634
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003635 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003636 mLock.unlock();
3637 } // release lock
3638
3639 if (needWake) {
3640 mLooper->wake();
3641 }
3642}
3643
3644bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
3645 return mInputFilterEnabled;
3646}
3647
3648void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
3649#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003650 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
3651 "displayId=%" PRId32 ", policyFlags=0x%x, "
Garfield Tan00f511d2019-06-12 16:55:40 -07003652 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
3653 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
Garfield Tanab0ab9c2019-07-10 18:58:28 -07003654 "yCursorPosition=%f, downTime=%" PRId64,
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003655 args->id, args->eventTime, args->deviceId, args->source, args->displayId,
3656 args->policyFlags, args->action, args->actionButton, args->flags, args->metaState,
3657 args->buttonState, args->edgeFlags, args->xPrecision, args->yPrecision,
3658 args->xCursorPosition, args->yCursorPosition, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003659 for (uint32_t i = 0; i < args->pointerCount; i++) {
3660 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003661 "x=%f, y=%f, pressure=%f, size=%f, "
3662 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
3663 "orientation=%f",
3664 i, args->pointerProperties[i].id, args->pointerProperties[i].toolType,
3665 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
3666 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
3667 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
3668 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
3669 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
3670 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
3671 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
3672 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
3673 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003674 }
3675#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003676 if (!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
3677 args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003678 return;
3679 }
3680
3681 uint32_t policyFlags = args->policyFlags;
3682 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003683
3684 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08003685 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003686 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3687 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003688 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003689 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003690
3691 bool needWake;
3692 { // acquire lock
3693 mLock.lock();
3694
3695 if (shouldSendMotionToInputFilterLocked(args)) {
3696 mLock.unlock();
3697
3698 MotionEvent event;
chaviw9eaa22c2020-07-01 16:21:27 -07003699 ui::Transform transform;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003700 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
3701 args->action, args->actionButton, args->flags, args->edgeFlags,
chaviw9eaa22c2020-07-01 16:21:27 -07003702 args->metaState, args->buttonState, args->classification, transform,
3703 args->xPrecision, args->yPrecision, args->xCursorPosition,
3704 args->yCursorPosition, args->downTime, args->eventTime,
3705 args->pointerCount, args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003706
3707 policyFlags |= POLICY_FLAG_FILTERED;
3708 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3709 return; // event was consumed by the filter
3710 }
3711
3712 mLock.lock();
3713 }
3714
3715 // Just enqueue a new motion event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003716 std::unique_ptr<MotionEntry> newEntry =
3717 std::make_unique<MotionEntry>(args->id, args->eventTime, args->deviceId,
3718 args->source, args->displayId, policyFlags,
3719 args->action, args->actionButton, args->flags,
3720 args->metaState, args->buttonState,
3721 args->classification, args->edgeFlags,
3722 args->xPrecision, args->yPrecision,
3723 args->xCursorPosition, args->yCursorPosition,
3724 args->downTime, args->pointerCount,
3725 args->pointerProperties, args->pointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003726
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003727 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003728 mLock.unlock();
3729 } // release lock
3730
3731 if (needWake) {
3732 mLooper->wake();
3733 }
3734}
3735
Chris Yef59a2f42020-10-16 12:55:26 -07003736void InputDispatcher::notifySensor(const NotifySensorArgs* args) {
3737#if DEBUG_INBOUND_EVENT_DETAILS
3738 ALOGD("notifySensor - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
3739 " sensorType=%s",
3740 args->id, args->eventTime, args->deviceId, args->source,
3741 NamedEnum::string(args->sensorType).c_str());
3742#endif
3743
3744 bool needWake;
3745 { // acquire lock
3746 mLock.lock();
3747
3748 // Just enqueue a new sensor event.
3749 std::unique_ptr<SensorEntry> newEntry =
3750 std::make_unique<SensorEntry>(args->id, args->eventTime, args->deviceId,
3751 args->source, 0 /* policyFlags*/, args->hwTimestamp,
3752 args->sensorType, args->accuracy,
3753 args->accuracyChanged, args->values);
3754
3755 needWake = enqueueInboundEventLocked(std::move(newEntry));
3756 mLock.unlock();
3757 } // release lock
3758
3759 if (needWake) {
3760 mLooper->wake();
3761 }
3762}
3763
Michael Wrightd02c5b62014-02-10 15:10:22 -08003764bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08003765 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003766}
3767
3768void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
3769#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003770 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003771 "switchMask=0x%08x",
3772 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003773#endif
3774
3775 uint32_t policyFlags = args->policyFlags;
3776 policyFlags |= POLICY_FLAG_TRUSTED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003777 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003778}
3779
3780void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
3781#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003782 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
3783 args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003784#endif
3785
3786 bool needWake;
3787 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003788 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003789
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003790 std::unique_ptr<DeviceResetEntry> newEntry =
3791 std::make_unique<DeviceResetEntry>(args->id, args->eventTime, args->deviceId);
3792 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003793 } // release lock
3794
3795 if (needWake) {
3796 mLooper->wake();
3797 }
3798}
3799
Prabir Pradhan7e186182020-11-10 13:56:45 -08003800void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs* args) {
3801#if DEBUG_INBOUND_EVENT_DETAILS
3802 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args->eventTime,
3803 args->enabled ? "true" : "false");
3804#endif
3805
Prabir Pradhan99987712020-11-10 18:43:05 -08003806 bool needWake;
3807 { // acquire lock
3808 std::scoped_lock _l(mLock);
3809 auto entry = std::make_unique<PointerCaptureChangedEntry>(args->id, args->eventTime,
3810 args->enabled);
3811 needWake = enqueueInboundEventLocked(std::move(entry));
3812 } // release lock
3813
3814 if (needWake) {
3815 mLooper->wake();
3816 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08003817}
3818
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003819InputEventInjectionResult InputDispatcher::injectInputEvent(
3820 const InputEvent* event, int32_t injectorPid, int32_t injectorUid,
3821 InputEventInjectionSync syncMode, std::chrono::milliseconds timeout, uint32_t policyFlags) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003822#if DEBUG_INBOUND_EVENT_DETAILS
3823 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003824 "syncMode=%d, timeout=%lld, policyFlags=0x%08x",
3825 event->getType(), injectorPid, injectorUid, syncMode, timeout.count(), policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003826#endif
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003827 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003828
3829 policyFlags |= POLICY_FLAG_INJECTED;
3830 if (hasInjectionPermission(injectorPid, injectorUid)) {
3831 policyFlags |= POLICY_FLAG_TRUSTED;
3832 }
3833
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003834 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003835 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003836 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003837 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
3838 int32_t action = incomingKey.getAction();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003839 if (!validateKeyEvent(action)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003840 return InputEventInjectionResult::FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003841 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003842
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003843 int32_t flags = incomingKey.getFlags();
3844 int32_t keyCode = incomingKey.getKeyCode();
3845 int32_t metaState = incomingKey.getMetaState();
3846 accelerateMetaShortcuts(VIRTUAL_KEYBOARD_ID, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003847 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003848 KeyEvent keyEvent;
Garfield Tan4cc839f2020-01-24 11:26:14 -08003849 keyEvent.initialize(incomingKey.getId(), VIRTUAL_KEYBOARD_ID, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003850 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
3851 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
3852 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003853
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003854 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
3855 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00003856 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003857
3858 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
3859 android::base::Timer t;
3860 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
3861 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3862 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
3863 std::to_string(t.duration().count()).c_str());
3864 }
3865 }
3866
3867 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003868 std::unique_ptr<KeyEntry> injectedEntry =
3869 std::make_unique<KeyEntry>(incomingKey.getId(), incomingKey.getEventTime(),
3870 VIRTUAL_KEYBOARD_ID, incomingKey.getSource(),
3871 incomingKey.getDisplayId(), policyFlags, action,
3872 flags, keyCode, incomingKey.getScanCode(), metaState,
3873 incomingKey.getRepeatCount(),
3874 incomingKey.getDownTime());
3875 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003876 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003877 }
3878
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003879 case AINPUT_EVENT_TYPE_MOTION: {
3880 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
3881 int32_t action = motionEvent->getAction();
3882 size_t pointerCount = motionEvent->getPointerCount();
3883 const PointerProperties* pointerProperties = motionEvent->getPointerProperties();
3884 int32_t actionButton = motionEvent->getActionButton();
3885 int32_t displayId = motionEvent->getDisplayId();
3886 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003887 return InputEventInjectionResult::FAILED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003888 }
3889
3890 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
3891 nsecs_t eventTime = motionEvent->getEventTime();
3892 android::base::Timer t;
3893 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
3894 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3895 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
3896 std::to_string(t.duration().count()).c_str());
3897 }
3898 }
3899
3900 mLock.lock();
3901 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
3902 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003903 std::unique_ptr<MotionEntry> injectedEntry =
3904 std::make_unique<MotionEntry>(motionEvent->getId(), *sampleEventTimes,
3905 VIRTUAL_KEYBOARD_ID, motionEvent->getSource(),
3906 motionEvent->getDisplayId(), policyFlags, action,
3907 actionButton, motionEvent->getFlags(),
3908 motionEvent->getMetaState(),
3909 motionEvent->getButtonState(),
3910 motionEvent->getClassification(),
3911 motionEvent->getEdgeFlags(),
3912 motionEvent->getXPrecision(),
3913 motionEvent->getYPrecision(),
3914 motionEvent->getRawXCursorPosition(),
3915 motionEvent->getRawYCursorPosition(),
3916 motionEvent->getDownTime(),
3917 uint32_t(pointerCount), pointerProperties,
3918 samplePointerCoords, motionEvent->getXOffset(),
3919 motionEvent->getYOffset());
3920 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003921 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
3922 sampleEventTimes += 1;
3923 samplePointerCoords += pointerCount;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003924 std::unique_ptr<MotionEntry> nextInjectedEntry =
3925 std::make_unique<MotionEntry>(motionEvent->getId(), *sampleEventTimes,
3926 VIRTUAL_KEYBOARD_ID, motionEvent->getSource(),
3927 motionEvent->getDisplayId(), policyFlags,
3928 action, actionButton, motionEvent->getFlags(),
3929 motionEvent->getMetaState(),
3930 motionEvent->getButtonState(),
3931 motionEvent->getClassification(),
3932 motionEvent->getEdgeFlags(),
3933 motionEvent->getXPrecision(),
3934 motionEvent->getYPrecision(),
3935 motionEvent->getRawXCursorPosition(),
3936 motionEvent->getRawYCursorPosition(),
3937 motionEvent->getDownTime(),
3938 uint32_t(pointerCount), pointerProperties,
3939 samplePointerCoords,
3940 motionEvent->getXOffset(),
3941 motionEvent->getYOffset());
3942 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003943 }
3944 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003945 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003946
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003947 default:
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08003948 ALOGW("Cannot inject %s events", inputEventTypeToString(event->getType()));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003949 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003950 }
3951
3952 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003953 if (syncMode == InputEventInjectionSync::NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003954 injectionState->injectionIsAsync = true;
3955 }
3956
3957 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003958 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003959
3960 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003961 while (!injectedEntries.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003962 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003963 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003964 }
3965
3966 mLock.unlock();
3967
3968 if (needWake) {
3969 mLooper->wake();
3970 }
3971
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003972 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003973 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003974 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003975
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003976 if (syncMode == InputEventInjectionSync::NONE) {
3977 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003978 } else {
3979 for (;;) {
3980 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003981 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003982 break;
3983 }
3984
3985 nsecs_t remainingTimeout = endTime - now();
3986 if (remainingTimeout <= 0) {
3987#if DEBUG_INJECTION
3988 ALOGD("injectInputEvent - Timed out waiting for injection result "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003989 "to become available.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003990#endif
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003991 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003992 break;
3993 }
3994
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003995 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003996 }
3997
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003998 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
3999 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004000 while (injectionState->pendingForegroundDispatches != 0) {
4001#if DEBUG_INJECTION
4002 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004003 injectionState->pendingForegroundDispatches);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004004#endif
4005 nsecs_t remainingTimeout = endTime - now();
4006 if (remainingTimeout <= 0) {
4007#if DEBUG_INJECTION
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004008 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
4009 "dispatches to finish.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004010#endif
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004011 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004012 break;
4013 }
4014
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004015 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004016 }
4017 }
4018 }
4019
4020 injectionState->release();
4021 } // release lock
4022
4023#if DEBUG_INJECTION
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004024 ALOGD("injectInputEvent - Finished with result %d. injectorPid=%d, injectorUid=%d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004025 injectionResult, injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004026#endif
4027
4028 return injectionResult;
4029}
4030
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004031std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05004032 std::array<uint8_t, 32> calculatedHmac;
4033 std::unique_ptr<VerifiedInputEvent> result;
4034 switch (event.getType()) {
4035 case AINPUT_EVENT_TYPE_KEY: {
4036 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
4037 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
4038 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004039 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05004040 break;
4041 }
4042 case AINPUT_EVENT_TYPE_MOTION: {
4043 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
4044 VerifiedMotionEvent verifiedMotionEvent =
4045 verifiedMotionEventFromMotionEvent(motionEvent);
4046 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004047 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05004048 break;
4049 }
4050 default: {
4051 ALOGE("Cannot verify events of type %" PRId32, event.getType());
4052 return nullptr;
4053 }
4054 }
4055 if (calculatedHmac == INVALID_HMAC) {
4056 return nullptr;
4057 }
4058 if (calculatedHmac != event.getHmac()) {
4059 return nullptr;
4060 }
4061 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004062}
4063
Michael Wrightd02c5b62014-02-10 15:10:22 -08004064bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004065 return injectorUid == 0 ||
4066 mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004067}
4068
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004069void InputDispatcher::setInjectionResult(EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004070 InputEventInjectionResult injectionResult) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004071 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004072 if (injectionState) {
4073#if DEBUG_INJECTION
4074 ALOGD("Setting input event injection result to %d. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004075 "injectorPid=%d, injectorUid=%d",
4076 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004077#endif
4078
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004079 if (injectionState->injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004080 // Log the outcome since the injector did not wait for the injection result.
4081 switch (injectionResult) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004082 case InputEventInjectionResult::SUCCEEDED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004083 ALOGV("Asynchronous input event injection succeeded.");
4084 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004085 case InputEventInjectionResult::FAILED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004086 ALOGW("Asynchronous input event injection failed.");
4087 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004088 case InputEventInjectionResult::PERMISSION_DENIED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004089 ALOGW("Asynchronous input event injection permission denied.");
4090 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004091 case InputEventInjectionResult::TIMED_OUT:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004092 ALOGW("Asynchronous input event injection timed out.");
4093 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004094 case InputEventInjectionResult::PENDING:
4095 ALOGE("Setting result to 'PENDING' for asynchronous injection");
4096 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004097 }
4098 }
4099
4100 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004101 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004102 }
4103}
4104
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004105void InputDispatcher::incrementPendingForegroundDispatches(EventEntry& entry) {
4106 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004107 if (injectionState) {
4108 injectionState->pendingForegroundDispatches += 1;
4109 }
4110}
4111
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004112void InputDispatcher::decrementPendingForegroundDispatches(EventEntry& entry) {
4113 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004114 if (injectionState) {
4115 injectionState->pendingForegroundDispatches -= 1;
4116
4117 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004118 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004119 }
4120 }
4121}
4122
Vishnu Nairad321cd2020-08-20 16:40:21 -07004123const std::vector<sp<InputWindowHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004124 int32_t displayId) const {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004125 static const std::vector<sp<InputWindowHandle>> EMPTY_WINDOW_HANDLES;
4126 auto it = mWindowHandlesByDisplay.find(displayId);
4127 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08004128}
4129
Michael Wrightd02c5b62014-02-10 15:10:22 -08004130sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08004131 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08004132 if (windowHandleToken == nullptr) {
4133 return nullptr;
4134 }
4135
Arthur Hungb92218b2018-08-14 12:00:21 +08004136 for (auto& it : mWindowHandlesByDisplay) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004137 const std::vector<sp<InputWindowHandle>>& windowHandles = it.second;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004138 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004139 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004140 return windowHandle;
4141 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004142 }
4143 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004144 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004145}
4146
Vishnu Nairad321cd2020-08-20 16:40:21 -07004147sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(const sp<IBinder>& windowHandleToken,
4148 int displayId) const {
4149 if (windowHandleToken == nullptr) {
4150 return nullptr;
4151 }
4152
4153 for (const sp<InputWindowHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
4154 if (windowHandle->getToken() == windowHandleToken) {
4155 return windowHandle;
4156 }
4157 }
4158 return nullptr;
4159}
4160
4161sp<InputWindowHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
4162 sp<IBinder> focusedToken = getValueByKey(mFocusedWindowTokenByDisplay, displayId);
4163 return getWindowHandleLocked(focusedToken, displayId);
4164}
4165
Mady Mellor017bcd12020-06-23 19:12:00 +00004166bool InputDispatcher::hasWindowHandleLocked(const sp<InputWindowHandle>& windowHandle) const {
4167 for (auto& it : mWindowHandlesByDisplay) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004168 const std::vector<sp<InputWindowHandle>>& windowHandles = it.second;
Mady Mellor017bcd12020-06-23 19:12:00 +00004169 for (const sp<InputWindowHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08004170 if (handle->getId() == windowHandle->getId() &&
4171 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004172 if (windowHandle->getInfo()->displayId != it.first) {
4173 ALOGE("Found window %s in display %" PRId32
4174 ", but it should belong to display %" PRId32,
4175 windowHandle->getName().c_str(), it.first,
4176 windowHandle->getInfo()->displayId);
4177 }
4178 return true;
Arthur Hungb92218b2018-08-14 12:00:21 +08004179 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004180 }
4181 }
4182 return false;
4183}
4184
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004185bool InputDispatcher::hasResponsiveConnectionLocked(InputWindowHandle& windowHandle) const {
4186 sp<Connection> connection = getConnectionLocked(windowHandle.getToken());
4187 const bool noInputChannel =
4188 windowHandle.getInfo()->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
4189 if (connection != nullptr && noInputChannel) {
4190 ALOGW("%s has feature NO_INPUT_CHANNEL, but it matched to connection %s",
4191 windowHandle.getName().c_str(), connection->inputChannel->getName().c_str());
4192 return false;
4193 }
4194
4195 if (connection == nullptr) {
4196 if (!noInputChannel) {
4197 ALOGI("Could not find connection for %s", windowHandle.getName().c_str());
4198 }
4199 return false;
4200 }
4201 if (!connection->responsive) {
4202 ALOGW("Window %s is not responsive", windowHandle.getName().c_str());
4203 return false;
4204 }
4205 return true;
4206}
4207
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004208std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
4209 const sp<IBinder>& token) const {
Robert Carr5c8a0262018-10-03 16:30:44 -07004210 size_t count = mInputChannelsByToken.count(token);
4211 if (count == 0) {
4212 return nullptr;
4213 }
4214 return mInputChannelsByToken.at(token);
4215}
4216
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004217void InputDispatcher::updateWindowHandlesForDisplayLocked(
4218 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
4219 if (inputWindowHandles.empty()) {
4220 // Remove all handles on a display if there are no windows left.
4221 mWindowHandlesByDisplay.erase(displayId);
4222 return;
4223 }
4224
4225 // Since we compare the pointer of input window handles across window updates, we need
4226 // to make sure the handle object for the same window stays unchanged across updates.
4227 const std::vector<sp<InputWindowHandle>>& oldHandles = getWindowHandlesLocked(displayId);
chaviwaf87b3e2019-10-01 16:59:28 -07004228 std::unordered_map<int32_t /*id*/, sp<InputWindowHandle>> oldHandlesById;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004229 for (const sp<InputWindowHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07004230 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004231 }
4232
4233 std::vector<sp<InputWindowHandle>> newHandles;
4234 for (const sp<InputWindowHandle>& handle : inputWindowHandles) {
4235 if (!handle->updateInfo()) {
4236 // handle no longer valid
4237 continue;
4238 }
4239
4240 const InputWindowInfo* info = handle->getInfo();
4241 if ((getInputChannelLocked(handle->getToken()) == nullptr &&
4242 info->portalToDisplayId == ADISPLAY_ID_NONE)) {
4243 const bool noInputChannel =
Michael Wright44753b12020-07-08 13:48:11 +01004244 info->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
4245 const bool canReceiveInput = !info->flags.test(InputWindowInfo::Flag::NOT_TOUCHABLE) ||
4246 !info->flags.test(InputWindowInfo::Flag::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004247 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07004248 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004249 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07004250 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004251 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004252 }
4253
4254 if (info->displayId != displayId) {
4255 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
4256 handle->getName().c_str(), displayId, info->displayId);
4257 continue;
4258 }
4259
Robert Carredd13602020-04-13 17:24:34 -07004260 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
4261 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviwaf87b3e2019-10-01 16:59:28 -07004262 const sp<InputWindowHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004263 oldHandle->updateFrom(handle);
4264 newHandles.push_back(oldHandle);
4265 } else {
4266 newHandles.push_back(handle);
4267 }
4268 }
4269
4270 // Insert or replace
4271 mWindowHandlesByDisplay[displayId] = newHandles;
4272}
4273
Arthur Hung72d8dc32020-03-28 00:48:39 +00004274void InputDispatcher::setInputWindows(
4275 const std::unordered_map<int32_t, std::vector<sp<InputWindowHandle>>>& handlesPerDisplay) {
4276 { // acquire lock
4277 std::scoped_lock _l(mLock);
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004278 for (const auto& [displayId, handles] : handlesPerDisplay) {
4279 setInputWindowsLocked(handles, displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004280 }
4281 }
4282 // Wake up poll loop since it may need to make new input dispatching choices.
4283 mLooper->wake();
4284}
4285
Arthur Hungb92218b2018-08-14 12:00:21 +08004286/**
4287 * Called from InputManagerService, update window handle list by displayId that can receive input.
4288 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
4289 * If set an empty list, remove all handles from the specific display.
4290 * For focused handle, check if need to change and send a cancel event to previous one.
4291 * For removed handle, check if need to send a cancel event if already in touch.
4292 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00004293void InputDispatcher::setInputWindowsLocked(
4294 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004295 if (DEBUG_FOCUS) {
4296 std::string windowList;
4297 for (const sp<InputWindowHandle>& iwh : inputWindowHandles) {
4298 windowList += iwh->getName() + " ";
4299 }
4300 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
4301 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004302
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004303 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
4304 for (const sp<InputWindowHandle>& window : inputWindowHandles) {
4305 const bool noInputWindow =
4306 window->getInfo()->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
4307 if (noInputWindow && window->getToken() != nullptr) {
4308 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
4309 window->getName().c_str());
4310 window->releaseChannel();
4311 }
4312 }
4313
Arthur Hung72d8dc32020-03-28 00:48:39 +00004314 // Copy old handles for release if they are no longer present.
4315 const std::vector<sp<InputWindowHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004316
Arthur Hung72d8dc32020-03-28 00:48:39 +00004317 updateWindowHandlesForDisplayLocked(inputWindowHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004318
Vishnu Nair958da932020-08-21 17:12:37 -07004319 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
4320 if (mLastHoverWindowHandle &&
4321 std::find(windowHandles.begin(), windowHandles.end(), mLastHoverWindowHandle) ==
4322 windowHandles.end()) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004323 mLastHoverWindowHandle = nullptr;
4324 }
4325
Vishnu Nair958da932020-08-21 17:12:37 -07004326 sp<IBinder> focusedToken = getValueByKey(mFocusedWindowTokenByDisplay, displayId);
4327 if (focusedToken) {
4328 FocusResult result = checkTokenFocusableLocked(focusedToken, displayId);
4329 if (result != FocusResult::OK) {
4330 onFocusChangedLocked(focusedToken, nullptr, displayId, typeToString(result));
4331 }
4332 }
4333
4334 std::optional<FocusRequest> focusRequest =
4335 getOptionalValueByKey(mPendingFocusRequests, displayId);
4336 if (focusRequest) {
4337 // If the window from the pending request is now visible, provide it focus.
4338 FocusResult result = handleFocusRequestLocked(*focusRequest);
4339 if (result != FocusResult::NOT_VISIBLE) {
4340 // Drop the request if we were able to change the focus or we cannot change
4341 // it for another reason.
4342 mPendingFocusRequests.erase(displayId);
4343 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004344 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004345
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004346 std::unordered_map<int32_t, TouchState>::iterator stateIt =
4347 mTouchStatesByDisplay.find(displayId);
4348 if (stateIt != mTouchStatesByDisplay.end()) {
4349 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00004350 for (size_t i = 0; i < state.windows.size();) {
4351 TouchedWindow& touchedWindow = state.windows[i];
Mady Mellor017bcd12020-06-23 19:12:00 +00004352 if (!hasWindowHandleLocked(touchedWindow.windowHandle)) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004353 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004354 ALOGD("Touched window was removed: %s in display %" PRId32,
4355 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004356 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004357 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00004358 getInputChannelLocked(touchedWindow.windowHandle->getToken());
4359 if (touchedInputChannel != nullptr) {
4360 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4361 "touched window was removed");
4362 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004363 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004364 state.windows.erase(state.windows.begin() + i);
4365 } else {
4366 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004367 }
4368 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004369 }
Arthur Hung25e2af12020-03-26 12:58:37 +00004370
Arthur Hung72d8dc32020-03-28 00:48:39 +00004371 // Release information for windows that are no longer present.
4372 // This ensures that unused input channels are released promptly.
4373 // Otherwise, they might stick around until the window handle is destroyed
4374 // which might not happen until the next GC.
4375 for (const sp<InputWindowHandle>& oldWindowHandle : oldWindowHandles) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004376 if (!hasWindowHandleLocked(oldWindowHandle)) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004377 if (DEBUG_FOCUS) {
4378 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00004379 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004380 oldWindowHandle->releaseChannel();
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004381 // To avoid making too many calls into the compat framework, only
4382 // check for window flags when windows are going away.
4383 // TODO(b/157929241) : delete this. This is only needed temporarily
4384 // in order to gather some data about the flag usage
4385 if (oldWindowHandle->getInfo()->flags.test(InputWindowInfo::Flag::SLIPPERY)) {
4386 ALOGW("%s has FLAG_SLIPPERY. Please report this in b/157929241",
4387 oldWindowHandle->getName().c_str());
4388 if (mCompatService != nullptr) {
4389 mCompatService->reportChangeByUid(IInputConstants::BLOCK_FLAG_SLIPPERY,
4390 oldWindowHandle->getInfo()->ownerUid);
4391 }
4392 }
Arthur Hung25e2af12020-03-26 12:58:37 +00004393 }
chaviw291d88a2019-02-14 10:33:58 -08004394 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004395}
4396
4397void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07004398 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004399 if (DEBUG_FOCUS) {
4400 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
4401 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
4402 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004403 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004404 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004405
Chris Yea209fde2020-07-22 13:54:51 -07004406 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08004407 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004408
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004409 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
4410 return; // This application is already focused. No need to wake up or change anything.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004411 }
4412
Chris Yea209fde2020-07-22 13:54:51 -07004413 // Set the new application handle.
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004414 if (inputApplicationHandle != nullptr) {
4415 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
4416 } else {
4417 mFocusedApplicationHandlesByDisplay.erase(displayId);
4418 }
4419
4420 // No matter what the old focused application was, stop waiting on it because it is
4421 // no longer focused.
4422 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004423 } // release lock
4424
4425 // Wake up poll loop since it may need to make new input dispatching choices.
4426 mLooper->wake();
4427}
4428
Tiger Huang721e26f2018-07-24 22:26:19 +08004429/**
4430 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
4431 * the display not specified.
4432 *
4433 * We track any unreleased events for each window. If a window loses the ability to receive the
4434 * released event, we will send a cancel event to it. So when the focused display is changed, we
4435 * cancel all the unreleased display-unspecified events for the focused window on the old focused
4436 * display. The display-specified events won't be affected.
4437 */
4438void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004439 if (DEBUG_FOCUS) {
4440 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
4441 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004442 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004443 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08004444
4445 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004446 sp<IBinder> oldFocusedWindowToken =
4447 getValueByKey(mFocusedWindowTokenByDisplay, mFocusedDisplayId);
4448 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004449 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07004450 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08004451 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004452 CancelationOptions
4453 options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
4454 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004455 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08004456 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
4457 }
4458 }
4459 mFocusedDisplayId = displayId;
4460
Chris Ye3c2d6f52020-08-09 10:39:48 -07004461 // Find new focused window and validate
Vishnu Nairad321cd2020-08-20 16:40:21 -07004462 sp<IBinder> newFocusedWindowToken =
4463 getValueByKey(mFocusedWindowTokenByDisplay, displayId);
4464 notifyFocusChangedLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08004465
Vishnu Nairad321cd2020-08-20 16:40:21 -07004466 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08004467 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07004468 if (!mFocusedWindowTokenByDisplay.empty()) {
4469 ALOGE("But another display has a focused window\n%s",
4470 dumpFocusedWindowsLocked().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08004471 }
4472 }
4473 }
4474
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004475 if (DEBUG_FOCUS) {
4476 logDispatchStateLocked();
4477 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004478 } // release lock
4479
4480 // Wake up poll loop since it may need to make new input dispatching choices.
4481 mLooper->wake();
4482}
4483
Michael Wrightd02c5b62014-02-10 15:10:22 -08004484void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004485 if (DEBUG_FOCUS) {
4486 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
4487 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004488
4489 bool changed;
4490 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004491 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004492
4493 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
4494 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004495 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004496 }
4497
4498 if (mDispatchEnabled && !enabled) {
4499 resetAndDropEverythingLocked("dispatcher is being disabled");
4500 }
4501
4502 mDispatchEnabled = enabled;
4503 mDispatchFrozen = frozen;
4504 changed = true;
4505 } else {
4506 changed = false;
4507 }
4508
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004509 if (DEBUG_FOCUS) {
4510 logDispatchStateLocked();
4511 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004512 } // release lock
4513
4514 if (changed) {
4515 // Wake up poll loop since it may need to make new input dispatching choices.
4516 mLooper->wake();
4517 }
4518}
4519
4520void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004521 if (DEBUG_FOCUS) {
4522 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
4523 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004524
4525 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004526 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004527
4528 if (mInputFilterEnabled == enabled) {
4529 return;
4530 }
4531
4532 mInputFilterEnabled = enabled;
4533 resetAndDropEverythingLocked("input filter is being enabled or disabled");
4534 } // release lock
4535
4536 // Wake up poll loop since there might be work to do to drop everything.
4537 mLooper->wake();
4538}
4539
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08004540void InputDispatcher::setInTouchMode(bool inTouchMode) {
4541 std::scoped_lock lock(mLock);
4542 mInTouchMode = inTouchMode;
4543}
4544
Bernardo Rufinoea97d182020-08-19 14:43:14 +01004545void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
4546 if (opacity < 0 || opacity > 1) {
4547 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
4548 return;
4549 }
4550
4551 std::scoped_lock lock(mLock);
4552 mMaximumObscuringOpacityForTouch = opacity;
4553}
4554
4555void InputDispatcher::setBlockUntrustedTouchesMode(BlockUntrustedTouchesMode mode) {
4556 std::scoped_lock lock(mLock);
4557 mBlockUntrustedTouchesMode = mode;
4558}
4559
chaviwfbe5d9c2018-12-26 12:23:37 -08004560bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken) {
4561 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004562 if (DEBUG_FOCUS) {
4563 ALOGD("Trivial transfer to same window.");
4564 }
chaviwfbe5d9c2018-12-26 12:23:37 -08004565 return true;
4566 }
4567
Michael Wrightd02c5b62014-02-10 15:10:22 -08004568 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004569 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004570
chaviwfbe5d9c2018-12-26 12:23:37 -08004571 sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromToken);
4572 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toToken);
Yi Kong9b14ac62018-07-17 13:48:38 -07004573 if (fromWindowHandle == nullptr || toWindowHandle == nullptr) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004574 ALOGW("Cannot transfer focus because from or to window not found.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004575 return false;
4576 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004577 if (DEBUG_FOCUS) {
4578 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
4579 fromWindowHandle->getName().c_str(), toWindowHandle->getName().c_str());
4580 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004581 if (fromWindowHandle->getInfo()->displayId != toWindowHandle->getInfo()->displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004582 if (DEBUG_FOCUS) {
4583 ALOGD("Cannot transfer focus because windows are on different displays.");
4584 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004585 return false;
4586 }
4587
4588 bool found = false;
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004589 for (std::pair<const int32_t, TouchState>& pair : mTouchStatesByDisplay) {
4590 TouchState& state = pair.second;
Jeff Brownf086ddb2014-02-11 14:28:48 -08004591 for (size_t i = 0; i < state.windows.size(); i++) {
4592 const TouchedWindow& touchedWindow = state.windows[i];
4593 if (touchedWindow.windowHandle == fromWindowHandle) {
4594 int32_t oldTargetFlags = touchedWindow.targetFlags;
4595 BitSet32 pointerIds = touchedWindow.pointerIds;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004596
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004597 state.windows.erase(state.windows.begin() + i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004598
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004599 int32_t newTargetFlags = oldTargetFlags &
4600 (InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_SPLIT |
4601 InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004602 state.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004603
Jeff Brownf086ddb2014-02-11 14:28:48 -08004604 found = true;
4605 goto Found;
4606 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004607 }
4608 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004609 Found:
Michael Wrightd02c5b62014-02-10 15:10:22 -08004610
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004611 if (!found) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004612 if (DEBUG_FOCUS) {
4613 ALOGD("Focus transfer failed because from window did not have focus.");
4614 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004615 return false;
4616 }
4617
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004618 sp<Connection> fromConnection = getConnectionLocked(fromToken);
4619 sp<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004620 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004621 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004622 CancelationOptions
4623 options(CancelationOptions::CANCEL_POINTER_EVENTS,
4624 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004625 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004626 synthesizePointerDownEventsForConnectionLocked(toConnection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004627 }
4628
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004629 if (DEBUG_FOCUS) {
4630 logDispatchStateLocked();
4631 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004632 } // release lock
4633
4634 // Wake up poll loop since it may need to make new input dispatching choices.
4635 mLooper->wake();
4636 return true;
4637}
4638
4639void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004640 if (DEBUG_FOCUS) {
4641 ALOGD("Resetting and dropping all events (%s).", reason);
4642 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004643
4644 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
4645 synthesizeCancelationEventsForAllConnectionsLocked(options);
4646
4647 resetKeyRepeatLocked();
4648 releasePendingEventLocked();
4649 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004650 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004651
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004652 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08004653 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004654 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07004655 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004656}
4657
4658void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004659 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004660 dumpDispatchStateLocked(dump);
4661
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004662 std::istringstream stream(dump);
4663 std::string line;
4664
4665 while (std::getline(stream, line, '\n')) {
4666 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004667 }
4668}
4669
Vishnu Nairad321cd2020-08-20 16:40:21 -07004670std::string InputDispatcher::dumpFocusedWindowsLocked() {
4671 if (mFocusedWindowTokenByDisplay.empty()) {
4672 return INDENT "FocusedWindows: <none>\n";
4673 }
4674
4675 std::string dump;
4676 dump += INDENT "FocusedWindows:\n";
4677 for (auto& it : mFocusedWindowTokenByDisplay) {
4678 const int32_t displayId = it.first;
4679 const sp<InputWindowHandle> windowHandle = getFocusedWindowHandleLocked(displayId);
4680 if (windowHandle) {
4681 dump += StringPrintf(INDENT2 "displayId=%" PRId32 ", name='%s'\n", displayId,
4682 windowHandle->getName().c_str());
4683 } else {
4684 dump += StringPrintf(INDENT2 "displayId=%" PRId32
4685 " has focused token without a window'\n",
4686 displayId);
4687 }
4688 }
4689 return dump;
4690}
4691
Siarhei Vishniakouad991402020-10-28 11:40:09 -05004692std::string InputDispatcher::dumpPendingFocusRequestsLocked() {
4693 if (mPendingFocusRequests.empty()) {
4694 return INDENT "mPendingFocusRequests: <none>\n";
4695 }
4696
4697 std::string dump;
4698 dump += INDENT "mPendingFocusRequests:\n";
4699 for (const auto& [displayId, focusRequest] : mPendingFocusRequests) {
4700 // Rather than printing raw values for focusRequest.token and focusRequest.focusedToken,
4701 // try to resolve them to actual windows.
4702 std::string windowName = getConnectionNameLocked(focusRequest.token);
4703 std::string focusedWindowName = getConnectionNameLocked(focusRequest.focusedToken);
4704 dump += StringPrintf(INDENT2 "displayId=%" PRId32 ", token->%s, focusedToken->%s\n",
4705 displayId, windowName.c_str(), focusedWindowName.c_str());
4706 }
4707 return dump;
4708}
4709
Prabir Pradhan99987712020-11-10 18:43:05 -08004710std::string InputDispatcher::dumpPointerCaptureStateLocked() {
4711 std::string dump;
4712
4713 dump += StringPrintf(INDENT "FocusedWindowRequestedPointerCapture: %s\n",
4714 toString(mFocusedWindowRequestedPointerCapture));
4715
4716 std::string windowName = "None";
4717 if (mWindowTokenWithPointerCapture) {
4718 const sp<InputWindowHandle> captureWindowHandle =
4719 getWindowHandleLocked(mWindowTokenWithPointerCapture);
4720 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
4721 : "token has capture without window";
4722 }
4723 dump += StringPrintf(INDENT "CurrentWindowWithPointerCapture: %s\n", windowName.c_str());
4724
4725 return dump;
4726}
4727
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004728void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07004729 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
4730 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
4731 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08004732 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004733
Tiger Huang721e26f2018-07-24 22:26:19 +08004734 if (!mFocusedApplicationHandlesByDisplay.empty()) {
4735 dump += StringPrintf(INDENT "FocusedApplications:\n");
4736 for (auto& it : mFocusedApplicationHandlesByDisplay) {
4737 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07004738 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05004739 const std::chrono::duration timeout =
4740 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004741 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004742 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05004743 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08004744 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004745 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08004746 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004747 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004748
Vishnu Nairad321cd2020-08-20 16:40:21 -07004749 dump += dumpFocusedWindowsLocked();
Siarhei Vishniakouad991402020-10-28 11:40:09 -05004750 dump += dumpPendingFocusRequestsLocked();
Prabir Pradhan99987712020-11-10 18:43:05 -08004751 dump += dumpPointerCaptureStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004752
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004753 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004754 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004755 for (const std::pair<int32_t, TouchState>& pair : mTouchStatesByDisplay) {
4756 const TouchState& state = pair.second;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004757 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004758 state.displayId, toString(state.down), toString(state.split),
4759 state.deviceId, state.source);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004760 if (!state.windows.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004761 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004762 for (size_t i = 0; i < state.windows.size(); i++) {
4763 const TouchedWindow& touchedWindow = state.windows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004764 dump += StringPrintf(INDENT4
4765 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
4766 i, touchedWindow.windowHandle->getName().c_str(),
4767 touchedWindow.pointerIds.value, touchedWindow.targetFlags);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004768 }
4769 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004770 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004771 }
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004772 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004773 dump += INDENT3 "Portal windows:\n";
4774 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004775 const sp<InputWindowHandle> portalWindowHandle = state.portalWindows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004776 dump += StringPrintf(INDENT4 "%zu: name='%s'\n", i,
4777 portalWindowHandle->getName().c_str());
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004778 }
4779 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004780 }
4781 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004782 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004783 }
4784
Arthur Hungb92218b2018-08-14 12:00:21 +08004785 if (!mWindowHandlesByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004786 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004787 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
Arthur Hung3b413f22018-10-26 18:05:34 +08004788 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", it.first);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004789 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004790 dump += INDENT2 "Windows:\n";
4791 for (size_t i = 0; i < windowHandles.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004792 const sp<InputWindowHandle>& windowHandle = windowHandles[i];
Arthur Hungb92218b2018-08-14 12:00:21 +08004793 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004794
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00004795 dump += StringPrintf(INDENT3 "%zu: name='%s', id=%" PRId32 ", displayId=%d, "
Vishnu Nair47074b82020-08-14 11:54:47 -07004796 "portalToDisplayId=%d, paused=%s, focusable=%s, "
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00004797 "hasWallpaper=%s, visible=%s, alpha=%.2f, "
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00004798 "flags=%s, type=%s, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004799 "frame=[%d,%d][%d,%d], globalScale=%f, "
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004800 "applicationInfo=%s, "
chaviw1ff3d1e2020-07-01 15:53:47 -07004801 "touchableRegion=",
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00004802 i, windowInfo->name.c_str(), windowInfo->id,
4803 windowInfo->displayId, windowInfo->portalToDisplayId,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004804 toString(windowInfo->paused),
Vishnu Nair47074b82020-08-14 11:54:47 -07004805 toString(windowInfo->focusable),
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004806 toString(windowInfo->hasWallpaper),
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00004807 toString(windowInfo->visible), windowInfo->alpha,
Michael Wright8759d672020-07-21 00:46:45 +01004808 windowInfo->flags.string().c_str(),
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00004809 NamedEnum::string(windowInfo->type).c_str(),
Michael Wright44753b12020-07-08 13:48:11 +01004810 windowInfo->frameLeft, windowInfo->frameTop,
4811 windowInfo->frameRight, windowInfo->frameBottom,
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004812 windowInfo->globalScaleFactor,
4813 windowInfo->applicationInfo.name.c_str());
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00004814 dump += dumpRegion(windowInfo->touchableRegion);
Michael Wright44753b12020-07-08 13:48:11 +01004815 dump += StringPrintf(", inputFeatures=%s",
4816 windowInfo->inputFeatures.string().c_str());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004817 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%" PRId64
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00004818 "ms, trustedOverlay=%s, hasToken=%s, "
4819 "touchOcclusionMode=%s\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004820 windowInfo->ownerPid, windowInfo->ownerUid,
Bernardo Rufinoc2f1fad2020-11-04 17:30:57 +00004821 millis(windowInfo->dispatchingTimeout),
4822 toString(windowInfo->trustedOverlay),
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00004823 toString(windowInfo->token != nullptr),
4824 toString(windowInfo->touchOcclusionMode).c_str());
chaviw85b44202020-07-24 11:46:21 -07004825 windowInfo->transform.dump(dump, "transform", INDENT4);
Arthur Hungb92218b2018-08-14 12:00:21 +08004826 }
4827 } else {
4828 dump += INDENT2 "Windows: <none>\n";
4829 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004830 }
4831 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08004832 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004833 }
4834
Michael Wright3dd60e22019-03-27 22:06:44 +00004835 if (!mGlobalMonitorsByDisplay.empty() || !mGestureMonitorsByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004836 for (auto& it : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004837 const std::vector<Monitor>& monitors = it.second;
4838 dump += StringPrintf(INDENT "Global monitors in display %" PRId32 ":\n", it.first);
4839 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004840 }
4841 for (auto& it : mGestureMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004842 const std::vector<Monitor>& monitors = it.second;
4843 dump += StringPrintf(INDENT "Gesture monitors in display %" PRId32 ":\n", it.first);
4844 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004845 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004846 } else {
Michael Wright3dd60e22019-03-27 22:06:44 +00004847 dump += INDENT "Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004848 }
4849
4850 nsecs_t currentTime = now();
4851
4852 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004853 if (!mRecentQueue.empty()) {
4854 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004855 for (std::shared_ptr<EventEntry>& entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004856 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05004857 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004858 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004859 }
4860 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004861 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004862 }
4863
4864 // Dump event currently being dispatched.
4865 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004866 dump += INDENT "PendingEvent:\n";
4867 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05004868 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004869 dump += StringPrintf(", age=%" PRId64 "ms\n",
4870 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004871 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004872 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004873 }
4874
4875 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004876 if (!mInboundQueue.empty()) {
4877 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004878 for (std::shared_ptr<EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004879 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05004880 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004881 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004882 }
4883 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004884 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004885 }
4886
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004887 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004888 dump += INDENT "ReplacedKeys:\n";
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004889 for (const std::pair<KeyReplacement, int32_t>& pair : mReplacedKeys) {
4890 const KeyReplacement& replacement = pair.first;
4891 int32_t newKeyCode = pair.second;
4892 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004893 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07004894 }
4895 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004896 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07004897 }
4898
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004899 if (!mConnectionsByFd.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004900 dump += INDENT "Connections:\n";
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004901 for (const auto& pair : mConnectionsByFd) {
4902 const sp<Connection>& connection = pair.second;
4903 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004904 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004905 pair.first, connection->getInputChannelName().c_str(),
4906 connection->getWindowName().c_str(), connection->getStatusLabel(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004907 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004908
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004909 if (!connection->outboundQueue.empty()) {
4910 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
4911 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05004912 dump += dumpQueue(connection->outboundQueue, currentTime);
4913
Michael Wrightd02c5b62014-02-10 15:10:22 -08004914 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004915 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004916 }
4917
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004918 if (!connection->waitQueue.empty()) {
4919 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
4920 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05004921 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004922 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004923 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004924 }
4925 }
4926 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004927 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004928 }
4929
4930 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004931 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
4932 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004933 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004934 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004935 }
4936
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004937 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004938 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
4939 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
4940 ns2ms(mConfig.keyRepeatTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004941}
4942
Michael Wright3dd60e22019-03-27 22:06:44 +00004943void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
4944 const size_t numMonitors = monitors.size();
4945 for (size_t i = 0; i < numMonitors; i++) {
4946 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004947 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00004948 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
4949 dump += "\n";
4950 }
4951}
4952
Garfield Tan15601662020-09-22 15:32:38 -07004953base::Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(
4954 const std::string& name) {
4955#if DEBUG_CHANNEL_CREATION
4956 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004957#endif
4958
Garfield Tan15601662020-09-22 15:32:38 -07004959 std::shared_ptr<InputChannel> serverChannel;
4960 std::unique_ptr<InputChannel> clientChannel;
4961 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
4962
4963 if (result) {
4964 return base::Error(result) << "Failed to open input channel pair with name " << name;
4965 }
4966
Michael Wrightd02c5b62014-02-10 15:10:22 -08004967 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004968 std::scoped_lock _l(mLock);
Garfield Tan15601662020-09-22 15:32:38 -07004969 sp<Connection> connection = new Connection(serverChannel, false /*monitor*/, mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004970
Garfield Tan15601662020-09-22 15:32:38 -07004971 int fd = serverChannel->getFd();
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004972 mConnectionsByFd[fd] = connection;
Garfield Tan15601662020-09-22 15:32:38 -07004973 mInputChannelsByToken[serverChannel->getConnectionToken()] = serverChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004974
Michael Wrightd02c5b62014-02-10 15:10:22 -08004975 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
4976 } // release lock
4977
4978 // Wake the looper because some connections have changed.
4979 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07004980 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004981}
4982
Garfield Tan15601662020-09-22 15:32:38 -07004983base::Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(
Siarhei Vishniakou58cfc602020-12-14 23:21:30 +00004984 int32_t displayId, bool isGestureMonitor, const std::string& name, int32_t pid) {
Garfield Tan15601662020-09-22 15:32:38 -07004985 std::shared_ptr<InputChannel> serverChannel;
4986 std::unique_ptr<InputChannel> clientChannel;
4987 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
4988 if (result) {
4989 return base::Error(result) << "Failed to open input channel pair with name " << name;
4990 }
4991
Michael Wright3dd60e22019-03-27 22:06:44 +00004992 { // acquire lock
4993 std::scoped_lock _l(mLock);
4994
4995 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07004996 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
4997 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00004998 }
4999
Garfield Tan15601662020-09-22 15:32:38 -07005000 sp<Connection> connection = new Connection(serverChannel, true /*monitor*/, mIdGenerator);
Michael Wright3dd60e22019-03-27 22:06:44 +00005001
Garfield Tan15601662020-09-22 15:32:38 -07005002 const int fd = serverChannel->getFd();
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005003 mConnectionsByFd[fd] = connection;
Garfield Tan15601662020-09-22 15:32:38 -07005004 mInputChannelsByToken[serverChannel->getConnectionToken()] = serverChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005005
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005006 auto& monitorsByDisplay =
5007 isGestureMonitor ? mGestureMonitorsByDisplay : mGlobalMonitorsByDisplay;
Siarhei Vishniakou58cfc602020-12-14 23:21:30 +00005008 monitorsByDisplay[displayId].emplace_back(serverChannel, pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005009
5010 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
Michael Wright3dd60e22019-03-27 22:06:44 +00005011 }
Garfield Tan15601662020-09-22 15:32:38 -07005012
Michael Wright3dd60e22019-03-27 22:06:44 +00005013 // Wake the looper because some connections have changed.
5014 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005015 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005016}
5017
Garfield Tan15601662020-09-22 15:32:38 -07005018status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005019 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005020 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005021
Garfield Tan15601662020-09-22 15:32:38 -07005022 status_t status = removeInputChannelLocked(connectionToken, false /*notify*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005023 if (status) {
5024 return status;
5025 }
5026 } // release lock
5027
5028 // Wake the poll loop because removing the connection may have changed the current
5029 // synchronization state.
5030 mLooper->wake();
5031 return OK;
5032}
5033
Garfield Tan15601662020-09-22 15:32:38 -07005034status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
5035 bool notify) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005036 sp<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005037 if (connection == nullptr) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005038 ALOGW("Attempted to unregister already unregistered input channel");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005039 return BAD_VALUE;
5040 }
5041
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005042 removeConnectionLocked(connection);
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005043 mInputChannelsByToken.erase(connectionToken);
Robert Carr5c8a0262018-10-03 16:30:44 -07005044
Michael Wrightd02c5b62014-02-10 15:10:22 -08005045 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005046 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005047 }
5048
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005049 mLooper->removeFd(connection->inputChannel->getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005050
5051 nsecs_t currentTime = now();
5052 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
5053
5054 connection->status = Connection::STATUS_ZOMBIE;
5055 return OK;
5056}
5057
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005058void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
5059 removeMonitorChannelLocked(connectionToken, mGlobalMonitorsByDisplay);
5060 removeMonitorChannelLocked(connectionToken, mGestureMonitorsByDisplay);
Michael Wright3dd60e22019-03-27 22:06:44 +00005061}
5062
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005063void InputDispatcher::removeMonitorChannelLocked(
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005064 const sp<IBinder>& connectionToken,
Michael Wright3dd60e22019-03-27 22:06:44 +00005065 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005066 for (auto it = monitorsByDisplay.begin(); it != monitorsByDisplay.end();) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005067 std::vector<Monitor>& monitors = it->second;
5068 const size_t numMonitors = monitors.size();
5069 for (size_t i = 0; i < numMonitors; i++) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005070 if (monitors[i].inputChannel->getConnectionToken() == connectionToken) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005071 monitors.erase(monitors.begin() + i);
5072 break;
5073 }
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005074 }
Michael Wright3dd60e22019-03-27 22:06:44 +00005075 if (monitors.empty()) {
5076 it = monitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005077 } else {
5078 ++it;
5079 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005080 }
5081}
5082
Michael Wright3dd60e22019-03-27 22:06:44 +00005083status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
5084 { // acquire lock
5085 std::scoped_lock _l(mLock);
5086 std::optional<int32_t> foundDisplayId = findGestureMonitorDisplayByTokenLocked(token);
5087
5088 if (!foundDisplayId) {
5089 ALOGW("Attempted to pilfer pointers from an un-registered monitor or invalid token");
5090 return BAD_VALUE;
5091 }
5092 int32_t displayId = foundDisplayId.value();
5093
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005094 std::unordered_map<int32_t, TouchState>::iterator stateIt =
5095 mTouchStatesByDisplay.find(displayId);
5096 if (stateIt == mTouchStatesByDisplay.end()) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005097 ALOGW("Failed to pilfer pointers: no pointers on display %" PRId32 ".", displayId);
5098 return BAD_VALUE;
5099 }
5100
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005101 TouchState& state = stateIt->second;
Michael Wright3dd60e22019-03-27 22:06:44 +00005102 std::optional<int32_t> foundDeviceId;
5103 for (const TouchedMonitor& touchedMonitor : state.gestureMonitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005104 if (touchedMonitor.monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005105 foundDeviceId = state.deviceId;
5106 }
5107 }
5108 if (!foundDeviceId || !state.down) {
5109 ALOGW("Attempted to pilfer points from a monitor without any on-going pointer streams."
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005110 " Ignoring.");
Michael Wright3dd60e22019-03-27 22:06:44 +00005111 return BAD_VALUE;
5112 }
5113 int32_t deviceId = foundDeviceId.value();
5114
5115 // Send cancel events to all the input channels we're stealing from.
5116 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005117 "gesture monitor stole pointer stream");
Michael Wright3dd60e22019-03-27 22:06:44 +00005118 options.deviceId = deviceId;
5119 options.displayId = displayId;
5120 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005121 std::shared_ptr<InputChannel> channel =
5122 getInputChannelLocked(window.windowHandle->getToken());
Michael Wright3a240c42019-12-10 20:53:41 +00005123 if (channel != nullptr) {
5124 synthesizeCancelationEventsForInputChannelLocked(channel, options);
5125 }
Michael Wright3dd60e22019-03-27 22:06:44 +00005126 }
5127 // Then clear the current touch state so we stop dispatching to them as well.
5128 state.filterNonMonitors();
5129 }
5130 return OK;
5131}
5132
Prabir Pradhan99987712020-11-10 18:43:05 -08005133void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
5134 { // acquire lock
5135 std::scoped_lock _l(mLock);
5136 if (DEBUG_FOCUS) {
5137 const sp<InputWindowHandle> windowHandle = getWindowHandleLocked(windowToken);
5138 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
5139 windowHandle != nullptr ? windowHandle->getName().c_str()
5140 : "token without window");
5141 }
5142
5143 const sp<IBinder> focusedToken =
5144 getValueByKey(mFocusedWindowTokenByDisplay, mFocusedDisplayId);
5145 if (focusedToken != windowToken) {
5146 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
5147 enabled ? "enable" : "disable");
5148 return;
5149 }
5150
5151 if (enabled == mFocusedWindowRequestedPointerCapture) {
5152 ALOGW("Ignoring request to %s Pointer Capture: "
5153 "window has %s requested pointer capture.",
5154 enabled ? "enable" : "disable", enabled ? "already" : "not");
5155 return;
5156 }
5157
5158 mFocusedWindowRequestedPointerCapture = enabled;
5159 setPointerCaptureLocked(enabled);
5160 } // release lock
5161
5162 // Wake the thread to process command entries.
5163 mLooper->wake();
5164}
5165
Michael Wright3dd60e22019-03-27 22:06:44 +00005166std::optional<int32_t> InputDispatcher::findGestureMonitorDisplayByTokenLocked(
5167 const sp<IBinder>& token) {
5168 for (const auto& it : mGestureMonitorsByDisplay) {
5169 const std::vector<Monitor>& monitors = it.second;
5170 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005171 if (monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005172 return it.first;
5173 }
5174 }
5175 }
5176 return std::nullopt;
5177}
5178
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005179std::optional<int32_t> InputDispatcher::findMonitorPidByTokenLocked(const sp<IBinder>& token) {
5180 std::optional<int32_t> gesturePid = findMonitorPidByToken(mGestureMonitorsByDisplay, token);
5181 if (gesturePid.has_value()) {
5182 return gesturePid;
5183 }
5184 return findMonitorPidByToken(mGlobalMonitorsByDisplay, token);
5185}
5186
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005187sp<Connection> InputDispatcher::getConnectionLocked(const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005188 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005189 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08005190 }
5191
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005192 for (const auto& pair : mConnectionsByFd) {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005193 const sp<Connection>& connection = pair.second;
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005194 if (connection->inputChannel->getConnectionToken() == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005195 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005196 }
5197 }
Robert Carr4e670e52018-08-15 13:26:12 -07005198
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005199 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005200}
5201
Siarhei Vishniakouad991402020-10-28 11:40:09 -05005202std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
5203 sp<Connection> connection = getConnectionLocked(connectionToken);
5204 if (connection == nullptr) {
5205 return "<nullptr>";
5206 }
5207 return connection->getInputChannelName();
5208}
5209
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005210void InputDispatcher::removeConnectionLocked(const sp<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005211 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005212 removeByValue(mConnectionsByFd, connection);
5213}
5214
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005215void InputDispatcher::onDispatchCycleFinishedLocked(nsecs_t currentTime,
5216 const sp<Connection>& connection, uint32_t seq,
5217 bool handled) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005218 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5219 &InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005220 commandEntry->connection = connection;
5221 commandEntry->eventTime = currentTime;
5222 commandEntry->seq = seq;
5223 commandEntry->handled = handled;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005224 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005225}
5226
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005227void InputDispatcher::onDispatchCycleBrokenLocked(nsecs_t currentTime,
5228 const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005229 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005230 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005231
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005232 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5233 &InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005234 commandEntry->connection = connection;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005235 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005236}
5237
Vishnu Nairad321cd2020-08-20 16:40:21 -07005238void InputDispatcher::notifyFocusChangedLocked(const sp<IBinder>& oldToken,
5239 const sp<IBinder>& newToken) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005240 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5241 &InputDispatcher::doNotifyFocusChangedLockedInterruptible);
chaviw0c06c6e2019-01-09 13:27:07 -08005242 commandEntry->oldToken = oldToken;
5243 commandEntry->newToken = newToken;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005244 postCommandLocked(std::move(commandEntry));
Robert Carrf759f162018-11-13 12:57:11 -08005245}
5246
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005247void InputDispatcher::onAnrLocked(const sp<Connection>& connection) {
5248 if (connection == nullptr) {
5249 LOG_ALWAYS_FATAL("Caller must check for nullness");
5250 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005251 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
5252 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005253 if (connection->waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005254 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005255 connection->inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005256 return;
5257 }
5258 /**
5259 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
5260 * may not be the one that caused the timeout to occur. One possibility is that window timeout
5261 * has changed. This could cause newer entries to time out before the already dispatched
5262 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
5263 * processes the events linearly. So providing information about the oldest entry seems to be
5264 * most useful.
5265 */
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005266 DispatchEntry* oldestEntry = *connection->waitQueue.begin();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005267 const nsecs_t currentWait = now() - oldestEntry->deliveryTime;
5268 std::string reason =
5269 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005270 connection->inputChannel->getName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005271 ns2ms(currentWait),
5272 oldestEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005273 sp<IBinder> connectionToken = connection->inputChannel->getConnectionToken();
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06005274 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005275
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005276 processConnectionUnresponsiveLocked(*connection, std::move(reason));
5277
5278 // Stop waking up for events on this connection, it is already unresponsive
5279 cancelEventsForAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005280}
5281
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005282void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
5283 std::string reason =
5284 StringPrintf("%s does not have a focused window", application->getName().c_str());
5285 updateLastAnrStateLocked(*application, reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005286
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005287 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5288 &InputDispatcher::doNotifyNoFocusedWindowAnrLockedInterruptible);
5289 commandEntry->inputApplicationHandle = std::move(application);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005290 postCommandLocked(std::move(commandEntry));
5291}
5292
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00005293void InputDispatcher::onUntrustedTouchLocked(const std::string& obscuringPackage) {
5294 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5295 &InputDispatcher::doNotifyUntrustedTouchLockedInterruptible);
5296 commandEntry->obscuringPackage = obscuringPackage;
5297 postCommandLocked(std::move(commandEntry));
5298}
5299
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005300void InputDispatcher::updateLastAnrStateLocked(const sp<InputWindowHandle>& window,
5301 const std::string& reason) {
5302 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
5303 updateLastAnrStateLocked(windowLabel, reason);
5304}
5305
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005306void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
5307 const std::string& reason) {
5308 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005309 updateLastAnrStateLocked(windowLabel, reason);
5310}
5311
5312void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
5313 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005314 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07005315 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005316 struct tm tm;
5317 localtime_r(&t, &tm);
5318 char timestr[64];
5319 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005320 mLastAnrState.clear();
5321 mLastAnrState += INDENT "ANR:\n";
5322 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005323 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
5324 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005325 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005326}
5327
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005328void InputDispatcher::doNotifyConfigurationChangedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005329 mLock.unlock();
5330
5331 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
5332
5333 mLock.lock();
5334}
5335
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005336void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005337 sp<Connection> connection = commandEntry->connection;
5338
5339 if (connection->status != Connection::STATUS_ZOMBIE) {
5340 mLock.unlock();
5341
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005342 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005343
5344 mLock.lock();
5345 }
5346}
5347
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005348void InputDispatcher::doNotifyFocusChangedLockedInterruptible(CommandEntry* commandEntry) {
chaviw0c06c6e2019-01-09 13:27:07 -08005349 sp<IBinder> oldToken = commandEntry->oldToken;
5350 sp<IBinder> newToken = commandEntry->newToken;
Robert Carrf759f162018-11-13 12:57:11 -08005351 mLock.unlock();
chaviw0c06c6e2019-01-09 13:27:07 -08005352 mPolicy->notifyFocusChanged(oldToken, newToken);
Robert Carrf759f162018-11-13 12:57:11 -08005353 mLock.lock();
5354}
5355
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005356void InputDispatcher::doNotifyNoFocusedWindowAnrLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005357 mLock.unlock();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005358
5359 mPolicy->notifyNoFocusedWindowAnr(commandEntry->inputApplicationHandle);
5360
5361 mLock.lock();
5362}
5363
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005364void InputDispatcher::doNotifyWindowUnresponsiveLockedInterruptible(CommandEntry* commandEntry) {
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005365 mLock.unlock();
5366
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005367 mPolicy->notifyWindowUnresponsive(commandEntry->connectionToken, commandEntry->reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005368
5369 mLock.lock();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005370}
5371
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005372void InputDispatcher::doNotifyMonitorUnresponsiveLockedInterruptible(CommandEntry* commandEntry) {
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005373 mLock.unlock();
5374
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005375 mPolicy->notifyMonitorUnresponsive(commandEntry->pid, commandEntry->reason);
5376
5377 mLock.lock();
5378}
5379
5380void InputDispatcher::doNotifyWindowResponsiveLockedInterruptible(CommandEntry* commandEntry) {
5381 mLock.unlock();
5382
5383 mPolicy->notifyWindowResponsive(commandEntry->connectionToken);
5384
5385 mLock.lock();
5386}
5387
5388void InputDispatcher::doNotifyMonitorResponsiveLockedInterruptible(CommandEntry* commandEntry) {
5389 mLock.unlock();
5390
5391 mPolicy->notifyMonitorResponsive(commandEntry->pid);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005392
5393 mLock.lock();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005394}
5395
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00005396void InputDispatcher::doNotifyUntrustedTouchLockedInterruptible(CommandEntry* commandEntry) {
5397 mLock.unlock();
5398
5399 mPolicy->notifyUntrustedTouch(commandEntry->obscuringPackage);
5400
5401 mLock.lock();
5402}
5403
Michael Wrightd02c5b62014-02-10 15:10:22 -08005404void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
5405 CommandEntry* commandEntry) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005406 KeyEntry& entry = *(commandEntry->keyEntry);
5407 KeyEvent event = createKeyEvent(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005408
5409 mLock.unlock();
5410
Michael Wright2b3c3302018-03-02 17:19:13 +00005411 android::base::Timer t;
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06005412 const sp<IBinder>& token = commandEntry->connectionToken;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005413 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(token, &event, entry.policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00005414 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
5415 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005416 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00005417 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005418
5419 mLock.lock();
5420
5421 if (delay < 0) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005422 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005423 } else if (!delay) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005424 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005425 } else {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005426 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
5427 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005428 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005429}
5430
chaviwfd6d3512019-03-25 13:23:49 -07005431void InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible(CommandEntry* commandEntry) {
5432 mLock.unlock();
5433 mPolicy->onPointerDownOutsideFocus(commandEntry->newToken);
5434 mLock.lock();
5435}
5436
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005437/**
5438 * Connection is responsive if it has no events in the waitQueue that are older than the
5439 * current time.
5440 */
5441static bool isConnectionResponsive(const Connection& connection) {
5442 const nsecs_t currentTime = now();
5443 for (const DispatchEntry* entry : connection.waitQueue) {
5444 if (entry->timeoutTime < currentTime) {
5445 return false;
5446 }
5447 }
5448 return true;
5449}
5450
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005451void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005452 sp<Connection> connection = commandEntry->connection;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005453 const nsecs_t finishTime = commandEntry->eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005454 uint32_t seq = commandEntry->seq;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005455 const bool handled = commandEntry->handled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005456
5457 // Handle post-event policy actions.
Garfield Tane84e6f92019-08-29 17:28:41 -07005458 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005459 if (dispatchEntryIt == connection->waitQueue.end()) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005460 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005461 }
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005462 DispatchEntry* dispatchEntry = *dispatchEntryIt;
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07005463 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005464 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005465 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
5466 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005467 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07005468 reportDispatchStatistics(std::chrono::nanoseconds(eventDuration), *connection, handled);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005469
5470 bool restartEvent;
Siarhei Vishniakou49483272019-10-22 13:13:47 -07005471 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005472 KeyEntry& keyEntry = static_cast<KeyEntry&>(*(dispatchEntry->eventEntry));
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005473 restartEvent =
5474 afterKeyEventLockedInterruptible(connection, dispatchEntry, keyEntry, handled);
Siarhei Vishniakou49483272019-10-22 13:13:47 -07005475 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005476 MotionEntry& motionEntry = static_cast<MotionEntry&>(*(dispatchEntry->eventEntry));
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005477 restartEvent = afterMotionEventLockedInterruptible(connection, dispatchEntry, motionEntry,
5478 handled);
5479 } else {
5480 restartEvent = false;
5481 }
5482
5483 // Dequeue the event and start the next cycle.
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07005484 // Because the lock might have been released, it is possible that the
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005485 // contents of the wait queue to have been drained, so we need to double-check
5486 // a few things.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005487 dispatchEntryIt = connection->findWaitQueueEntry(seq);
5488 if (dispatchEntryIt != connection->waitQueue.end()) {
5489 dispatchEntry = *dispatchEntryIt;
5490 connection->waitQueue.erase(dispatchEntryIt);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005491 const sp<IBinder>& connectionToken = connection->inputChannel->getConnectionToken();
5492 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005493 if (!connection->responsive) {
5494 connection->responsive = isConnectionResponsive(*connection);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005495 if (connection->responsive) {
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005496 // The connection was unresponsive, and now it's responsive.
5497 processConnectionResponsiveLocked(*connection);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005498 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005499 }
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005500 traceWaitQueueLength(connection);
5501 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005502 connection->outboundQueue.push_front(dispatchEntry);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005503 traceOutboundQueueLength(connection);
5504 } else {
5505 releaseDispatchEntry(dispatchEntry);
5506 }
5507 }
5508
5509 // Start the next dispatch cycle for this connection.
5510 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005511}
5512
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005513void InputDispatcher::sendMonitorUnresponsiveCommandLocked(int32_t pid, std::string reason) {
5514 std::unique_ptr<CommandEntry> monitorUnresponsiveCommand = std::make_unique<CommandEntry>(
5515 &InputDispatcher::doNotifyMonitorUnresponsiveLockedInterruptible);
5516 monitorUnresponsiveCommand->pid = pid;
5517 monitorUnresponsiveCommand->reason = std::move(reason);
5518 postCommandLocked(std::move(monitorUnresponsiveCommand));
5519}
5520
5521void InputDispatcher::sendWindowUnresponsiveCommandLocked(sp<IBinder> connectionToken,
5522 std::string reason) {
5523 std::unique_ptr<CommandEntry> windowUnresponsiveCommand = std::make_unique<CommandEntry>(
5524 &InputDispatcher::doNotifyWindowUnresponsiveLockedInterruptible);
5525 windowUnresponsiveCommand->connectionToken = std::move(connectionToken);
5526 windowUnresponsiveCommand->reason = std::move(reason);
5527 postCommandLocked(std::move(windowUnresponsiveCommand));
5528}
5529
5530void InputDispatcher::sendMonitorResponsiveCommandLocked(int32_t pid) {
5531 std::unique_ptr<CommandEntry> monitorResponsiveCommand = std::make_unique<CommandEntry>(
5532 &InputDispatcher::doNotifyMonitorResponsiveLockedInterruptible);
5533 monitorResponsiveCommand->pid = pid;
5534 postCommandLocked(std::move(monitorResponsiveCommand));
5535}
5536
5537void InputDispatcher::sendWindowResponsiveCommandLocked(sp<IBinder> connectionToken) {
5538 std::unique_ptr<CommandEntry> windowResponsiveCommand = std::make_unique<CommandEntry>(
5539 &InputDispatcher::doNotifyWindowResponsiveLockedInterruptible);
5540 windowResponsiveCommand->connectionToken = std::move(connectionToken);
5541 postCommandLocked(std::move(windowResponsiveCommand));
5542}
5543
5544/**
5545 * Tell the policy that a connection has become unresponsive so that it can start ANR.
5546 * Check whether the connection of interest is a monitor or a window, and add the corresponding
5547 * command entry to the command queue.
5548 */
5549void InputDispatcher::processConnectionUnresponsiveLocked(const Connection& connection,
5550 std::string reason) {
5551 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
5552 if (connection.monitor) {
5553 ALOGW("Monitor %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
5554 reason.c_str());
5555 std::optional<int32_t> pid = findMonitorPidByTokenLocked(connectionToken);
5556 if (!pid.has_value()) {
5557 ALOGE("Could not find unresponsive monitor for connection %s",
5558 connection.inputChannel->getName().c_str());
5559 return;
5560 }
5561 sendMonitorUnresponsiveCommandLocked(pid.value(), std::move(reason));
5562 return;
5563 }
5564 // If not a monitor, must be a window
5565 ALOGW("Window %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
5566 reason.c_str());
5567 sendWindowUnresponsiveCommandLocked(connectionToken, std::move(reason));
5568}
5569
5570/**
5571 * Tell the policy that a connection has become responsive so that it can stop ANR.
5572 */
5573void InputDispatcher::processConnectionResponsiveLocked(const Connection& connection) {
5574 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
5575 if (connection.monitor) {
5576 std::optional<int32_t> pid = findMonitorPidByTokenLocked(connectionToken);
5577 if (!pid.has_value()) {
5578 ALOGE("Could not find responsive monitor for connection %s",
5579 connection.inputChannel->getName().c_str());
5580 return;
5581 }
5582 sendMonitorResponsiveCommandLocked(pid.value());
5583 return;
5584 }
5585 // If not a monitor, must be a window
5586 sendWindowResponsiveCommandLocked(connectionToken);
5587}
5588
Michael Wrightd02c5b62014-02-10 15:10:22 -08005589bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005590 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005591 KeyEntry& keyEntry, bool handled) {
5592 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005593 if (!handled) {
5594 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005595 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005596 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005597 return false;
5598 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005599
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005600 // Get the fallback key state.
5601 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005602 int32_t originalKeyCode = keyEntry.keyCode;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005603 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005604 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005605 connection->inputState.removeFallbackKey(originalKeyCode);
5606 }
5607
5608 if (handled || !dispatchEntry->hasForegroundTarget()) {
5609 // If the application handles the original key for which we previously
5610 // generated a fallback or if the window is not a foreground window,
5611 // then cancel the associated fallback key, if any.
5612 if (fallbackKeyCode != -1) {
5613 // Dispatch the unhandled key to the policy with the cancel flag.
Michael Wrightd02c5b62014-02-10 15:10:22 -08005614#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005615 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005616 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005617 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005618#endif
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005619 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005620 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005621
5622 mLock.unlock();
5623
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005624 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005625 keyEntry.policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005626
5627 mLock.lock();
5628
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005629 // Cancel the fallback key.
5630 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005631 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005632 "application handled the original non-fallback key "
5633 "or is no longer a foreground target, "
5634 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005635 options.keyCode = fallbackKeyCode;
5636 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005637 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005638 connection->inputState.removeFallbackKey(originalKeyCode);
5639 }
5640 } else {
5641 // If the application did not handle a non-fallback key, first check
5642 // that we are in a good state to perform unhandled key event processing
5643 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005644 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005645 if (fallbackKeyCode == -1 && !initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005646#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005647 ALOGD("Unhandled key event: Skipping unhandled key event processing "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005648 "since this is not an initial down. "
5649 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005650 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005651#endif
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005652 return false;
5653 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005654
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005655 // Dispatch the unhandled key to the policy.
5656#if DEBUG_OUTBOUND_EVENT_DETAILS
5657 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005658 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005659 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005660#endif
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005661 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005662
5663 mLock.unlock();
5664
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005665 bool fallback =
5666 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005667 &event, keyEntry.policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005668
5669 mLock.lock();
5670
5671 if (connection->status != Connection::STATUS_NORMAL) {
5672 connection->inputState.removeFallbackKey(originalKeyCode);
5673 return false;
5674 }
5675
5676 // Latch the fallback keycode for this key on an initial down.
5677 // The fallback keycode cannot change at any other point in the lifecycle.
5678 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005679 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005680 fallbackKeyCode = event.getKeyCode();
5681 } else {
5682 fallbackKeyCode = AKEYCODE_UNKNOWN;
5683 }
5684 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
5685 }
5686
5687 ALOG_ASSERT(fallbackKeyCode != -1);
5688
5689 // Cancel the fallback key if the policy decides not to send it anymore.
5690 // We will continue to dispatch the key to the policy but we will no
5691 // longer dispatch a fallback key to the application.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005692 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
5693 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005694#if DEBUG_OUTBOUND_EVENT_DETAILS
5695 if (fallback) {
5696 ALOGD("Unhandled key event: Policy requested to send key %d"
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005697 "as a fallback for %d, but on the DOWN it had requested "
5698 "to send %d instead. Fallback canceled.",
5699 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005700 } else {
5701 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005702 "but on the DOWN it had requested to send %d. "
5703 "Fallback canceled.",
5704 originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005705 }
5706#endif
5707
5708 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
5709 "canceling fallback, policy no longer desires it");
5710 options.keyCode = fallbackKeyCode;
5711 synthesizeCancelationEventsForConnectionLocked(connection, options);
5712
5713 fallback = false;
5714 fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005715 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005716 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005717 }
5718 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005719
5720#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005721 {
5722 std::string msg;
5723 const KeyedVector<int32_t, int32_t>& fallbackKeys =
5724 connection->inputState.getFallbackKeys();
5725 for (size_t i = 0; i < fallbackKeys.size(); i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005726 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005727 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005728 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005729 fallbackKeys.size(), msg.c_str());
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005730 }
5731#endif
5732
5733 if (fallback) {
5734 // Restart the dispatch cycle using the fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005735 keyEntry.eventTime = event.getEventTime();
5736 keyEntry.deviceId = event.getDeviceId();
5737 keyEntry.source = event.getSource();
5738 keyEntry.displayId = event.getDisplayId();
5739 keyEntry.flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
5740 keyEntry.keyCode = fallbackKeyCode;
5741 keyEntry.scanCode = event.getScanCode();
5742 keyEntry.metaState = event.getMetaState();
5743 keyEntry.repeatCount = event.getRepeatCount();
5744 keyEntry.downTime = event.getDownTime();
5745 keyEntry.syntheticRepeat = false;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005746
5747#if DEBUG_OUTBOUND_EVENT_DETAILS
5748 ALOGD("Unhandled key event: Dispatching fallback key. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005749 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005750 originalKeyCode, fallbackKeyCode, keyEntry.metaState);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005751#endif
5752 return true; // restart the event
5753 } else {
5754#if DEBUG_OUTBOUND_EVENT_DETAILS
5755 ALOGD("Unhandled key event: No fallback key.");
5756#endif
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005757
5758 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005759 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005760 }
5761 }
5762 return false;
5763}
5764
5765bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005766 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005767 MotionEntry& motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005768 return false;
5769}
5770
5771void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
5772 mLock.unlock();
5773
5774 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType);
5775
5776 mLock.lock();
5777}
5778
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07005779void InputDispatcher::reportDispatchStatistics(std::chrono::nanoseconds eventDuration,
5780 const Connection& connection, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005781 // TODO Write some statistics about how long we spend waiting.
5782}
5783
Siarhei Vishniakoude4bf152019-08-16 11:12:52 -05005784/**
5785 * Report the touch event latency to the statsd server.
5786 * Input events are reported for statistics if:
5787 * - This is a touchscreen event
5788 * - InputFilter is not enabled
5789 * - Event is not injected or synthesized
5790 *
5791 * Statistics should be reported before calling addValue, to prevent a fresh new sample
5792 * from getting aggregated with the "old" data.
5793 */
5794void InputDispatcher::reportTouchEventForStatistics(const MotionEntry& motionEntry)
5795 REQUIRES(mLock) {
5796 const bool reportForStatistics = (motionEntry.source == AINPUT_SOURCE_TOUCHSCREEN) &&
5797 !(motionEntry.isSynthesized()) && !mInputFilterEnabled;
5798 if (!reportForStatistics) {
5799 return;
5800 }
5801
5802 if (mTouchStatistics.shouldReport()) {
5803 android::util::stats_write(android::util::TOUCH_EVENT_REPORTED, mTouchStatistics.getMin(),
5804 mTouchStatistics.getMax(), mTouchStatistics.getMean(),
5805 mTouchStatistics.getStDev(), mTouchStatistics.getCount());
5806 mTouchStatistics.reset();
5807 }
5808 const float latencyMicros = nanoseconds_to_microseconds(now() - motionEntry.eventTime);
5809 mTouchStatistics.addValue(latencyMicros);
5810}
5811
Michael Wrightd02c5b62014-02-10 15:10:22 -08005812void InputDispatcher::traceInboundQueueLengthLocked() {
5813 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005814 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005815 }
5816}
5817
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08005818void InputDispatcher::traceOutboundQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005819 if (ATRACE_ENABLED()) {
5820 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08005821 snprintf(counterName, sizeof(counterName), "oq:%s", connection->getWindowName().c_str());
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005822 ATRACE_INT(counterName, connection->outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005823 }
5824}
5825
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08005826void InputDispatcher::traceWaitQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005827 if (ATRACE_ENABLED()) {
5828 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08005829 snprintf(counterName, sizeof(counterName), "wq:%s", connection->getWindowName().c_str());
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005830 ATRACE_INT(counterName, connection->waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005831 }
5832}
5833
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005834void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005835 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005836
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005837 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005838 dumpDispatchStateLocked(dump);
5839
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005840 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005841 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005842 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005843 }
5844}
5845
5846void InputDispatcher::monitor() {
5847 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005848 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005849 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005850 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005851}
5852
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08005853/**
5854 * Wake up the dispatcher and wait until it processes all events and commands.
5855 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
5856 * this method can be safely called from any thread, as long as you've ensured that
5857 * the work you are interested in completing has already been queued.
5858 */
5859bool InputDispatcher::waitForIdle() {
5860 /**
5861 * Timeout should represent the longest possible time that a device might spend processing
5862 * events and commands.
5863 */
5864 constexpr std::chrono::duration TIMEOUT = 100ms;
5865 std::unique_lock lock(mLock);
5866 mLooper->wake();
5867 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
5868 return result == std::cv_status::no_timeout;
5869}
5870
Vishnu Naire798b472020-07-23 13:52:21 -07005871/**
5872 * Sets focus to the window identified by the token. This must be called
5873 * after updating any input window handles.
5874 *
5875 * Params:
5876 * request.token - input channel token used to identify the window that should gain focus.
5877 * request.focusedToken - the token that the caller expects currently to be focused. If the
5878 * specified token does not match the currently focused window, this request will be dropped.
5879 * If the specified focused token matches the currently focused window, the call will succeed.
5880 * Set this to "null" if this call should succeed no matter what the currently focused token is.
5881 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
5882 * when requesting the focus change. This determines which request gets
5883 * precedence if there is a focus change request from another source such as pointer down.
5884 */
Vishnu Nair958da932020-08-21 17:12:37 -07005885void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
5886 { // acquire lock
5887 std::scoped_lock _l(mLock);
5888
5889 const int32_t displayId = request.displayId;
5890 const sp<IBinder> oldFocusedToken = getValueByKey(mFocusedWindowTokenByDisplay, displayId);
5891 if (request.focusedToken && oldFocusedToken != request.focusedToken) {
5892 ALOGD_IF(DEBUG_FOCUS,
5893 "setFocusedWindow on display %" PRId32
5894 " ignored, reason: focusedToken is not focused",
5895 displayId);
5896 return;
5897 }
5898
5899 mPendingFocusRequests.erase(displayId);
5900 FocusResult result = handleFocusRequestLocked(request);
5901 if (result == FocusResult::NOT_VISIBLE) {
5902 // The requested window is not currently visible. Wait for the window to become visible
5903 // and then provide it focus. This is to handle situations where a user action triggers
5904 // a new window to appear. We want to be able to queue any key events after the user
5905 // action and deliver it to the newly focused window. In order for this to happen, we
5906 // take focus from the currently focused window so key events can be queued.
5907 ALOGD_IF(DEBUG_FOCUS,
5908 "setFocusedWindow on display %" PRId32
5909 " pending, reason: window is not visible",
5910 displayId);
5911 mPendingFocusRequests[displayId] = request;
5912 onFocusChangedLocked(oldFocusedToken, nullptr, displayId,
5913 "setFocusedWindow_AwaitingWindowVisibility");
5914 } else if (result != FocusResult::OK) {
5915 ALOGW("setFocusedWindow on display %" PRId32 " ignored, reason:%s", displayId,
5916 typeToString(result));
5917 }
5918 } // release lock
5919 // Wake up poll loop since it may need to make new input dispatching choices.
5920 mLooper->wake();
5921}
5922
5923InputDispatcher::FocusResult InputDispatcher::handleFocusRequestLocked(
5924 const FocusRequest& request) {
5925 const int32_t displayId = request.displayId;
5926 const sp<IBinder> newFocusedToken = request.token;
5927 const sp<IBinder> oldFocusedToken = getValueByKey(mFocusedWindowTokenByDisplay, displayId);
5928
5929 if (oldFocusedToken == request.token) {
5930 ALOGD_IF(DEBUG_FOCUS,
5931 "setFocusedWindow on display %" PRId32 " ignored, reason: already focused",
5932 displayId);
5933 return FocusResult::OK;
5934 }
5935
5936 FocusResult result = checkTokenFocusableLocked(newFocusedToken, displayId);
5937 if (result != FocusResult::OK) {
5938 return result;
5939 }
5940
5941 std::string_view reason =
5942 (request.focusedToken) ? "setFocusedWindow_FocusCheck" : "setFocusedWindow";
5943 onFocusChangedLocked(oldFocusedToken, newFocusedToken, displayId, reason);
5944 return FocusResult::OK;
5945}
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005946
Vishnu Nairad321cd2020-08-20 16:40:21 -07005947void InputDispatcher::onFocusChangedLocked(const sp<IBinder>& oldFocusedToken,
5948 const sp<IBinder>& newFocusedToken, int32_t displayId,
5949 std::string_view reason) {
5950 if (oldFocusedToken) {
5951 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(oldFocusedToken);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005952 if (focusedInputChannel) {
5953 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
5954 "focus left window");
5955 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Vishnu Nairad321cd2020-08-20 16:40:21 -07005956 enqueueFocusEventLocked(oldFocusedToken, false /*hasFocus*/, reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005957 }
Vishnu Nairad321cd2020-08-20 16:40:21 -07005958 mFocusedWindowTokenByDisplay.erase(displayId);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005959 }
Vishnu Nairad321cd2020-08-20 16:40:21 -07005960 if (newFocusedToken) {
5961 mFocusedWindowTokenByDisplay[displayId] = newFocusedToken;
5962 enqueueFocusEventLocked(newFocusedToken, true /*hasFocus*/, reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005963 }
5964
Prabir Pradhan99987712020-11-10 18:43:05 -08005965 // If a window has pointer capture, then it must have focus. We need to ensure that this
5966 // contract is upheld when pointer capture is being disabled due to a loss of window focus.
5967 // If the window loses focus before it loses pointer capture, then the window can be in a state
5968 // where it has pointer capture but not focus, violating the contract. Therefore we must
5969 // dispatch the pointer capture event before the focus event. Since focus events are added to
5970 // the front of the queue (above), we add the pointer capture event to the front of the queue
5971 // after the focus events are added. This ensures the pointer capture event ends up at the
5972 // front.
5973 disablePointerCaptureForcedLocked();
5974
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005975 if (mFocusedDisplayId == displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005976 notifyFocusChangedLocked(oldFocusedToken, newFocusedToken);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005977 }
5978}
Vishnu Nair958da932020-08-21 17:12:37 -07005979
Prabir Pradhan99987712020-11-10 18:43:05 -08005980void InputDispatcher::disablePointerCaptureForcedLocked() {
5981 if (!mFocusedWindowRequestedPointerCapture && !mWindowTokenWithPointerCapture) {
5982 return;
5983 }
5984
5985 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
5986
5987 if (mFocusedWindowRequestedPointerCapture) {
5988 mFocusedWindowRequestedPointerCapture = false;
5989 setPointerCaptureLocked(false);
5990 }
5991
5992 if (!mWindowTokenWithPointerCapture) {
5993 // No need to send capture changes because no window has capture.
5994 return;
5995 }
5996
5997 if (mPendingEvent != nullptr) {
5998 // Move the pending event to the front of the queue. This will give the chance
5999 // for the pending event to be dropped if it is a captured event.
6000 mInboundQueue.push_front(mPendingEvent);
6001 mPendingEvent = nullptr;
6002 }
6003
6004 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
6005 false /* hasCapture */);
6006 mInboundQueue.push_front(std::move(entry));
6007}
6008
Vishnu Nair958da932020-08-21 17:12:37 -07006009/**
6010 * Checks if the window token can be focused on a display. The token can be focused if there is
6011 * at least one window handle that is visible with the same token and all window handles with the
6012 * same token are focusable.
6013 *
6014 * In the case of mirroring, two windows may share the same window token and their visibility
6015 * might be different. Example, the mirrored window can cover the window its mirroring. However,
6016 * we expect the focusability of the windows to match since its hard to reason why one window can
6017 * receive focus events and the other cannot when both are backed by the same input channel.
6018 */
6019InputDispatcher::FocusResult InputDispatcher::checkTokenFocusableLocked(const sp<IBinder>& token,
6020 int32_t displayId) const {
6021 bool allWindowsAreFocusable = true;
6022 bool visibleWindowFound = false;
6023 bool windowFound = false;
6024 for (const sp<InputWindowHandle>& window : getWindowHandlesLocked(displayId)) {
6025 if (window->getToken() != token) {
6026 continue;
6027 }
6028 windowFound = true;
6029 if (window->getInfo()->visible) {
6030 // Check if at least a single window is visible.
6031 visibleWindowFound = true;
6032 }
6033 if (!window->getInfo()->focusable) {
6034 // Check if all windows with the window token are focusable.
6035 allWindowsAreFocusable = false;
6036 break;
6037 }
6038 }
6039
6040 if (!windowFound) {
6041 return FocusResult::NO_WINDOW;
6042 }
6043 if (!allWindowsAreFocusable) {
6044 return FocusResult::NOT_FOCUSABLE;
6045 }
6046 if (!visibleWindowFound) {
6047 return FocusResult::NOT_VISIBLE;
6048 }
6049
6050 return FocusResult::OK;
6051}
Prabir Pradhan99987712020-11-10 18:43:05 -08006052
6053void InputDispatcher::setPointerCaptureLocked(bool enabled) {
6054 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
6055 &InputDispatcher::doSetPointerCaptureLockedInterruptible);
6056 commandEntry->enabled = enabled;
6057 postCommandLocked(std::move(commandEntry));
6058}
6059
6060void InputDispatcher::doSetPointerCaptureLockedInterruptible(
6061 android::inputdispatcher::CommandEntry* commandEntry) {
6062 mLock.unlock();
6063
6064 mPolicy->setPointerCapture(commandEntry->enabled);
6065
6066 mLock.lock();
6067}
6068
Garfield Tane84e6f92019-08-29 17:28:41 -07006069} // namespace android::inputdispatcher