blob: d0a5c09c800a6049e8f000f8ac5e6bdd3a15b4a1 [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
Bernardo Rufino49d99e42021-01-18 15:16:59 +0000130static inline const std::string toString(sp<IBinder> binder) {
131 if (binder == nullptr) {
132 return "<null>";
133 }
134 return StringPrintf("%p", binder.get());
135}
136
Michael Wrightd02c5b62014-02-10 15:10:22 -0800137static inline int32_t getMotionEventActionPointerIndex(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700138 return (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) >>
139 AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800140}
141
142static bool isValidKeyAction(int32_t action) {
143 switch (action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700144 case AKEY_EVENT_ACTION_DOWN:
145 case AKEY_EVENT_ACTION_UP:
146 return true;
147 default:
148 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800149 }
150}
151
152static bool validateKeyEvent(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700153 if (!isValidKeyAction(action)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800154 ALOGE("Key event has invalid action code 0x%x", action);
155 return false;
156 }
157 return true;
158}
159
Michael Wright7b159c92015-05-14 14:48:03 +0100160static bool isValidMotionAction(int32_t action, int32_t actionButton, int32_t pointerCount) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800161 switch (action & AMOTION_EVENT_ACTION_MASK) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700162 case AMOTION_EVENT_ACTION_DOWN:
163 case AMOTION_EVENT_ACTION_UP:
164 case AMOTION_EVENT_ACTION_CANCEL:
165 case AMOTION_EVENT_ACTION_MOVE:
166 case AMOTION_EVENT_ACTION_OUTSIDE:
167 case AMOTION_EVENT_ACTION_HOVER_ENTER:
168 case AMOTION_EVENT_ACTION_HOVER_MOVE:
169 case AMOTION_EVENT_ACTION_HOVER_EXIT:
170 case AMOTION_EVENT_ACTION_SCROLL:
171 return true;
172 case AMOTION_EVENT_ACTION_POINTER_DOWN:
173 case AMOTION_EVENT_ACTION_POINTER_UP: {
174 int32_t index = getMotionEventActionPointerIndex(action);
175 return index >= 0 && index < pointerCount;
176 }
177 case AMOTION_EVENT_ACTION_BUTTON_PRESS:
178 case AMOTION_EVENT_ACTION_BUTTON_RELEASE:
179 return actionButton != 0;
180 default:
181 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800182 }
183}
184
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -0500185static int64_t millis(std::chrono::nanoseconds t) {
186 return std::chrono::duration_cast<std::chrono::milliseconds>(t).count();
187}
188
Michael Wright7b159c92015-05-14 14:48:03 +0100189static bool validateMotionEvent(int32_t action, int32_t actionButton, size_t pointerCount,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700190 const PointerProperties* pointerProperties) {
191 if (!isValidMotionAction(action, actionButton, pointerCount)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800192 ALOGE("Motion event has invalid action code 0x%x", action);
193 return false;
194 }
195 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
Narayan Kamath37764c72014-03-27 14:21:09 +0000196 ALOGE("Motion event has invalid pointer count %zu; value must be between 1 and %d.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700197 pointerCount, MAX_POINTERS);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800198 return false;
199 }
200 BitSet32 pointerIdBits;
201 for (size_t i = 0; i < pointerCount; i++) {
202 int32_t id = pointerProperties[i].id;
203 if (id < 0 || id > MAX_POINTER_ID) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700204 ALOGE("Motion event has invalid pointer id %d; value must be between 0 and %d", id,
205 MAX_POINTER_ID);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800206 return false;
207 }
208 if (pointerIdBits.hasBit(id)) {
209 ALOGE("Motion event has duplicate pointer id %d", id);
210 return false;
211 }
212 pointerIdBits.markBit(id);
213 }
214 return true;
215}
216
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000217static std::string dumpRegion(const Region& region) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800218 if (region.isEmpty()) {
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000219 return "<empty>";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800220 }
221
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000222 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800223 bool first = true;
224 Region::const_iterator cur = region.begin();
225 Region::const_iterator const tail = region.end();
226 while (cur != tail) {
227 if (first) {
228 first = false;
229 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800230 dump += "|";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800231 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800232 dump += StringPrintf("[%d,%d][%d,%d]", cur->left, cur->top, cur->right, cur->bottom);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800233 cur++;
234 }
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000235 return dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800236}
237
Siarhei Vishniakou14411c92020-09-18 21:15:05 -0500238static std::string dumpQueue(const std::deque<DispatchEntry*>& queue, nsecs_t currentTime) {
239 constexpr size_t maxEntries = 50; // max events to print
240 constexpr size_t skipBegin = maxEntries / 2;
241 const size_t skipEnd = queue.size() - maxEntries / 2;
242 // skip from maxEntries / 2 ... size() - maxEntries/2
243 // only print from 0 .. skipBegin and then from skipEnd .. size()
244
245 std::string dump;
246 for (size_t i = 0; i < queue.size(); i++) {
247 const DispatchEntry& entry = *queue[i];
248 if (i >= skipBegin && i < skipEnd) {
249 dump += StringPrintf(INDENT4 "<skipped %zu entries>\n", skipEnd - skipBegin);
250 i = skipEnd - 1; // it will be incremented to "skipEnd" by 'continue'
251 continue;
252 }
253 dump.append(INDENT4);
254 dump += entry.eventEntry->getDescription();
255 dump += StringPrintf(", seq=%" PRIu32
256 ", targetFlags=0x%08x, resolvedAction=%d, age=%" PRId64 "ms",
257 entry.seq, entry.targetFlags, entry.resolvedAction,
258 ns2ms(currentTime - entry.eventEntry->eventTime));
259 if (entry.deliveryTime != 0) {
260 // This entry was delivered, so add information on how long we've been waiting
261 dump += StringPrintf(", wait=%" PRId64 "ms", ns2ms(currentTime - entry.deliveryTime));
262 }
263 dump.append("\n");
264 }
265 return dump;
266}
267
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700268/**
269 * Find the entry in std::unordered_map by key, and return it.
270 * If the entry is not found, return a default constructed entry.
271 *
272 * Useful when the entries are vectors, since an empty vector will be returned
273 * if the entry is not found.
274 * Also useful when the entries are sp<>. If an entry is not found, nullptr is returned.
275 */
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700276template <typename K, typename V>
277static V getValueByKey(const std::unordered_map<K, V>& map, K key) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700278 auto it = map.find(key);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700279 return it != map.end() ? it->second : V{};
Tiger Huang721e26f2018-07-24 22:26:19 +0800280}
281
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700282/**
283 * Find the entry in std::unordered_map by value, and remove it.
284 * If more than one entry has the same value, then all matching
285 * key-value pairs will be removed.
286 *
287 * Return true if at least one value has been removed.
288 */
289template <typename K, typename V>
290static bool removeByValue(std::unordered_map<K, V>& map, const V& value) {
291 bool removed = false;
292 for (auto it = map.begin(); it != map.end();) {
293 if (it->second == value) {
294 it = map.erase(it);
295 removed = true;
296 } else {
297 it++;
298 }
299 }
300 return removed;
301}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800302
chaviwaf87b3e2019-10-01 16:59:28 -0700303static bool haveSameToken(const sp<InputWindowHandle>& first, const sp<InputWindowHandle>& second) {
304 if (first == second) {
305 return true;
306 }
307
308 if (first == nullptr || second == nullptr) {
309 return false;
310 }
311
312 return first->getToken() == second->getToken();
313}
314
Bernardo Rufino1ff9d592021-01-18 16:58:57 +0000315static bool haveSameApplicationToken(const InputWindowInfo* first, const InputWindowInfo* second) {
316 if (first == nullptr || second == nullptr) {
317 return false;
318 }
319 return first->applicationInfo.token != nullptr &&
320 first->applicationInfo.token == second->applicationInfo.token;
321}
322
Siarhei Vishniakouadfd4fa2019-12-20 11:02:58 -0800323static bool isStaleEvent(nsecs_t currentTime, const EventEntry& entry) {
324 return currentTime - entry.eventTime >= STALE_EVENT_TIMEOUT;
325}
326
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000327static std::unique_ptr<DispatchEntry> createDispatchEntry(const InputTarget& inputTarget,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700328 std::shared_ptr<EventEntry> eventEntry,
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000329 int32_t inputTargetFlags) {
yunho.shinf4a80b82020-11-16 21:13:57 +0900330 if (eventEntry->type == EventEntry::Type::MOTION) {
331 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
332 if (motionEntry.source & AINPUT_SOURCE_CLASS_JOYSTICK) {
333 const ui::Transform identityTransform;
334 // Use identity transform for joystick events events because they don't depend on
335 // the window info
336 return std::make_unique<DispatchEntry>(eventEntry, inputTargetFlags, identityTransform,
337 1.0f /*globalScaleFactor*/);
338 }
339 }
340
chaviw1ff3d1e2020-07-01 15:53:47 -0700341 if (inputTarget.useDefaultPointerTransform()) {
342 const ui::Transform& transform = inputTarget.getDefaultPointerTransform();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700343 return std::make_unique<DispatchEntry>(eventEntry, inputTargetFlags, transform,
chaviw1ff3d1e2020-07-01 15:53:47 -0700344 inputTarget.globalScaleFactor);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000345 }
346
347 ALOG_ASSERT(eventEntry->type == EventEntry::Type::MOTION);
348 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
349
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700350 std::vector<PointerCoords> pointerCoords;
351 pointerCoords.resize(motionEntry.pointerCount);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000352
353 // Use the first pointer information to normalize all other pointers. This could be any pointer
354 // as long as all other pointers are normalized to the same value and the final DispatchEntry
chaviw1ff3d1e2020-07-01 15:53:47 -0700355 // uses the transform for the normalized pointer.
356 const ui::Transform& firstPointerTransform =
357 inputTarget.pointerTransforms[inputTarget.pointerIds.firstMarkedBit()];
358 ui::Transform inverseFirstTransform = firstPointerTransform.inverse();
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000359
360 // Iterate through all pointers in the event to normalize against the first.
361 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.pointerCount; pointerIndex++) {
362 const PointerProperties& pointerProperties = motionEntry.pointerProperties[pointerIndex];
363 uint32_t pointerId = uint32_t(pointerProperties.id);
chaviw1ff3d1e2020-07-01 15:53:47 -0700364 const ui::Transform& currTransform = inputTarget.pointerTransforms[pointerId];
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000365
366 pointerCoords[pointerIndex].copyFrom(motionEntry.pointerCoords[pointerIndex]);
chaviw1ff3d1e2020-07-01 15:53:47 -0700367 // First, apply the current pointer's transform to update the coordinates into
368 // window space.
369 pointerCoords[pointerIndex].transform(currTransform);
370 // Next, apply the inverse transform of the normalized coordinates so the
371 // current coordinates are transformed into the normalized coordinate space.
372 pointerCoords[pointerIndex].transform(inverseFirstTransform);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000373 }
374
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700375 std::unique_ptr<MotionEntry> combinedMotionEntry =
376 std::make_unique<MotionEntry>(motionEntry.id, motionEntry.eventTime,
377 motionEntry.deviceId, motionEntry.source,
378 motionEntry.displayId, motionEntry.policyFlags,
379 motionEntry.action, motionEntry.actionButton,
380 motionEntry.flags, motionEntry.metaState,
381 motionEntry.buttonState, motionEntry.classification,
382 motionEntry.edgeFlags, motionEntry.xPrecision,
383 motionEntry.yPrecision, motionEntry.xCursorPosition,
384 motionEntry.yCursorPosition, motionEntry.downTime,
385 motionEntry.pointerCount, motionEntry.pointerProperties,
386 pointerCoords.data(), 0 /* xOffset */, 0 /* yOffset */);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000387
388 if (motionEntry.injectionState) {
389 combinedMotionEntry->injectionState = motionEntry.injectionState;
390 combinedMotionEntry->injectionState->refCount += 1;
391 }
392
393 std::unique_ptr<DispatchEntry> dispatchEntry =
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700394 std::make_unique<DispatchEntry>(std::move(combinedMotionEntry), inputTargetFlags,
395 firstPointerTransform, inputTarget.globalScaleFactor);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000396 return dispatchEntry;
397}
398
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -0700399static void addGestureMonitors(const std::vector<Monitor>& monitors,
400 std::vector<TouchedMonitor>& outTouchedMonitors, float xOffset = 0,
401 float yOffset = 0) {
402 if (monitors.empty()) {
403 return;
404 }
405 outTouchedMonitors.reserve(monitors.size() + outTouchedMonitors.size());
406 for (const Monitor& monitor : monitors) {
407 outTouchedMonitors.emplace_back(monitor, xOffset, yOffset);
408 }
409}
410
Garfield Tan15601662020-09-22 15:32:38 -0700411static status_t openInputChannelPair(const std::string& name,
412 std::shared_ptr<InputChannel>& serverChannel,
413 std::unique_ptr<InputChannel>& clientChannel) {
414 std::unique_ptr<InputChannel> uniqueServerChannel;
415 status_t result = InputChannel::openInputChannelPair(name, uniqueServerChannel, clientChannel);
416
417 serverChannel = std::move(uniqueServerChannel);
418 return result;
419}
420
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500421template <typename T>
422static bool sharedPointersEqual(const std::shared_ptr<T>& lhs, const std::shared_ptr<T>& rhs) {
423 if (lhs == nullptr && rhs == nullptr) {
424 return true;
425 }
426 if (lhs == nullptr || rhs == nullptr) {
427 return false;
428 }
429 return *lhs == *rhs;
430}
431
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000432static sp<IPlatformCompatNative> getCompatService() {
433 sp<IBinder> service(defaultServiceManager()->getService(String16("platform_compat_native")));
434 if (service == nullptr) {
435 ALOGE("Failed to link to compat service");
436 return nullptr;
437 }
438 return interface_cast<IPlatformCompatNative>(service);
439}
440
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +0000441static KeyEvent createKeyEvent(const KeyEntry& entry) {
442 KeyEvent event;
443 event.initialize(entry.id, entry.deviceId, entry.source, entry.displayId, INVALID_HMAC,
444 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
445 entry.repeatCount, entry.downTime, entry.eventTime);
446 return event;
447}
448
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000449static std::optional<int32_t> findMonitorPidByToken(
450 const std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay,
451 const sp<IBinder>& token) {
452 for (const auto& it : monitorsByDisplay) {
453 const std::vector<Monitor>& monitors = it.second;
454 for (const Monitor& monitor : monitors) {
455 if (monitor.inputChannel->getConnectionToken() == token) {
456 return monitor.pid;
457 }
458 }
459 }
460 return std::nullopt;
461}
462
Michael Wrightd02c5b62014-02-10 15:10:22 -0800463// --- InputDispatcher ---
464
Garfield Tan00f511d2019-06-12 16:55:40 -0700465InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy)
466 : mPolicy(policy),
467 mPendingEvent(nullptr),
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700468 mLastDropReason(DropReason::NOT_DROPPED),
Garfield Tanff1f1bb2020-01-28 13:24:04 -0800469 mIdGenerator(IdGenerator::Source::INPUT_DISPATCHER),
Garfield Tan00f511d2019-06-12 16:55:40 -0700470 mAppSwitchSawKeyDown(false),
471 mAppSwitchDueTime(LONG_LONG_MAX),
472 mNextUnblockedEvent(nullptr),
473 mDispatchEnabled(false),
474 mDispatchFrozen(false),
475 mInputFilterEnabled(false),
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -0800476 // mInTouchMode will be initialized by the WindowManager to the default device config.
477 // To avoid leaking stack in case that call never comes, and for tests,
478 // initialize it here anyways.
479 mInTouchMode(true),
Bernardo Rufinoea97d182020-08-19 14:43:14 +0100480 mMaximumObscuringOpacityForTouch(1.0f),
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000481 mFocusedDisplayId(ADISPLAY_ID_DEFAULT),
Prabir Pradhan99987712020-11-10 18:43:05 -0800482 mFocusedWindowRequestedPointerCapture(false),
483 mWindowTokenWithPointerCapture(nullptr),
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000484 mCompatService(getCompatService()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800485 mLooper = new Looper(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800486 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800487
Yi Kong9b14ac62018-07-17 13:48:38 -0700488 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800489
490 policy->getDispatcherConfiguration(&mConfig);
491}
492
493InputDispatcher::~InputDispatcher() {
494 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800495 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800496
497 resetKeyRepeatLocked();
498 releasePendingEventLocked();
499 drainInboundQueueLocked();
500 }
501
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700502 while (!mConnectionsByFd.empty()) {
503 sp<Connection> connection = mConnectionsByFd.begin()->second;
Garfield Tan15601662020-09-22 15:32:38 -0700504 removeInputChannel(connection->inputChannel->getConnectionToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800505 }
506}
507
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700508status_t InputDispatcher::start() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700509 if (mThread) {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700510 return ALREADY_EXISTS;
511 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700512 mThread = std::make_unique<InputThread>(
513 "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
514 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700515}
516
517status_t InputDispatcher::stop() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700518 if (mThread && mThread->isCallingThread()) {
519 ALOGE("InputDispatcher cannot be stopped from its own thread!");
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700520 return INVALID_OPERATION;
521 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700522 mThread.reset();
523 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700524}
525
Michael Wrightd02c5b62014-02-10 15:10:22 -0800526void InputDispatcher::dispatchOnce() {
527 nsecs_t nextWakeupTime = LONG_LONG_MAX;
528 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800529 std::scoped_lock _l(mLock);
530 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800531
532 // Run a dispatch loop if there are no pending commands.
533 // The dispatch loop might enqueue commands to run afterwards.
534 if (!haveCommandsLocked()) {
535 dispatchOnceInnerLocked(&nextWakeupTime);
536 }
537
538 // Run all pending commands if there are any.
539 // If any commands were run then force the next poll to wake up immediately.
540 if (runCommandsLockedInterruptible()) {
541 nextWakeupTime = LONG_LONG_MIN;
542 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800543
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700544 // If we are still waiting for ack on some events,
545 // we might have to wake up earlier to check if an app is anr'ing.
546 const nsecs_t nextAnrCheck = processAnrsLocked();
547 nextWakeupTime = std::min(nextWakeupTime, nextAnrCheck);
548
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800549 // We are about to enter an infinitely long sleep, because we have no commands or
550 // pending or queued events
551 if (nextWakeupTime == LONG_LONG_MAX) {
552 mDispatcherEnteredIdle.notify_all();
553 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800554 } // release lock
555
556 // Wait for callback or timeout or wake. (make sure we round up, not down)
557 nsecs_t currentTime = now();
558 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
559 mLooper->pollOnce(timeoutMillis);
560}
561
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700562/**
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500563 * Raise ANR if there is no focused window.
564 * Before the ANR is raised, do a final state check:
565 * 1. The currently focused application must be the same one we are waiting for.
566 * 2. Ensure we still don't have a focused window.
567 */
568void InputDispatcher::processNoFocusedWindowAnrLocked() {
569 // Check if the application that we are waiting for is still focused.
570 std::shared_ptr<InputApplicationHandle> focusedApplication =
571 getValueByKey(mFocusedApplicationHandlesByDisplay, mAwaitedApplicationDisplayId);
572 if (focusedApplication == nullptr ||
573 focusedApplication->getApplicationToken() !=
574 mAwaitedFocusedApplication->getApplicationToken()) {
575 // Unexpected because we should have reset the ANR timer when focused application changed
576 ALOGE("Waited for a focused window, but focused application has already changed to %s",
577 focusedApplication->getName().c_str());
578 return; // The focused application has changed.
579 }
580
581 const sp<InputWindowHandle>& focusedWindowHandle =
582 getFocusedWindowHandleLocked(mAwaitedApplicationDisplayId);
583 if (focusedWindowHandle != nullptr) {
584 return; // We now have a focused window. No need for ANR.
585 }
586 onAnrLocked(mAwaitedFocusedApplication);
587}
588
589/**
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700590 * Check if any of the connections' wait queues have events that are too old.
591 * If we waited for events to be ack'ed for more than the window timeout, raise an ANR.
592 * Return the time at which we should wake up next.
593 */
594nsecs_t InputDispatcher::processAnrsLocked() {
595 const nsecs_t currentTime = now();
596 nsecs_t nextAnrCheck = LONG_LONG_MAX;
597 // Check if we are waiting for a focused window to appear. Raise ANR if waited too long
598 if (mNoFocusedWindowTimeoutTime.has_value() && mAwaitedFocusedApplication != nullptr) {
599 if (currentTime >= *mNoFocusedWindowTimeoutTime) {
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500600 processNoFocusedWindowAnrLocked();
Chris Yea209fde2020-07-22 13:54:51 -0700601 mAwaitedFocusedApplication.reset();
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500602 mNoFocusedWindowTimeoutTime = std::nullopt;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700603 return LONG_LONG_MIN;
604 } else {
Siarhei Vishniakou38a6d272020-10-20 20:29:33 -0500605 // Keep waiting. We will drop the event when mNoFocusedWindowTimeoutTime comes.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700606 nextAnrCheck = *mNoFocusedWindowTimeoutTime;
607 }
608 }
609
610 // Check if any connection ANRs are due
611 nextAnrCheck = std::min(nextAnrCheck, mAnrTracker.firstTimeout());
612 if (currentTime < nextAnrCheck) { // most likely scenario
613 return nextAnrCheck; // everything is normal. Let's check again at nextAnrCheck
614 }
615
616 // If we reached here, we have an unresponsive connection.
617 sp<Connection> connection = getConnectionLocked(mAnrTracker.firstToken());
618 if (connection == nullptr) {
619 ALOGE("Could not find connection for entry %" PRId64, mAnrTracker.firstTimeout());
620 return nextAnrCheck;
621 }
622 connection->responsive = false;
623 // Stop waking up for this unresponsive connection
624 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000625 onAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700626 return LONG_LONG_MIN;
627}
628
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500629std::chrono::nanoseconds InputDispatcher::getDispatchingTimeoutLocked(const sp<IBinder>& token) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700630 sp<InputWindowHandle> window = getWindowHandleLocked(token);
631 if (window != nullptr) {
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500632 return window->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700633 }
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500634 return DEFAULT_INPUT_DISPATCHING_TIMEOUT;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700635}
636
Michael Wrightd02c5b62014-02-10 15:10:22 -0800637void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
638 nsecs_t currentTime = now();
639
Jeff Browndc5992e2014-04-11 01:27:26 -0700640 // Reset the key repeat timer whenever normal dispatch is suspended while the
641 // device is in a non-interactive state. This is to ensure that we abort a key
642 // repeat if the device is just coming out of sleep.
643 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800644 resetKeyRepeatLocked();
645 }
646
647 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
648 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +0100649 if (DEBUG_FOCUS) {
650 ALOGD("Dispatch frozen. Waiting some more.");
651 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800652 return;
653 }
654
655 // Optimize latency of app switches.
656 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
657 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
658 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
659 if (mAppSwitchDueTime < *nextWakeupTime) {
660 *nextWakeupTime = mAppSwitchDueTime;
661 }
662
663 // Ready to start a new event.
664 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700665 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700666 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800667 if (isAppSwitchDue) {
668 // The inbound queue is empty so the app switch key we were waiting
669 // for will never arrive. Stop waiting for it.
670 resetPendingAppSwitchLocked(false);
671 isAppSwitchDue = false;
672 }
673
674 // Synthesize a key repeat if appropriate.
675 if (mKeyRepeatState.lastKeyEntry) {
676 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
677 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
678 } else {
679 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
680 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
681 }
682 }
683 }
684
685 // Nothing to do if there is no pending event.
686 if (!mPendingEvent) {
687 return;
688 }
689 } else {
690 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700691 mPendingEvent = mInboundQueue.front();
692 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800693 traceInboundQueueLengthLocked();
694 }
695
696 // Poke user activity for this event.
697 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700698 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800699 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800700 }
701
702 // Now we have an event to dispatch.
703 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700704 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800705 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700706 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800707 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700708 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800709 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700710 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800711 }
712
713 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700714 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800715 }
716
717 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700718 case EventEntry::Type::CONFIGURATION_CHANGED: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700719 const ConfigurationChangedEntry& typedEntry =
720 static_cast<const ConfigurationChangedEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700721 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700722 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700723 break;
724 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800725
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700726 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700727 const DeviceResetEntry& typedEntry =
728 static_cast<const DeviceResetEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700729 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700730 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700731 break;
732 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800733
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100734 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700735 std::shared_ptr<FocusEntry> typedEntry =
736 std::static_pointer_cast<FocusEntry>(mPendingEvent);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100737 dispatchFocusLocked(currentTime, typedEntry);
738 done = true;
739 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
740 break;
741 }
742
Prabir Pradhan99987712020-11-10 18:43:05 -0800743 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
744 const auto typedEntry =
745 std::static_pointer_cast<PointerCaptureChangedEntry>(mPendingEvent);
746 dispatchPointerCaptureChangedLocked(currentTime, typedEntry, dropReason);
747 done = true;
748 break;
749 }
750
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700751 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700752 std::shared_ptr<KeyEntry> keyEntry = std::static_pointer_cast<KeyEntry>(mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700753 if (isAppSwitchDue) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700754 if (isAppSwitchKeyEvent(*keyEntry)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700755 resetPendingAppSwitchLocked(true);
756 isAppSwitchDue = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700757 } else if (dropReason == DropReason::NOT_DROPPED) {
758 dropReason = DropReason::APP_SWITCH;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700759 }
760 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700761 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *keyEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700762 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700763 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700764 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
765 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700766 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700767 done = dispatchKeyLocked(currentTime, keyEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700768 break;
769 }
770
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700771 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700772 std::shared_ptr<MotionEntry> motionEntry =
773 std::static_pointer_cast<MotionEntry>(mPendingEvent);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700774 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
775 dropReason = DropReason::APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800776 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700777 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *motionEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700778 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700779 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700780 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
781 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700782 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700783 done = dispatchMotionLocked(currentTime, motionEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700784 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800785 }
Chris Yef59a2f42020-10-16 12:55:26 -0700786
787 case EventEntry::Type::SENSOR: {
788 std::shared_ptr<SensorEntry> sensorEntry =
789 std::static_pointer_cast<SensorEntry>(mPendingEvent);
790 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
791 dropReason = DropReason::APP_SWITCH;
792 }
793 // Sensor timestamps use SYSTEM_TIME_BOOTTIME time base, so we can't use
794 // 'currentTime' here, get SYSTEM_TIME_BOOTTIME instead.
795 nsecs_t bootTime = systemTime(SYSTEM_TIME_BOOTTIME);
796 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(bootTime, *sensorEntry)) {
797 dropReason = DropReason::STALE;
798 }
799 dispatchSensorLocked(currentTime, sensorEntry, &dropReason, nextWakeupTime);
800 done = true;
801 break;
802 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800803 }
804
805 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700806 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700807 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800808 }
Michael Wright3a981722015-06-10 15:26:13 +0100809 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800810
811 releasePendingEventLocked();
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700812 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -0800813 }
814}
815
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700816/**
817 * Return true if the events preceding this incoming motion event should be dropped
818 * Return false otherwise (the default behaviour)
819 */
820bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700821 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700822 (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700823
824 // Optimize case where the current application is unresponsive and the user
825 // decides to touch a window in a different application.
826 // If the application takes too long to catch up then we drop all events preceding
827 // the touch into the other window.
828 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700829 int32_t displayId = motionEntry.displayId;
830 int32_t x = static_cast<int32_t>(
831 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
832 int32_t y = static_cast<int32_t>(
833 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
834 sp<InputWindowHandle> touchedWindowHandle =
835 findTouchedWindowAtLocked(displayId, x, y, nullptr);
836 if (touchedWindowHandle != nullptr &&
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700837 touchedWindowHandle->getApplicationToken() !=
838 mAwaitedFocusedApplication->getApplicationToken()) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700839 // User touched a different application than the one we are waiting on.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700840 ALOGI("Pruning input queue because user touched a different application while waiting "
841 "for %s",
842 mAwaitedFocusedApplication->getName().c_str());
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700843 return true;
844 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700845
846 // Alternatively, maybe there's a gesture monitor that could handle this event
847 std::vector<TouchedMonitor> gestureMonitors =
848 findTouchedGestureMonitorsLocked(displayId, {});
849 for (TouchedMonitor& gestureMonitor : gestureMonitors) {
850 sp<Connection> connection =
851 getConnectionLocked(gestureMonitor.monitor.inputChannel->getConnectionToken());
Siarhei Vishniakou34ed4d42020-06-18 00:43:02 +0000852 if (connection != nullptr && connection->responsive) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700853 // This monitor could take more input. Drop all events preceding this
854 // event, so that gesture monitor could get a chance to receive the stream
855 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
856 "responsive gesture monitor that may handle the event",
857 mAwaitedFocusedApplication->getName().c_str());
858 return true;
859 }
860 }
861 }
862
863 // Prevent getting stuck: if we have a pending key event, and some motion events that have not
864 // yet been processed by some connections, the dispatcher will wait for these motion
865 // events to be processed before dispatching the key event. This is because these motion events
866 // may cause a new window to be launched, which the user might expect to receive focus.
867 // To prevent waiting forever for such events, just send the key to the currently focused window
868 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
869 ALOGD("Received a new pointer down event, stop waiting for events to process and "
870 "just send the pending key event to the focused window.");
871 mKeyIsWaitingForEventsTimeout = now();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700872 }
873 return false;
874}
875
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700876bool InputDispatcher::enqueueInboundEventLocked(std::unique_ptr<EventEntry> newEntry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700877 bool needWake = mInboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700878 mInboundQueue.push_back(std::move(newEntry));
879 EventEntry& entry = *(mInboundQueue.back());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800880 traceInboundQueueLengthLocked();
881
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700882 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700883 case EventEntry::Type::KEY: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700884 // Optimize app switch latency.
885 // If the application takes too long to catch up then we drop all events preceding
886 // the app switch key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700887 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700888 if (isAppSwitchKeyEvent(keyEntry)) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700889 if (keyEntry.action == AKEY_EVENT_ACTION_DOWN) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700890 mAppSwitchSawKeyDown = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700891 } else if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700892 if (mAppSwitchSawKeyDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800893#if DEBUG_APP_SWITCH
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700894 ALOGD("App switch is pending!");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800895#endif
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700896 mAppSwitchDueTime = keyEntry.eventTime + APP_SWITCH_TIMEOUT;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700897 mAppSwitchSawKeyDown = false;
898 needWake = true;
899 }
900 }
901 }
902 break;
903 }
904
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700905 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700906 if (shouldPruneInboundQueueLocked(static_cast<MotionEntry&>(entry))) {
907 mNextUnblockedEvent = mInboundQueue.back();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700908 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800909 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700910 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800911 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100912 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700913 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
914 break;
915 }
916 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -0800917 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -0700918 case EventEntry::Type::SENSOR:
Prabir Pradhan99987712020-11-10 18:43:05 -0800919 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700920 // nothing to do
921 break;
922 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800923 }
924
925 return needWake;
926}
927
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700928void InputDispatcher::addRecentEventLocked(std::shared_ptr<EventEntry> entry) {
Chris Yef59a2f42020-10-16 12:55:26 -0700929 // Do not store sensor event in recent queue to avoid flooding the queue.
930 if (entry->type != EventEntry::Type::SENSOR) {
931 mRecentQueue.push_back(entry);
932 }
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700933 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700934 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800935 }
936}
937
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700938sp<InputWindowHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, int32_t x,
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700939 int32_t y, TouchState* touchState,
940 bool addOutsideTargets,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700941 bool addPortalWindows) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700942 if ((addPortalWindows || addOutsideTargets) && touchState == nullptr) {
943 LOG_ALWAYS_FATAL(
944 "Must provide a valid touch state if adding portal windows or outside targets");
945 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800946 // Traverse windows from front to back to find touched window.
Vishnu Nairad321cd2020-08-20 16:40:21 -0700947 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800948 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800949 const InputWindowInfo* windowInfo = windowHandle->getInfo();
950 if (windowInfo->displayId == displayId) {
Michael Wright44753b12020-07-08 13:48:11 +0100951 auto flags = windowInfo->flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800952
953 if (windowInfo->visible) {
Michael Wright44753b12020-07-08 13:48:11 +0100954 if (!flags.test(InputWindowInfo::Flag::NOT_TOUCHABLE)) {
955 bool isTouchModal = !flags.test(InputWindowInfo::Flag::NOT_FOCUSABLE) &&
956 !flags.test(InputWindowInfo::Flag::NOT_TOUCH_MODAL);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800957 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800958 int32_t portalToDisplayId = windowInfo->portalToDisplayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700959 if (portalToDisplayId != ADISPLAY_ID_NONE &&
960 portalToDisplayId != displayId) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800961 if (addPortalWindows) {
962 // For the monitoring channels of the display.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700963 touchState->addPortalWindow(windowHandle);
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800964 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700965 return findTouchedWindowAtLocked(portalToDisplayId, x, y, touchState,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700966 addOutsideTargets, addPortalWindows);
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800967 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800968 // Found window.
969 return windowHandle;
970 }
971 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800972
Michael Wright44753b12020-07-08 13:48:11 +0100973 if (addOutsideTargets && flags.test(InputWindowInfo::Flag::WATCH_OUTSIDE_TOUCH)) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700974 touchState->addOrUpdateWindow(windowHandle,
975 InputTarget::FLAG_DISPATCH_AS_OUTSIDE,
976 BitSet32(0));
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800977 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800978 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800979 }
980 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700981 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800982}
983
Garfield Tane84e6f92019-08-29 17:28:41 -0700984std::vector<TouchedMonitor> InputDispatcher::findTouchedGestureMonitorsLocked(
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -0700985 int32_t displayId, const std::vector<sp<InputWindowHandle>>& portalWindows) const {
Michael Wright3dd60e22019-03-27 22:06:44 +0000986 std::vector<TouchedMonitor> touchedMonitors;
987
988 std::vector<Monitor> monitors = getValueByKey(mGestureMonitorsByDisplay, displayId);
989 addGestureMonitors(monitors, touchedMonitors);
990 for (const sp<InputWindowHandle>& portalWindow : portalWindows) {
991 const InputWindowInfo* windowInfo = portalWindow->getInfo();
992 monitors = getValueByKey(mGestureMonitorsByDisplay, windowInfo->portalToDisplayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700993 addGestureMonitors(monitors, touchedMonitors, -windowInfo->frameLeft,
994 -windowInfo->frameTop);
Michael Wright3dd60e22019-03-27 22:06:44 +0000995 }
996 return touchedMonitors;
997}
998
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700999void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001000 const char* reason;
1001 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001002 case DropReason::POLICY:
Michael Wrightd02c5b62014-02-10 15:10:22 -08001003#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001004 ALOGD("Dropped event because policy consumed it.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001005#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001006 reason = "inbound event was dropped because the policy consumed it";
1007 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001008 case DropReason::DISABLED:
1009 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001010 ALOGI("Dropped event because input dispatch is disabled.");
1011 }
1012 reason = "inbound event was dropped because input dispatch is disabled";
1013 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001014 case DropReason::APP_SWITCH:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001015 ALOGI("Dropped event because of pending overdue app switch.");
1016 reason = "inbound event was dropped because of pending overdue app switch";
1017 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001018 case DropReason::BLOCKED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001019 ALOGI("Dropped event because the current application is not responding and the user "
1020 "has started interacting with a different application.");
1021 reason = "inbound event was dropped because the current application is not responding "
1022 "and the user has started interacting with a different application";
1023 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001024 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001025 ALOGI("Dropped event because it is stale.");
1026 reason = "inbound event was dropped because it is stale";
1027 break;
Prabir Pradhan99987712020-11-10 18:43:05 -08001028 case DropReason::NO_POINTER_CAPTURE:
1029 ALOGI("Dropped event because there is no window with Pointer Capture.");
1030 reason = "inbound event was dropped because there is no window with Pointer Capture";
1031 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001032 case DropReason::NOT_DROPPED: {
1033 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001034 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001035 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001036 }
1037
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001038 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001039 case EventEntry::Type::KEY: {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001040 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
1041 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001042 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001043 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001044 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001045 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1046 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001047 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
1048 synthesizeCancelationEventsForAllConnectionsLocked(options);
1049 } else {
1050 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
1051 synthesizeCancelationEventsForAllConnectionsLocked(options);
1052 }
1053 break;
1054 }
Chris Yef59a2f42020-10-16 12:55:26 -07001055 case EventEntry::Type::SENSOR: {
1056 break;
1057 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001058 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
1059 break;
1060 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001061 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001062 case EventEntry::Type::CONFIGURATION_CHANGED:
1063 case EventEntry::Type::DEVICE_RESET: {
Chris Yef59a2f42020-10-16 12:55:26 -07001064 LOG_ALWAYS_FATAL("Should not drop %s events", NamedEnum::string(entry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001065 break;
1066 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001067 }
1068}
1069
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001070static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001071 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
1072 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001073}
1074
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001075bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
1076 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
1077 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
1078 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001079}
1080
1081bool InputDispatcher::isAppSwitchPendingLocked() {
1082 return mAppSwitchDueTime != LONG_LONG_MAX;
1083}
1084
1085void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
1086 mAppSwitchDueTime = LONG_LONG_MAX;
1087
1088#if DEBUG_APP_SWITCH
1089 if (handled) {
1090 ALOGD("App switch has arrived.");
1091 } else {
1092 ALOGD("App switch was abandoned.");
1093 }
1094#endif
1095}
1096
Michael Wrightd02c5b62014-02-10 15:10:22 -08001097bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001098 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001099}
1100
1101bool InputDispatcher::runCommandsLockedInterruptible() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001102 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001103 return false;
1104 }
1105
1106 do {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001107 std::unique_ptr<CommandEntry> commandEntry = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001108 mCommandQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001109 Command command = commandEntry->command;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001110 command(*this, commandEntry.get()); // commands are implicitly 'LockedInterruptible'
Michael Wrightd02c5b62014-02-10 15:10:22 -08001111
1112 commandEntry->connection.clear();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001113 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001114 return true;
1115}
1116
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001117void InputDispatcher::postCommandLocked(std::unique_ptr<CommandEntry> commandEntry) {
1118 mCommandQueue.push_back(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001119}
1120
1121void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001122 while (!mInboundQueue.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001123 std::shared_ptr<EventEntry> entry = mInboundQueue.front();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001124 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001125 releaseInboundEventLocked(entry);
1126 }
1127 traceInboundQueueLengthLocked();
1128}
1129
1130void InputDispatcher::releasePendingEventLocked() {
1131 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001132 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -07001133 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001134 }
1135}
1136
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001137void InputDispatcher::releaseInboundEventLocked(std::shared_ptr<EventEntry> entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001138 InjectionState* injectionState = entry->injectionState;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001139 if (injectionState && injectionState->injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001140#if DEBUG_DISPATCH_CYCLE
1141 ALOGD("Injected inbound event was dropped.");
1142#endif
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001143 setInjectionResult(*entry, InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001144 }
1145 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001146 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001147 }
1148 addRecentEventLocked(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001149}
1150
1151void InputDispatcher::resetKeyRepeatLocked() {
1152 if (mKeyRepeatState.lastKeyEntry) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001153 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001154 }
1155}
1156
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001157std::shared_ptr<KeyEntry> InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
1158 std::shared_ptr<KeyEntry> entry = mKeyRepeatState.lastKeyEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001159
Michael Wright2e732952014-09-24 13:26:59 -07001160 uint32_t policyFlags = entry->policyFlags &
1161 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001162
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001163 std::shared_ptr<KeyEntry> newEntry =
1164 std::make_unique<KeyEntry>(mIdGenerator.nextId(), currentTime, entry->deviceId,
1165 entry->source, entry->displayId, policyFlags, entry->action,
1166 entry->flags, entry->keyCode, entry->scanCode,
1167 entry->metaState, entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001168
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001169 newEntry->syntheticRepeat = true;
1170 mKeyRepeatState.lastKeyEntry = newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001171 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001172 return newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001173}
1174
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001175bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001176 const ConfigurationChangedEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001177#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001178 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry.eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001179#endif
1180
1181 // Reset key repeating in case a keyboard device was added or removed or something.
1182 resetKeyRepeatLocked();
1183
1184 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001185 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
1186 &InputDispatcher::doNotifyConfigurationChangedLockedInterruptible);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001187 commandEntry->eventTime = entry.eventTime;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001188 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001189 return true;
1190}
1191
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001192bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime,
1193 const DeviceResetEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001194#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001195 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry.eventTime,
1196 entry.deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001197#endif
1198
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001199 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, "device was reset");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001200 options.deviceId = entry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001201 synthesizeCancelationEventsForAllConnectionsLocked(options);
1202 return true;
1203}
1204
Vishnu Nairad321cd2020-08-20 16:40:21 -07001205void InputDispatcher::enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus,
Vishnu Nairc519ff72021-01-21 08:23:08 -08001206 const std::string& reason) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001207 if (mPendingEvent != nullptr) {
1208 // Move the pending event to the front of the queue. This will give the chance
1209 // for the pending event to get dispatched to the newly focused window
1210 mInboundQueue.push_front(mPendingEvent);
1211 mPendingEvent = nullptr;
1212 }
1213
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001214 std::unique_ptr<FocusEntry> focusEntry =
1215 std::make_unique<FocusEntry>(mIdGenerator.nextId(), now(), windowToken, hasFocus,
1216 reason);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001217
1218 // This event should go to the front of the queue, but behind all other focus events
1219 // Find the last focus event, and insert right after it
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001220 std::deque<std::shared_ptr<EventEntry>>::reverse_iterator it =
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001221 std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001222 [](const std::shared_ptr<EventEntry>& event) {
1223 return event->type == EventEntry::Type::FOCUS;
1224 });
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001225
1226 // Maintain the order of focus events. Insert the entry after all other focus events.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001227 mInboundQueue.insert(it.base(), std::move(focusEntry));
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001228}
1229
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001230void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime, std::shared_ptr<FocusEntry> entry) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05001231 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001232 if (channel == nullptr) {
1233 return; // Window has gone away
1234 }
1235 InputTarget target;
1236 target.inputChannel = channel;
1237 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1238 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001239 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
1240 channel->getName();
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001241 std::string reason = std::string("reason=").append(entry->reason);
1242 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001243 dispatchEventLocked(currentTime, entry, {target});
1244}
1245
Prabir Pradhan99987712020-11-10 18:43:05 -08001246void InputDispatcher::dispatchPointerCaptureChangedLocked(
1247 nsecs_t currentTime, const std::shared_ptr<PointerCaptureChangedEntry>& entry,
1248 DropReason& dropReason) {
1249 const bool haveWindowWithPointerCapture = mWindowTokenWithPointerCapture != nullptr;
Prabir Pradhan167e6d92021-02-04 16:18:17 -08001250 if (entry->pointerCaptureEnabled && haveWindowWithPointerCapture) {
1251 LOG_ALWAYS_FATAL("Pointer Capture has already been enabled for the window.");
1252 }
1253 if (!entry->pointerCaptureEnabled && !haveWindowWithPointerCapture) {
Prabir Pradhan99987712020-11-10 18:43:05 -08001254 // Pointer capture was already forcefully disabled because of focus change.
1255 dropReason = DropReason::NOT_DROPPED;
1256 return;
1257 }
1258
1259 // Set drop reason for early returns
1260 dropReason = DropReason::NO_POINTER_CAPTURE;
1261
1262 sp<IBinder> token;
1263 if (entry->pointerCaptureEnabled) {
1264 // Enable Pointer Capture
1265 if (!mFocusedWindowRequestedPointerCapture) {
1266 // This can happen if a window requests capture and immediately releases capture.
1267 ALOGW("No window requested Pointer Capture.");
1268 return;
1269 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08001270 token = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08001271 LOG_ALWAYS_FATAL_IF(!token, "Cannot find focused window for Pointer Capture.");
1272 mWindowTokenWithPointerCapture = token;
1273 } else {
1274 // Disable Pointer Capture
1275 token = mWindowTokenWithPointerCapture;
1276 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan7d030382020-12-21 07:58:35 -08001277 if (mFocusedWindowRequestedPointerCapture) {
1278 mFocusedWindowRequestedPointerCapture = false;
1279 setPointerCaptureLocked(false);
1280 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001281 }
1282
1283 auto channel = getInputChannelLocked(token);
1284 if (channel == nullptr) {
1285 // Window has gone away, clean up Pointer Capture state.
1286 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan7d030382020-12-21 07:58:35 -08001287 if (mFocusedWindowRequestedPointerCapture) {
1288 mFocusedWindowRequestedPointerCapture = false;
1289 setPointerCaptureLocked(false);
1290 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001291 return;
1292 }
1293 InputTarget target;
1294 target.inputChannel = channel;
1295 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1296 entry->dispatchInProgress = true;
1297 dispatchEventLocked(currentTime, entry, {target});
1298
1299 dropReason = DropReason::NOT_DROPPED;
1300}
1301
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001302bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, std::shared_ptr<KeyEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001303 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001304 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001305 if (!entry->dispatchInProgress) {
1306 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1307 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1308 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1309 if (mKeyRepeatState.lastKeyEntry &&
Chris Ye2ad95392020-09-01 13:44:44 -07001310 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode &&
Michael Wrightd02c5b62014-02-10 15:10:22 -08001311 // We have seen two identical key downs in a row which indicates that the device
1312 // driver is automatically generating key repeats itself. We take note of the
1313 // repeat here, but we disable our own next key repeat timer since it is clear that
1314 // we will not need to synthesize key repeats ourselves.
Chris Ye2ad95392020-09-01 13:44:44 -07001315 mKeyRepeatState.lastKeyEntry->deviceId == entry->deviceId) {
1316 // Make sure we don't get key down from a different device. If a different
1317 // device Id has same key pressed down, the new device Id will replace the
1318 // current one to hold the key repeat with repeat count reset.
1319 // In the future when got a KEY_UP on the device id, drop it and do not
1320 // stop the key repeat on current device.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001321 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1322 resetKeyRepeatLocked();
1323 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
1324 } else {
1325 // Not a repeat. Save key down state in case we do see a repeat later.
1326 resetKeyRepeatLocked();
1327 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1328 }
1329 mKeyRepeatState.lastKeyEntry = entry;
Chris Ye2ad95392020-09-01 13:44:44 -07001330 } else if (entry->action == AKEY_EVENT_ACTION_UP && mKeyRepeatState.lastKeyEntry &&
1331 mKeyRepeatState.lastKeyEntry->deviceId != entry->deviceId) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001332 // The key on device 'deviceId' is still down, do not stop key repeat
Chris Ye2ad95392020-09-01 13:44:44 -07001333#if DEBUG_INBOUND_EVENT_DETAILS
1334 ALOGD("deviceId=%d got KEY_UP as stale", entry->deviceId);
1335#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001336 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001337 resetKeyRepeatLocked();
1338 }
1339
1340 if (entry->repeatCount == 1) {
1341 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1342 } else {
1343 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1344 }
1345
1346 entry->dispatchInProgress = true;
1347
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001348 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001349 }
1350
1351 // Handle case where the policy asked us to try again later last time.
1352 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
1353 if (currentTime < entry->interceptKeyWakeupTime) {
1354 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1355 *nextWakeupTime = entry->interceptKeyWakeupTime;
1356 }
1357 return false; // wait until next wakeup
1358 }
1359 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
1360 entry->interceptKeyWakeupTime = 0;
1361 }
1362
1363 // Give the policy a chance to intercept the key.
1364 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
1365 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001366 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
Siarhei Vishniakou49a350a2019-07-26 18:44:23 -07001367 &InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible);
Vishnu Nairad321cd2020-08-20 16:40:21 -07001368 sp<IBinder> focusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08001369 mFocusResolver.getFocusedWindowToken(getTargetDisplayId(*entry));
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06001370 commandEntry->connectionToken = focusedWindowToken;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001371 commandEntry->keyEntry = entry;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001372 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001373 return false; // wait for the command to run
1374 } else {
1375 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
1376 }
1377 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001378 if (*dropReason == DropReason::NOT_DROPPED) {
1379 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001380 }
1381 }
1382
1383 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001384 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001385 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001386 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1387 : InputEventInjectionResult::FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001388 mReporter->reportDroppedKey(entry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001389 return true;
1390 }
1391
1392 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001393 std::vector<InputTarget> inputTargets;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001394 InputEventInjectionResult injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001395 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001396 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001397 return false;
1398 }
1399
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001400 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001401 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001402 return true;
1403 }
1404
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001405 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001406 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001407
1408 // Dispatch the key.
1409 dispatchEventLocked(currentTime, entry, inputTargets);
1410 return true;
1411}
1412
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001413void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001414#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01001415 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001416 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1417 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001418 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1419 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
1420 entry.repeatCount, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001421#endif
1422}
1423
Chris Yef59a2f42020-10-16 12:55:26 -07001424void InputDispatcher::doNotifySensorLockedInterruptible(CommandEntry* commandEntry) {
1425 mLock.unlock();
1426
1427 const std::shared_ptr<SensorEntry>& entry = commandEntry->sensorEntry;
1428 if (entry->accuracyChanged) {
1429 mPolicy->notifySensorAccuracy(entry->deviceId, entry->sensorType, entry->accuracy);
1430 }
1431 mPolicy->notifySensorEvent(entry->deviceId, entry->sensorType, entry->accuracy,
1432 entry->hwTimestamp, entry->values);
1433 mLock.lock();
1434}
1435
1436void InputDispatcher::dispatchSensorLocked(nsecs_t currentTime, std::shared_ptr<SensorEntry> entry,
1437 DropReason* dropReason, nsecs_t* nextWakeupTime) {
1438#if DEBUG_OUTBOUND_EVENT_DETAILS
1439 ALOGD("notifySensorEvent eventTime=%" PRId64 ", hwTimestamp=%" PRId64 ", deviceId=%d, "
1440 "source=0x%x, sensorType=%s",
1441 entry->eventTime, entry->hwTimestamp, entry->deviceId, entry->source,
1442 NamedEnum::string(sensorType).c_str());
1443#endif
1444 std::unique_ptr<CommandEntry> commandEntry =
1445 std::make_unique<CommandEntry>(&InputDispatcher::doNotifySensorLockedInterruptible);
1446 commandEntry->sensorEntry = entry;
1447 postCommandLocked(std::move(commandEntry));
1448}
1449
1450bool InputDispatcher::flushSensor(int deviceId, InputDeviceSensorType sensorType) {
1451#if DEBUG_OUTBOUND_EVENT_DETAILS
1452 ALOGD("flushSensor deviceId=%d, sensorType=%s", deviceId,
1453 NamedEnum::string(sensorType).c_str());
1454#endif
1455 { // acquire lock
1456 std::scoped_lock _l(mLock);
1457
1458 for (auto it = mInboundQueue.begin(); it != mInboundQueue.end(); it++) {
1459 std::shared_ptr<EventEntry> entry = *it;
1460 if (entry->type == EventEntry::Type::SENSOR) {
1461 it = mInboundQueue.erase(it);
1462 releaseInboundEventLocked(entry);
1463 }
1464 }
1465 }
1466 return true;
1467}
1468
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001469bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, std::shared_ptr<MotionEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001470 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001471 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001472 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001473 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001474 entry->dispatchInProgress = true;
1475
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001476 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001477 }
1478
1479 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001480 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001481 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001482 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1483 : InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001484 return true;
1485 }
1486
1487 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
1488
1489 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001490 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001491
1492 bool conflictingPointerActions = false;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001493 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001494 if (isPointerEvent) {
1495 // Pointer event. (eg. touchscreen)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001496 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001497 findTouchedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001498 &conflictingPointerActions);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001499 } else {
1500 // Non touch event. (eg. trackball)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001501 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001502 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001503 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001504 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001505 return false;
1506 }
1507
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001508 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001509 if (injectionResult == InputEventInjectionResult::PERMISSION_DENIED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001510 ALOGW("Permission denied, dropping the motion (isPointer=%s)", toString(isPointerEvent));
1511 return true;
1512 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001513 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001514 CancelationOptions::Mode mode(isPointerEvent
1515 ? CancelationOptions::CANCEL_POINTER_EVENTS
1516 : CancelationOptions::CANCEL_NON_POINTER_EVENTS);
1517 CancelationOptions options(mode, "input event injection failed");
1518 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001519 return true;
1520 }
1521
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001522 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001523 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001524
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001525 if (isPointerEvent) {
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07001526 std::unordered_map<int32_t, TouchState>::iterator it =
1527 mTouchStatesByDisplay.find(entry->displayId);
1528 if (it != mTouchStatesByDisplay.end()) {
1529 const TouchState& state = it->second;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001530 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001531 // The event has gone through these portal windows, so we add monitoring targets of
1532 // the corresponding displays as well.
1533 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001534 const InputWindowInfo* windowInfo = state.portalWindows[i]->getInfo();
Michael Wright3dd60e22019-03-27 22:06:44 +00001535 addGlobalMonitoringTargetsLocked(inputTargets, windowInfo->portalToDisplayId,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001536 -windowInfo->frameLeft, -windowInfo->frameTop);
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001537 }
1538 }
1539 }
1540 }
1541
Michael Wrightd02c5b62014-02-10 15:10:22 -08001542 // Dispatch the motion.
1543 if (conflictingPointerActions) {
1544 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001545 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001546 synthesizeCancelationEventsForAllConnectionsLocked(options);
1547 }
1548 dispatchEventLocked(currentTime, entry, inputTargets);
1549 return true;
1550}
1551
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001552void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001553#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08001554 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001555 ", policyFlags=0x%x, "
1556 "action=0x%x, actionButton=0x%x, flags=0x%x, "
1557 "metaState=0x%x, buttonState=0x%x,"
1558 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001559 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1560 entry.action, entry.actionButton, entry.flags, entry.metaState, entry.buttonState,
1561 entry.edgeFlags, entry.xPrecision, entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001562
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001563 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001564 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001565 "x=%f, y=%f, pressure=%f, size=%f, "
1566 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1567 "orientation=%f",
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001568 i, entry.pointerProperties[i].id, entry.pointerProperties[i].toolType,
1569 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1570 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1571 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1572 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1573 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1574 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1575 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1576 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1577 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001578 }
1579#endif
1580}
1581
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001582void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
1583 std::shared_ptr<EventEntry> eventEntry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001584 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001585 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001586#if DEBUG_DISPATCH_CYCLE
1587 ALOGD("dispatchEventToCurrentInputTargets");
1588#endif
1589
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001590 updateInteractionTokensLocked(*eventEntry, inputTargets);
1591
Michael Wrightd02c5b62014-02-10 15:10:22 -08001592 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1593
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001594 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001595
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001596 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001597 sp<Connection> connection =
1598 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001599 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08001600 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001601 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001602 if (DEBUG_FOCUS) {
1603 ALOGD("Dropping event delivery to target with channel '%s' because it "
1604 "is no longer registered with the input dispatcher.",
1605 inputTarget.inputChannel->getName().c_str());
1606 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001607 }
1608 }
1609}
1610
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001611void InputDispatcher::cancelEventsForAnrLocked(const sp<Connection>& connection) {
1612 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
1613 // If the policy decides to close the app, we will get a channel removal event via
1614 // unregisterInputChannel, and will clean up the connection that way. We are already not
1615 // sending new pointers to the connection when it blocked, but focused events will continue to
1616 // pile up.
1617 ALOGW("Canceling events for %s because it is unresponsive",
1618 connection->inputChannel->getName().c_str());
1619 if (connection->status == Connection::STATUS_NORMAL) {
1620 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1621 "application not responding");
1622 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001623 }
1624}
1625
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001626void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001627 if (DEBUG_FOCUS) {
1628 ALOGD("Resetting ANR timeouts.");
1629 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001630
1631 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001632 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07001633 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001634}
1635
Tiger Huang721e26f2018-07-24 22:26:19 +08001636/**
1637 * Get the display id that the given event should go to. If this event specifies a valid display id,
1638 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1639 * Focused display is the display that the user most recently interacted with.
1640 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001641int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001642 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001643 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001644 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001645 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1646 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001647 break;
1648 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001649 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001650 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1651 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001652 break;
1653 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001654 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001655 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001656 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07001657 case EventEntry::Type::DEVICE_RESET:
1658 case EventEntry::Type::SENSOR: {
1659 ALOGE("%s events do not have a target display", NamedEnum::string(entry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001660 return ADISPLAY_ID_NONE;
1661 }
Tiger Huang721e26f2018-07-24 22:26:19 +08001662 }
1663 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1664}
1665
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001666bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
1667 const char* focusedWindowName) {
1668 if (mAnrTracker.empty()) {
1669 // already processed all events that we waited for
1670 mKeyIsWaitingForEventsTimeout = std::nullopt;
1671 return false;
1672 }
1673
1674 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
1675 // Start the timer
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00001676 // Wait to send key because there are unprocessed events that may cause focus to change
Siarhei Vishniakou70622952020-07-30 11:17:23 -05001677 mKeyIsWaitingForEventsTimeout = currentTime +
1678 std::chrono::duration_cast<std::chrono::nanoseconds>(KEY_WAITING_FOR_EVENTS_TIMEOUT)
1679 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001680 return true;
1681 }
1682
1683 // We still have pending events, and already started the timer
1684 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
1685 return true; // Still waiting
1686 }
1687
1688 // Waited too long, and some connection still hasn't processed all motions
1689 // Just send the key to the focused window
1690 ALOGW("Dispatching key to %s even though there are other unprocessed events",
1691 focusedWindowName);
1692 mKeyIsWaitingForEventsTimeout = std::nullopt;
1693 return false;
1694}
1695
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001696InputEventInjectionResult InputDispatcher::findFocusedWindowTargetsLocked(
1697 nsecs_t currentTime, const EventEntry& entry, std::vector<InputTarget>& inputTargets,
1698 nsecs_t* nextWakeupTime) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001699 std::string reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001700
Tiger Huang721e26f2018-07-24 22:26:19 +08001701 int32_t displayId = getTargetDisplayId(entry);
Vishnu Nairad321cd2020-08-20 16:40:21 -07001702 sp<InputWindowHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07001703 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08001704 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1705
Michael Wrightd02c5b62014-02-10 15:10:22 -08001706 // If there is no currently focused window and no focused application
1707 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001708 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
1709 ALOGI("Dropping %s event because there is no focused window or focused application in "
1710 "display %" PRId32 ".",
Chris Yef59a2f42020-10-16 12:55:26 -07001711 NamedEnum::string(entry.type).c_str(), displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001712 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001713 }
1714
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001715 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
1716 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
1717 // start interacting with another application via touch (app switch). This code can be removed
1718 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
1719 // an app is expected to have a focused window.
1720 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
1721 if (!mNoFocusedWindowTimeoutTime.has_value()) {
1722 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001723 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
1724 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
1725 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001726 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05001727 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001728 ALOGW("Waiting because no window has focus but %s may eventually add a "
1729 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001730 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001731 *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001732 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001733 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
1734 // Already raised ANR. Drop the event
1735 ALOGE("Dropping %s event because there is no focused window",
Chris Yef59a2f42020-10-16 12:55:26 -07001736 NamedEnum::string(entry.type).c_str());
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001737 return InputEventInjectionResult::FAILED;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001738 } else {
1739 // Still waiting for the focused window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001740 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001741 }
1742 }
1743
1744 // we have a valid, non-null focused window
1745 resetNoFocusedWindowTimeoutLocked();
1746
Michael Wrightd02c5b62014-02-10 15:10:22 -08001747 // Check permissions.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001748 if (!checkInjectionPermission(focusedWindowHandle, entry.injectionState)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001749 return InputEventInjectionResult::PERMISSION_DENIED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001750 }
1751
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001752 if (focusedWindowHandle->getInfo()->paused) {
1753 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001754 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001755 }
1756
1757 // If the event is a key event, then we must wait for all previous events to
1758 // complete before delivering it because previous events may have the
1759 // side-effect of transferring focus to a different window and we want to
1760 // ensure that the following keys are sent to the new window.
1761 //
1762 // Suppose the user touches a button in a window then immediately presses "A".
1763 // If the button causes a pop-up window to appear then we want to ensure that
1764 // the "A" key is delivered to the new pop-up window. This is because users
1765 // often anticipate pending UI changes when typing on a keyboard.
1766 // To obtain this behavior, we must serialize key events with respect to all
1767 // prior input events.
1768 if (entry.type == EventEntry::Type::KEY) {
1769 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
1770 *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001771 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001772 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001773 }
1774
1775 // Success! Output targets.
Tiger Huang721e26f2018-07-24 22:26:19 +08001776 addWindowTargetLocked(focusedWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001777 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS,
1778 BitSet32(0), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001779
1780 // Done.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001781 return InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001782}
1783
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001784/**
1785 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
1786 * that are currently unresponsive.
1787 */
1788std::vector<TouchedMonitor> InputDispatcher::selectResponsiveMonitorsLocked(
1789 const std::vector<TouchedMonitor>& monitors) const {
1790 std::vector<TouchedMonitor> responsiveMonitors;
1791 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
1792 [this](const TouchedMonitor& monitor) REQUIRES(mLock) {
1793 sp<Connection> connection = getConnectionLocked(
1794 monitor.monitor.inputChannel->getConnectionToken());
1795 if (connection == nullptr) {
1796 ALOGE("Could not find connection for monitor %s",
1797 monitor.monitor.inputChannel->getName().c_str());
1798 return false;
1799 }
1800 if (!connection->responsive) {
1801 ALOGW("Unresponsive monitor %s will not get the new gesture",
1802 connection->inputChannel->getName().c_str());
1803 return false;
1804 }
1805 return true;
1806 });
1807 return responsiveMonitors;
1808}
1809
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001810InputEventInjectionResult InputDispatcher::findTouchedWindowTargetsLocked(
1811 nsecs_t currentTime, const MotionEntry& entry, std::vector<InputTarget>& inputTargets,
1812 nsecs_t* nextWakeupTime, bool* outConflictingPointerActions) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001813 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001814 enum InjectionPermission {
1815 INJECTION_PERMISSION_UNKNOWN,
1816 INJECTION_PERMISSION_GRANTED,
1817 INJECTION_PERMISSION_DENIED
1818 };
1819
Michael Wrightd02c5b62014-02-10 15:10:22 -08001820 // For security reasons, we defer updating the touch state until we are sure that
1821 // event injection will be allowed.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001822 int32_t displayId = entry.displayId;
1823 int32_t action = entry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001824 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
1825
1826 // Update the touch state as needed based on the properties of the touch event.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001827 InputEventInjectionResult injectionResult = InputEventInjectionResult::PENDING;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001828 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
Garfield Tandf26e862020-07-01 20:18:19 -07001829 sp<InputWindowHandle> newHoverWindowHandle(mLastHoverWindowHandle);
1830 sp<InputWindowHandle> newTouchedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001831
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001832 // Copy current touch state into tempTouchState.
1833 // This state will be used to update mTouchStatesByDisplay at the end of this function.
1834 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07001835 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001836 TouchState tempTouchState;
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07001837 std::unordered_map<int32_t, TouchState>::iterator oldStateIt =
1838 mTouchStatesByDisplay.find(displayId);
1839 if (oldStateIt != mTouchStatesByDisplay.end()) {
1840 oldState = &(oldStateIt->second);
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001841 tempTouchState.copyFrom(*oldState);
Jeff Brownf086ddb2014-02-11 14:28:48 -08001842 }
1843
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001844 bool isSplit = tempTouchState.split;
1845 bool switchedDevice = tempTouchState.deviceId >= 0 && tempTouchState.displayId >= 0 &&
1846 (tempTouchState.deviceId != entry.deviceId || tempTouchState.source != entry.source ||
1847 tempTouchState.displayId != displayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001848 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
1849 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
1850 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
1851 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN ||
1852 maskedAction == AMOTION_EVENT_ACTION_SCROLL || isHoverAction);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001853 const bool isFromMouse = entry.source == AINPUT_SOURCE_MOUSE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001854 bool wrongDevice = false;
1855 if (newGesture) {
1856 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001857 if (switchedDevice && tempTouchState.down && !down && !isHoverAction) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001858 ALOGI("Dropping event because a pointer for a different device is already down "
1859 "in display %" PRId32,
1860 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001861 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001862 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001863 switchedDevice = false;
1864 wrongDevice = true;
1865 goto Failed;
1866 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001867 tempTouchState.reset();
1868 tempTouchState.down = down;
1869 tempTouchState.deviceId = entry.deviceId;
1870 tempTouchState.source = entry.source;
1871 tempTouchState.displayId = displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001872 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001873 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001874 ALOGI("Dropping move event because a pointer for a different device is already active "
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::PERMISSION_DENIED;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001879 switchedDevice = false;
1880 wrongDevice = true;
1881 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001882 }
1883
1884 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
1885 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
1886
Garfield Tan00f511d2019-06-12 16:55:40 -07001887 int32_t x;
1888 int32_t y;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001889 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Garfield Tan00f511d2019-06-12 16:55:40 -07001890 // Always dispatch mouse events to cursor position.
1891 if (isFromMouse) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001892 x = int32_t(entry.xCursorPosition);
1893 y = int32_t(entry.yCursorPosition);
Garfield Tan00f511d2019-06-12 16:55:40 -07001894 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001895 x = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X));
1896 y = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y));
Garfield Tan00f511d2019-06-12 16:55:40 -07001897 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001898 bool isDown = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Garfield Tandf26e862020-07-01 20:18:19 -07001899 newTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001900 findTouchedWindowAtLocked(displayId, x, y, &tempTouchState,
1901 isDown /*addOutsideTargets*/, true /*addPortalWindows*/);
Michael Wright3dd60e22019-03-27 22:06:44 +00001902
1903 std::vector<TouchedMonitor> newGestureMonitors = isDown
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001904 ? findTouchedGestureMonitorsLocked(displayId, tempTouchState.portalWindows)
Michael Wright3dd60e22019-03-27 22:06:44 +00001905 : std::vector<TouchedMonitor>{};
Michael Wrightd02c5b62014-02-10 15:10:22 -08001906
Michael Wrightd02c5b62014-02-10 15:10:22 -08001907 // Figure out whether splitting will be allowed for this window.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001908 if (newTouchedWindowHandle != nullptr &&
1909 newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Garfield Tanaddb02b2019-06-25 16:36:13 -07001910 // New window supports splitting, but we should never split mouse events.
1911 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001912 } else if (isSplit) {
1913 // New window does not support splitting but we have already split events.
1914 // Ignore the new window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001915 newTouchedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001916 }
1917
1918 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001919 if (newTouchedWindowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001920 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001921 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001922 }
1923
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001924 if (newTouchedWindowHandle != nullptr && newTouchedWindowHandle->getInfo()->paused) {
1925 ALOGI("Not sending touch event to %s because it is paused",
1926 newTouchedWindowHandle->getName().c_str());
1927 newTouchedWindowHandle = nullptr;
1928 }
1929
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001930 // Ensure the window has a connection and the connection is responsive
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001931 if (newTouchedWindowHandle != nullptr) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001932 const bool isResponsive = hasResponsiveConnectionLocked(*newTouchedWindowHandle);
1933 if (!isResponsive) {
1934 ALOGW("%s will not receive the new gesture at %" PRIu64,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001935 newTouchedWindowHandle->getName().c_str(), entry.eventTime);
1936 newTouchedWindowHandle = nullptr;
1937 }
1938 }
1939
Bernardo Rufinoea97d182020-08-19 14:43:14 +01001940 // Drop events that can't be trusted due to occlusion
1941 if (newTouchedWindowHandle != nullptr &&
1942 mBlockUntrustedTouchesMode != BlockUntrustedTouchesMode::DISABLED) {
1943 TouchOcclusionInfo occlusionInfo =
1944 computeTouchOcclusionInfoLocked(newTouchedWindowHandle, x, y);
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00001945 if (!isTouchTrustedLocked(occlusionInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00001946 if (DEBUG_TOUCH_OCCLUSION) {
1947 ALOGD("Stack of obscuring windows during untrusted touch (%d, %d):", x, y);
1948 for (const auto& log : occlusionInfo.debugInfo) {
1949 ALOGD("%s", log.c_str());
1950 }
1951 }
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00001952 onUntrustedTouchLocked(occlusionInfo.obscuringPackage);
1953 if (mBlockUntrustedTouchesMode == BlockUntrustedTouchesMode::BLOCK) {
1954 ALOGW("Dropping untrusted touch event due to %s/%d",
1955 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid);
1956 newTouchedWindowHandle = nullptr;
1957 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01001958 }
1959 }
1960
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001961 // Also don't send the new touch event to unresponsive gesture monitors
1962 newGestureMonitors = selectResponsiveMonitorsLocked(newGestureMonitors);
1963
Michael Wright3dd60e22019-03-27 22:06:44 +00001964 if (newTouchedWindowHandle == nullptr && newGestureMonitors.empty()) {
1965 ALOGI("Dropping event because there is no touchable window or gesture monitor at "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001966 "(%d, %d) in display %" PRId32 ".",
1967 x, y, displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001968 injectionResult = InputEventInjectionResult::FAILED;
Michael Wright3dd60e22019-03-27 22:06:44 +00001969 goto Failed;
1970 }
1971
1972 if (newTouchedWindowHandle != nullptr) {
1973 // Set target flags.
1974 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
1975 if (isSplit) {
1976 targetFlags |= InputTarget::FLAG_SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001977 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001978 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1979 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1980 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
1981 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1982 }
1983
1984 // Update hover state.
Garfield Tandf26e862020-07-01 20:18:19 -07001985 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
1986 newHoverWindowHandle = nullptr;
1987 } else if (isHoverAction) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001988 newHoverWindowHandle = newTouchedWindowHandle;
Michael Wright3dd60e22019-03-27 22:06:44 +00001989 }
1990
1991 // Update the temporary touch state.
1992 BitSet32 pointerIds;
1993 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001994 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wright3dd60e22019-03-27 22:06:44 +00001995 pointerIds.markBit(pointerId);
1996 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001997 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001998 }
1999
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002000 tempTouchState.addGestureMonitors(newGestureMonitors);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002001 } else {
2002 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
2003
2004 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002005 if (!tempTouchState.down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002006 if (DEBUG_FOCUS) {
2007 ALOGD("Dropping event because the pointer is not down or we previously "
2008 "dropped the pointer down event in display %" PRId32,
2009 displayId);
2010 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002011 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002012 goto Failed;
2013 }
2014
2015 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002016 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002017 tempTouchState.isSlippery()) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002018 int32_t x = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
2019 int32_t y = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002020
2021 sp<InputWindowHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002022 tempTouchState.getFirstForegroundWindowHandle();
Garfield Tandf26e862020-07-01 20:18:19 -07002023 newTouchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y, &tempTouchState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002024 if (oldTouchedWindowHandle != newTouchedWindowHandle &&
2025 oldTouchedWindowHandle != nullptr && newTouchedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002026 if (DEBUG_FOCUS) {
2027 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
2028 oldTouchedWindowHandle->getName().c_str(),
2029 newTouchedWindowHandle->getName().c_str(), displayId);
2030 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002031 // Make a slippery exit from the old window.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002032 tempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
2033 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT,
2034 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002035
2036 // Make a slippery entrance into the new window.
2037 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
2038 isSplit = true;
2039 }
2040
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002041 int32_t targetFlags =
2042 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002043 if (isSplit) {
2044 targetFlags |= InputTarget::FLAG_SPLIT;
2045 }
2046 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
2047 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002048 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
2049 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002050 }
2051
2052 BitSet32 pointerIds;
2053 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002054 pointerIds.markBit(entry.pointerProperties[0].id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002055 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002056 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002057 }
2058 }
2059 }
2060
2061 if (newHoverWindowHandle != mLastHoverWindowHandle) {
Garfield Tandf26e862020-07-01 20:18:19 -07002062 // Let the previous window know that the hover sequence is over, unless we already did it
2063 // when dispatching it as is to newTouchedWindowHandle.
2064 if (mLastHoverWindowHandle != nullptr &&
2065 (maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT ||
2066 mLastHoverWindowHandle != newTouchedWindowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002067#if DEBUG_HOVER
2068 ALOGD("Sending hover exit event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002069 mLastHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002070#endif
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002071 tempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
2072 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002073 }
2074
Garfield Tandf26e862020-07-01 20:18:19 -07002075 // Let the new window know that the hover sequence is starting, unless we already did it
2076 // when dispatching it as is to newTouchedWindowHandle.
2077 if (newHoverWindowHandle != nullptr &&
2078 (maskedAction != AMOTION_EVENT_ACTION_HOVER_ENTER ||
2079 newHoverWindowHandle != newTouchedWindowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002080#if DEBUG_HOVER
2081 ALOGD("Sending hover enter event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002082 newHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002083#endif
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002084 tempTouchState.addOrUpdateWindow(newHoverWindowHandle,
2085 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER,
2086 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002087 }
2088 }
2089
2090 // Check permission to inject into all touched foreground windows and ensure there
2091 // is at least one touched foreground window.
2092 {
2093 bool haveForegroundWindow = false;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002094 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002095 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
2096 haveForegroundWindow = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002097 if (!checkInjectionPermission(touchedWindow.windowHandle, entry.injectionState)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002098 injectionResult = InputEventInjectionResult::PERMISSION_DENIED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002099 injectionPermission = INJECTION_PERMISSION_DENIED;
2100 goto Failed;
2101 }
2102 }
2103 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002104 bool hasGestureMonitor = !tempTouchState.gestureMonitors.empty();
Michael Wright3dd60e22019-03-27 22:06:44 +00002105 if (!haveForegroundWindow && !hasGestureMonitor) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002106 ALOGI("Dropping event because there is no touched foreground window in display "
2107 "%" PRId32 " or gesture monitor to receive it.",
2108 displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002109 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002110 goto Failed;
2111 }
2112
2113 // Permission granted to injection into all touched foreground windows.
2114 injectionPermission = INJECTION_PERMISSION_GRANTED;
2115 }
2116
2117 // Check whether windows listening for outside touches are owned by the same UID. If it is
2118 // set the policy flag that we will not reveal coordinate information to this window.
2119 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2120 sp<InputWindowHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002121 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002122 if (foregroundWindowHandle) {
2123 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002124 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002125 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2126 sp<InputWindowHandle> inputWindowHandle = touchedWindow.windowHandle;
2127 if (inputWindowHandle->getInfo()->ownerUid != foregroundWindowUid) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002128 tempTouchState.addOrUpdateWindow(inputWindowHandle,
2129 InputTarget::FLAG_ZERO_COORDS,
2130 BitSet32(0));
Michael Wright3dd60e22019-03-27 22:06:44 +00002131 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002132 }
2133 }
2134 }
2135 }
2136
Michael Wrightd02c5b62014-02-10 15:10:22 -08002137 // If this is the first pointer going down and the touched window has a wallpaper
2138 // then also add the touched wallpaper windows so they are locked in for the duration
2139 // of the touch gesture.
2140 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
2141 // engine only supports touch events. We would need to add a mechanism similar
2142 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
2143 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2144 sp<InputWindowHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002145 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002146 if (foregroundWindowHandle && foregroundWindowHandle->getInfo()->hasWallpaper) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07002147 const std::vector<sp<InputWindowHandle>>& windowHandles =
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002148 getWindowHandlesLocked(displayId);
2149 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002150 const InputWindowInfo* info = windowHandle->getInfo();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002151 if (info->displayId == displayId &&
Michael Wright44753b12020-07-08 13:48:11 +01002152 windowHandle->getInfo()->type == InputWindowInfo::Type::WALLPAPER) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002153 tempTouchState
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002154 .addOrUpdateWindow(windowHandle,
2155 InputTarget::FLAG_WINDOW_IS_OBSCURED |
2156 InputTarget::
2157 FLAG_WINDOW_IS_PARTIALLY_OBSCURED |
2158 InputTarget::FLAG_DISPATCH_AS_IS,
2159 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002160 }
2161 }
2162 }
2163 }
2164
2165 // Success! Output targets.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002166 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002167
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002168 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002169 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002170 touchedWindow.pointerIds, inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002171 }
2172
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002173 for (const TouchedMonitor& touchedMonitor : tempTouchState.gestureMonitors) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002174 addMonitoringTargetLocked(touchedMonitor.monitor, touchedMonitor.xOffset,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002175 touchedMonitor.yOffset, inputTargets);
Michael Wright3dd60e22019-03-27 22:06:44 +00002176 }
2177
Michael Wrightd02c5b62014-02-10 15:10:22 -08002178 // Drop the outside or hover touch windows since we will not care about them
2179 // in the next iteration.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002180 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002181
2182Failed:
2183 // Check injection permission once and for all.
2184 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002185 if (checkInjectionPermission(nullptr, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002186 injectionPermission = INJECTION_PERMISSION_GRANTED;
2187 } else {
2188 injectionPermission = INJECTION_PERMISSION_DENIED;
2189 }
2190 }
2191
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002192 if (injectionPermission != INJECTION_PERMISSION_GRANTED) {
2193 return injectionResult;
2194 }
2195
Michael Wrightd02c5b62014-02-10 15:10:22 -08002196 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002197 if (!wrongDevice) {
2198 if (switchedDevice) {
2199 if (DEBUG_FOCUS) {
2200 ALOGD("Conflicting pointer actions: Switched to a different device.");
2201 }
2202 *outConflictingPointerActions = true;
2203 }
2204
2205 if (isHoverAction) {
2206 // Started hovering, therefore no longer down.
2207 if (oldState && oldState->down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002208 if (DEBUG_FOCUS) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002209 ALOGD("Conflicting pointer actions: Hover received while pointer was "
2210 "down.");
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002211 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002212 *outConflictingPointerActions = true;
2213 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002214 tempTouchState.reset();
2215 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2216 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
2217 tempTouchState.deviceId = entry.deviceId;
2218 tempTouchState.source = entry.source;
2219 tempTouchState.displayId = displayId;
2220 }
2221 } else if (maskedAction == AMOTION_EVENT_ACTION_UP ||
2222 maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
2223 // All pointers up or canceled.
2224 tempTouchState.reset();
2225 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2226 // First pointer went down.
2227 if (oldState && oldState->down) {
2228 if (DEBUG_FOCUS) {
2229 ALOGD("Conflicting pointer actions: Down received while already down.");
2230 }
2231 *outConflictingPointerActions = true;
2232 }
2233 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2234 // One pointer went up.
2235 if (isSplit) {
2236 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2237 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002238
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002239 for (size_t i = 0; i < tempTouchState.windows.size();) {
2240 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2241 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
2242 touchedWindow.pointerIds.clearBit(pointerId);
2243 if (touchedWindow.pointerIds.isEmpty()) {
2244 tempTouchState.windows.erase(tempTouchState.windows.begin() + i);
2245 continue;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002246 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002247 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002248 i += 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002249 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002250 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002251 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002252
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002253 // Save changes unless the action was scroll in which case the temporary touch
2254 // state was only valid for this one action.
2255 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
2256 if (tempTouchState.displayId >= 0) {
2257 mTouchStatesByDisplay[displayId] = tempTouchState;
2258 } else {
2259 mTouchStatesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002260 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002261 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002262
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002263 // Update hover state.
2264 mLastHoverWindowHandle = newHoverWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002265 }
2266
Michael Wrightd02c5b62014-02-10 15:10:22 -08002267 return injectionResult;
2268}
2269
2270void InputDispatcher::addWindowTargetLocked(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002271 int32_t targetFlags, BitSet32 pointerIds,
2272 std::vector<InputTarget>& inputTargets) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002273 std::vector<InputTarget>::iterator it =
2274 std::find_if(inputTargets.begin(), inputTargets.end(),
2275 [&windowHandle](const InputTarget& inputTarget) {
2276 return inputTarget.inputChannel->getConnectionToken() ==
2277 windowHandle->getToken();
2278 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002279
Chavi Weingarten114b77f2020-01-15 22:35:10 +00002280 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002281
2282 if (it == inputTargets.end()) {
2283 InputTarget inputTarget;
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05002284 std::shared_ptr<InputChannel> inputChannel =
2285 getInputChannelLocked(windowHandle->getToken());
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002286 if (inputChannel == nullptr) {
2287 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
2288 return;
2289 }
2290 inputTarget.inputChannel = inputChannel;
2291 inputTarget.flags = targetFlags;
2292 inputTarget.globalScaleFactor = windowInfo->globalScaleFactor;
2293 inputTargets.push_back(inputTarget);
2294 it = inputTargets.end() - 1;
2295 }
2296
2297 ALOG_ASSERT(it->flags == targetFlags);
2298 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
2299
chaviw1ff3d1e2020-07-01 15:53:47 -07002300 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002301}
2302
Michael Wright3dd60e22019-03-27 22:06:44 +00002303void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002304 int32_t displayId, float xOffset,
2305 float yOffset) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002306 std::unordered_map<int32_t, std::vector<Monitor>>::const_iterator it =
2307 mGlobalMonitorsByDisplay.find(displayId);
2308
2309 if (it != mGlobalMonitorsByDisplay.end()) {
2310 const std::vector<Monitor>& monitors = it->second;
2311 for (const Monitor& monitor : monitors) {
2312 addMonitoringTargetLocked(monitor, xOffset, yOffset, inputTargets);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002313 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002314 }
2315}
2316
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002317void InputDispatcher::addMonitoringTargetLocked(const Monitor& monitor, float xOffset,
2318 float yOffset,
2319 std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002320 InputTarget target;
2321 target.inputChannel = monitor.inputChannel;
2322 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
chaviw1ff3d1e2020-07-01 15:53:47 -07002323 ui::Transform t;
2324 t.set(xOffset, yOffset);
2325 target.setDefaultPointerTransform(t);
Michael Wright3dd60e22019-03-27 22:06:44 +00002326 inputTargets.push_back(target);
2327}
2328
Michael Wrightd02c5b62014-02-10 15:10:22 -08002329bool InputDispatcher::checkInjectionPermission(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002330 const InjectionState* injectionState) {
2331 if (injectionState &&
2332 (windowHandle == nullptr ||
2333 windowHandle->getInfo()->ownerUid != injectionState->injectorUid) &&
2334 !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002335 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002336 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002337 "owned by uid %d",
2338 injectionState->injectorPid, injectionState->injectorUid,
2339 windowHandle->getName().c_str(), windowHandle->getInfo()->ownerUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002340 } else {
2341 ALOGW("Permission denied: injecting event from pid %d uid %d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002342 injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002343 }
2344 return false;
2345 }
2346 return true;
2347}
2348
Robert Carrc9bf1d32020-04-13 17:21:08 -07002349/**
2350 * Indicate whether one window handle should be considered as obscuring
2351 * another window handle. We only check a few preconditions. Actually
2352 * checking the bounds is left to the caller.
2353 */
2354static bool canBeObscuredBy(const sp<InputWindowHandle>& windowHandle,
2355 const sp<InputWindowHandle>& otherHandle) {
2356 // Compare by token so cloned layers aren't counted
2357 if (haveSameToken(windowHandle, otherHandle)) {
2358 return false;
2359 }
2360 auto info = windowHandle->getInfo();
2361 auto otherInfo = otherHandle->getInfo();
2362 if (!otherInfo->visible) {
2363 return false;
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002364 } else if (otherInfo->alpha == 0 &&
2365 otherInfo->flags.test(InputWindowInfo::Flag::NOT_TOUCHABLE)) {
2366 // Those act as if they were invisible, so we don't need to flag them.
2367 // We do want to potentially flag touchable windows even if they have 0
2368 // opacity, since they can consume touches and alter the effects of the
2369 // user interaction (eg. apps that rely on
2370 // FLAG_WINDOW_IS_PARTIALLY_OBSCURED should still be told about those
2371 // windows), hence we also check for FLAG_NOT_TOUCHABLE.
2372 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00002373 } else if (info->ownerUid == otherInfo->ownerUid) {
2374 // If ownerUid is the same we don't generate occlusion events as there
2375 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002376 return false;
Chris Yefcdff3e2020-05-10 15:16:04 -07002377 } else if (otherInfo->trustedOverlay) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002378 return false;
2379 } else if (otherInfo->displayId != info->displayId) {
2380 return false;
2381 }
2382 return true;
2383}
2384
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002385/**
2386 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
2387 * untrusted, one should check:
2388 *
2389 * 1. If result.hasBlockingOcclusion is true.
2390 * If it's, it means the touch should be blocked due to a window with occlusion mode of
2391 * BLOCK_UNTRUSTED.
2392 *
2393 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
2394 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
2395 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
2396 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
2397 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
2398 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
2399 *
2400 * If neither of those is true, then it means the touch can be allowed.
2401 */
2402InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
2403 const sp<InputWindowHandle>& windowHandle, int32_t x, int32_t y) const {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002404 const InputWindowInfo* windowInfo = windowHandle->getInfo();
2405 int32_t displayId = windowInfo->displayId;
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002406 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2407 TouchOcclusionInfo info;
2408 info.hasBlockingOcclusion = false;
2409 info.obscuringOpacity = 0;
2410 info.obscuringUid = -1;
2411 std::map<int32_t, float> opacityByUid;
2412 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
2413 if (windowHandle == otherHandle) {
2414 break; // All future windows are below us. Exit early.
2415 }
2416 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Bernardo Rufino1ff9d592021-01-18 16:58:57 +00002417 if (canBeObscuredBy(windowHandle, otherHandle) && otherInfo->frameContainsPoint(x, y) &&
2418 !haveSameApplicationToken(windowInfo, otherInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002419 if (DEBUG_TOUCH_OCCLUSION) {
2420 info.debugInfo.push_back(
2421 dumpWindowForTouchOcclusion(otherInfo, /* isTouchedWindow */ false));
2422 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002423 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
2424 // we perform the checks below to see if the touch can be propagated or not based on the
2425 // window's touch occlusion mode
2426 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
2427 info.hasBlockingOcclusion = true;
2428 info.obscuringUid = otherInfo->ownerUid;
2429 info.obscuringPackage = otherInfo->packageName;
2430 break;
2431 }
2432 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
2433 uint32_t uid = otherInfo->ownerUid;
2434 float opacity =
2435 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
2436 // Given windows A and B:
2437 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
2438 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
2439 opacityByUid[uid] = opacity;
2440 if (opacity > info.obscuringOpacity) {
2441 info.obscuringOpacity = opacity;
2442 info.obscuringUid = uid;
2443 info.obscuringPackage = otherInfo->packageName;
2444 }
2445 }
2446 }
2447 }
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002448 if (DEBUG_TOUCH_OCCLUSION) {
2449 info.debugInfo.push_back(
2450 dumpWindowForTouchOcclusion(windowInfo, /* isTouchedWindow */ true));
2451 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002452 return info;
2453}
2454
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002455std::string InputDispatcher::dumpWindowForTouchOcclusion(const InputWindowInfo* info,
2456 bool isTouchedWindow) const {
Bernardo Rufino49d99e42021-01-18 15:16:59 +00002457 return StringPrintf(INDENT2
2458 "* %stype=%s, package=%s/%" PRId32 ", id=%" PRId32 ", mode=%s, alpha=%.2f, "
2459 "frame=[%" PRId32 ",%" PRId32 "][%" PRId32 ",%" PRId32
2460 "], touchableRegion=%s, window={%s}, flags={%s}, inputFeatures={%s}, "
2461 "hasToken=%s, applicationInfo.name=%s, applicationInfo.token=%s\n",
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002462 (isTouchedWindow) ? "[TOUCHED] " : "",
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00002463 NamedEnum::string(info->type, "%" PRId32).c_str(),
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00002464 info->packageName.c_str(), info->ownerUid, info->id,
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00002465 toString(info->touchOcclusionMode).c_str(), info->alpha, info->frameLeft,
2466 info->frameTop, info->frameRight, info->frameBottom,
2467 dumpRegion(info->touchableRegion).c_str(), info->name.c_str(),
Bernardo Rufino49d99e42021-01-18 15:16:59 +00002468 info->flags.string().c_str(), info->inputFeatures.string().c_str(),
2469 toString(info->token != nullptr), info->applicationInfo.name.c_str(),
2470 toString(info->applicationInfo.token).c_str());
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002471}
2472
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002473bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
2474 if (occlusionInfo.hasBlockingOcclusion) {
2475 ALOGW("Untrusted touch due to occlusion by %s/%d", occlusionInfo.obscuringPackage.c_str(),
2476 occlusionInfo.obscuringUid);
2477 return false;
2478 }
2479 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
2480 ALOGW("Untrusted touch due to occlusion by %s/%d (obscuring opacity = "
2481 "%.2f, maximum allowed = %.2f)",
2482 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid,
2483 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
2484 return false;
2485 }
2486 return true;
2487}
2488
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002489bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<InputWindowHandle>& windowHandle,
2490 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002491 int32_t displayId = windowHandle->getInfo()->displayId;
Vishnu Nairad321cd2020-08-20 16:40:21 -07002492 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002493 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002494 if (windowHandle == otherHandle) {
2495 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002496 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002497 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002498 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002499 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002500 return true;
2501 }
2502 }
2503 return false;
2504}
2505
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002506bool InputDispatcher::isWindowObscuredLocked(const sp<InputWindowHandle>& windowHandle) const {
2507 int32_t displayId = windowHandle->getInfo()->displayId;
Vishnu Nairad321cd2020-08-20 16:40:21 -07002508 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002509 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002510 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002511 if (windowHandle == otherHandle) {
2512 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002513 }
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002514 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002515 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002516 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002517 return true;
2518 }
2519 }
2520 return false;
2521}
2522
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002523std::string InputDispatcher::getApplicationWindowLabel(
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05002524 const InputApplicationHandle* applicationHandle,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002525 const sp<InputWindowHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002526 if (applicationHandle != nullptr) {
2527 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002528 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002529 } else {
2530 return applicationHandle->getName();
2531 }
Yi Kong9b14ac62018-07-17 13:48:38 -07002532 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002533 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002534 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002535 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002536 }
2537}
2538
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002539void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Prabir Pradhan99987712020-11-10 18:43:05 -08002540 if (eventEntry.type == EventEntry::Type::FOCUS ||
2541 eventEntry.type == EventEntry::Type::POINTER_CAPTURE_CHANGED) {
2542 // Focus or pointer capture changed events are passed to apps, but do not represent user
2543 // activity.
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002544 return;
2545 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002546 int32_t displayId = getTargetDisplayId(eventEntry);
Vishnu Nairad321cd2020-08-20 16:40:21 -07002547 sp<InputWindowHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Tiger Huang721e26f2018-07-24 22:26:19 +08002548 if (focusedWindowHandle != nullptr) {
2549 const InputWindowInfo* info = focusedWindowHandle->getInfo();
Michael Wright44753b12020-07-08 13:48:11 +01002550 if (info->inputFeatures.test(InputWindowInfo::Feature::DISABLE_USER_ACTIVITY)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002551#if DEBUG_DISPATCH_CYCLE
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002552 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002553#endif
2554 return;
2555 }
2556 }
2557
2558 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002559 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002560 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002561 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
2562 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002563 return;
2564 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002565
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002566 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002567 eventType = USER_ACTIVITY_EVENT_TOUCH;
2568 }
2569 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002570 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002571 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002572 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
2573 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002574 return;
2575 }
2576 eventType = USER_ACTIVITY_EVENT_BUTTON;
2577 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002578 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002579 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002580 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08002581 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07002582 case EventEntry::Type::SENSOR:
Prabir Pradhan99987712020-11-10 18:43:05 -08002583 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002584 LOG_ALWAYS_FATAL("%s events are not user activity",
Chris Yef59a2f42020-10-16 12:55:26 -07002585 NamedEnum::string(eventEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002586 break;
2587 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002588 }
2589
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002590 std::unique_ptr<CommandEntry> commandEntry =
2591 std::make_unique<CommandEntry>(&InputDispatcher::doPokeUserActivityLockedInterruptible);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002592 commandEntry->eventTime = eventEntry.eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002593 commandEntry->userActivityEventType = eventType;
Sean Stoutb4e0a592021-02-23 07:34:53 -08002594 commandEntry->displayId = displayId;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002595 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002596}
2597
2598void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002599 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002600 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002601 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002602 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002603 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002604 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002605 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002606 ATRACE_NAME(message.c_str());
2607 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002608#if DEBUG_DISPATCH_CYCLE
2609 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002610 "globalScaleFactor=%f, pointerIds=0x%x %s",
2611 connection->getInputChannelName().c_str(), inputTarget.flags,
2612 inputTarget.globalScaleFactor, inputTarget.pointerIds.value,
2613 inputTarget.getPointerInfoString().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002614#endif
2615
2616 // Skip this event if the connection status is not normal.
2617 // We don't want to enqueue additional outbound events if the connection is broken.
2618 if (connection->status != Connection::STATUS_NORMAL) {
2619#if DEBUG_DISPATCH_CYCLE
2620 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002621 connection->getInputChannelName().c_str(), connection->getStatusLabel());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002622#endif
2623 return;
2624 }
2625
2626 // Split a motion event if needed.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002627 if (inputTarget.flags & InputTarget::FLAG_SPLIT) {
2628 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
2629 "Entry type %s should not have FLAG_SPLIT",
Chris Yef59a2f42020-10-16 12:55:26 -07002630 NamedEnum::string(eventEntry->type).c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002631
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002632 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002633 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002634 std::unique_ptr<MotionEntry> splitMotionEntry =
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002635 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002636 if (!splitMotionEntry) {
2637 return; // split event was dropped
2638 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002639 if (DEBUG_FOCUS) {
2640 ALOGD("channel '%s' ~ Split motion event.",
2641 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002642 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002643 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002644 enqueueDispatchEntriesLocked(currentTime, connection, std::move(splitMotionEntry),
2645 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002646 return;
2647 }
2648 }
2649
2650 // Not splitting. Enqueue dispatch entries for the event as is.
2651 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
2652}
2653
2654void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002655 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002656 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002657 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002658 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002659 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002660 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002661 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002662 ATRACE_NAME(message.c_str());
2663 }
2664
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002665 bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002666
2667 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07002668 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002669 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002670 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002671 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07002672 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002673 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07002674 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002675 InputTarget::FLAG_DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07002676 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002677 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002678 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002679 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002680
2681 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002682 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002683 startDispatchCycleLocked(currentTime, connection);
2684 }
2685}
2686
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002687void InputDispatcher::enqueueDispatchEntryLocked(const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002688 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002689 const InputTarget& inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002690 int32_t dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002691 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002692 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
2693 connection->getInputChannelName().c_str(),
2694 dispatchModeToString(dispatchMode).c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002695 ATRACE_NAME(message.c_str());
2696 }
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002697 int32_t inputTargetFlags = inputTarget.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002698 if (!(inputTargetFlags & dispatchMode)) {
2699 return;
2700 }
2701 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
2702
2703 // This is a new event.
2704 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002705 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002706 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002707
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002708 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
2709 // different EventEntry than what was passed in.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002710 EventEntry& newEntry = *(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002711 // Apply target flags and update the connection's input state.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002712 switch (newEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002713 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002714 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002715 dispatchEntry->resolvedEventId = keyEntry.id;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002716 dispatchEntry->resolvedAction = keyEntry.action;
2717 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002718
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002719 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
2720 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002721#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002722 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key event",
2723 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002724#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002725 return; // skip the inconsistent event
2726 }
2727 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002728 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002729
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002730 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002731 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002732 // Assign a default value to dispatchEntry that will never be generated by InputReader,
2733 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
2734 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
2735 static_cast<int32_t>(IdGenerator::Source::OTHER);
2736 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002737 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2738 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
2739 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
2740 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
2741 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
2742 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2743 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
2744 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
2745 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
2746 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
2747 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002748 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002749 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002750 }
2751 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002752 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
2753 motionEntry.displayId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002754#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002755 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover enter "
2756 "event",
2757 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002758#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002759 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2760 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002761
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002762 dispatchEntry->resolvedFlags = motionEntry.flags;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002763 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
2764 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
2765 }
2766 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
2767 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2768 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002769
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002770 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
2771 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002772#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002773 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
2774 "event",
2775 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002776#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002777 return; // skip the inconsistent event
2778 }
2779
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002780 dispatchEntry->resolvedEventId =
2781 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
2782 ? mIdGenerator.nextId()
2783 : motionEntry.id;
2784 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
2785 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
2786 ") to MotionEvent(id=0x%" PRIx32 ").",
2787 motionEntry.id, dispatchEntry->resolvedEventId);
2788 ATRACE_NAME(message.c_str());
2789 }
2790
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002791 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002792 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002793
2794 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002795 }
Prabir Pradhan99987712020-11-10 18:43:05 -08002796 case EventEntry::Type::FOCUS:
2797 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002798 break;
2799 }
Chris Yef59a2f42020-10-16 12:55:26 -07002800 case EventEntry::Type::SENSOR: {
2801 LOG_ALWAYS_FATAL("SENSOR events should not go to apps via input channel");
2802 break;
2803 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002804 case EventEntry::Type::CONFIGURATION_CHANGED:
2805 case EventEntry::Type::DEVICE_RESET: {
2806 LOG_ALWAYS_FATAL("%s events should not go to apps",
Chris Yef59a2f42020-10-16 12:55:26 -07002807 NamedEnum::string(newEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002808 break;
2809 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002810 }
2811
2812 // Remember that we are waiting for this dispatch to complete.
2813 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002814 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002815 }
2816
2817 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002818 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002819 traceOutboundQueueLength(connection);
chaviw8c9cf542019-03-25 13:02:48 -07002820}
2821
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00002822/**
2823 * This function is purely for debugging. It helps us understand where the user interaction
2824 * was taking place. For example, if user is touching launcher, we will see a log that user
2825 * started interacting with launcher. In that example, the event would go to the wallpaper as well.
2826 * We will see both launcher and wallpaper in that list.
2827 * Once the interaction with a particular set of connections starts, no new logs will be printed
2828 * until the set of interacted connections changes.
2829 *
2830 * The following items are skipped, to reduce the logspam:
2831 * ACTION_OUTSIDE: any windows that are receiving ACTION_OUTSIDE are not logged
2832 * ACTION_UP: any windows that receive ACTION_UP are not logged (for both keys and motions).
2833 * This includes situations like the soft BACK button key. When the user releases (lifts up the
2834 * finger) the back button, then navigation bar will inject KEYCODE_BACK with ACTION_UP.
2835 * Both of those ACTION_UP events would not be logged
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00002836 */
2837void InputDispatcher::updateInteractionTokensLocked(const EventEntry& entry,
2838 const std::vector<InputTarget>& targets) {
2839 // Skip ACTION_UP events, and all events other than keys and motions
2840 if (entry.type == EventEntry::Type::KEY) {
2841 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
2842 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
2843 return;
2844 }
2845 } else if (entry.type == EventEntry::Type::MOTION) {
2846 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
2847 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
2848 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
2849 return;
2850 }
2851 } else {
2852 return; // Not a key or a motion
2853 }
2854
2855 std::unordered_set<sp<IBinder>, IBinderHash> newConnectionTokens;
2856 std::vector<sp<Connection>> newConnections;
2857 for (const InputTarget& target : targets) {
2858 if ((target.flags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) ==
2859 InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2860 continue; // Skip windows that receive ACTION_OUTSIDE
2861 }
2862
2863 sp<IBinder> token = target.inputChannel->getConnectionToken();
2864 sp<Connection> connection = getConnectionLocked(token);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00002865 if (connection == nullptr) {
2866 continue;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00002867 }
2868 newConnectionTokens.insert(std::move(token));
2869 newConnections.emplace_back(connection);
2870 }
2871 if (newConnectionTokens == mInteractionConnectionTokens) {
2872 return; // no change
2873 }
2874 mInteractionConnectionTokens = newConnectionTokens;
2875
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00002876 std::string targetList;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00002877 for (const sp<Connection>& connection : newConnections) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00002878 targetList += connection->getWindowName() + ", ";
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00002879 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00002880 std::string message = "Interaction with: " + targetList;
2881 if (targetList.empty()) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00002882 message += "<none>";
2883 }
2884 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
2885}
2886
chaviwfd6d3512019-03-25 13:23:49 -07002887void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07002888 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07002889 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07002890 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
2891 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07002892 return;
2893 }
2894
Vishnu Nairc519ff72021-01-21 08:23:08 -08002895 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07002896 if (focusedToken == token) {
2897 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07002898 return;
2899 }
2900
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002901 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
2902 &InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible);
Vishnu Nairad321cd2020-08-20 16:40:21 -07002903 commandEntry->newToken = token;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002904 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002905}
2906
2907void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002908 const sp<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002909 if (ATRACE_ENABLED()) {
2910 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002911 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002912 ATRACE_NAME(message.c_str());
2913 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002914#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002915 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002916#endif
2917
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002918 while (connection->status == Connection::STATUS_NORMAL && !connection->outboundQueue.empty()) {
2919 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002920 dispatchEntry->deliveryTime = currentTime;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05002921 const std::chrono::nanoseconds timeout =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002922 getDispatchingTimeoutLocked(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou70622952020-07-30 11:17:23 -05002923 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002924
2925 // Publish the event.
2926 status_t status;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002927 const EventEntry& eventEntry = *(dispatchEntry->eventEntry);
2928 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002929 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002930 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
2931 std::array<uint8_t, 32> hmac = getSignature(keyEntry, *dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002932
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002933 // Publish the key event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002934 status = connection->inputPublisher
2935 .publishKeyEvent(dispatchEntry->seq,
2936 dispatchEntry->resolvedEventId, keyEntry.deviceId,
2937 keyEntry.source, keyEntry.displayId,
2938 std::move(hmac), dispatchEntry->resolvedAction,
2939 dispatchEntry->resolvedFlags, keyEntry.keyCode,
2940 keyEntry.scanCode, keyEntry.metaState,
2941 keyEntry.repeatCount, keyEntry.downTime,
2942 keyEntry.eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002943 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002944 }
2945
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002946 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002947 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002948
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002949 PointerCoords scaledCoords[MAX_POINTERS];
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002950 const PointerCoords* usingCoords = motionEntry.pointerCoords;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002951
chaviw82357092020-01-28 13:13:06 -08002952 // Set the X and Y offset and X and Y scale depending on the input source.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002953 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) &&
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002954 !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
2955 float globalScaleFactor = dispatchEntry->globalScaleFactor;
chaviw82357092020-01-28 13:13:06 -08002956 if (globalScaleFactor != 1.0f) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002957 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
2958 scaledCoords[i] = motionEntry.pointerCoords[i];
chaviw82357092020-01-28 13:13:06 -08002959 // Don't apply window scale here since we don't want scale to affect raw
2960 // coordinates. The scale will be sent back to the client and applied
2961 // later when requesting relative coordinates.
2962 scaledCoords[i].scale(globalScaleFactor, 1 /* windowXScale */,
2963 1 /* windowYScale */);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002964 }
2965 usingCoords = scaledCoords;
2966 }
2967 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002968 // We don't want the dispatch target to know.
2969 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002970 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002971 scaledCoords[i].clear();
2972 }
2973 usingCoords = scaledCoords;
2974 }
2975 }
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07002976
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002977 std::array<uint8_t, 32> hmac = getSignature(motionEntry, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002978
2979 // Publish the motion event.
2980 status = connection->inputPublisher
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002981 .publishMotionEvent(dispatchEntry->seq,
2982 dispatchEntry->resolvedEventId,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002983 motionEntry.deviceId, motionEntry.source,
2984 motionEntry.displayId, std::move(hmac),
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002985 dispatchEntry->resolvedAction,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002986 motionEntry.actionButton,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002987 dispatchEntry->resolvedFlags,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002988 motionEntry.edgeFlags, motionEntry.metaState,
2989 motionEntry.buttonState,
2990 motionEntry.classification,
chaviw9eaa22c2020-07-01 16:21:27 -07002991 dispatchEntry->transform,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002992 motionEntry.xPrecision, motionEntry.yPrecision,
2993 motionEntry.xCursorPosition,
2994 motionEntry.yCursorPosition,
2995 motionEntry.downTime, motionEntry.eventTime,
2996 motionEntry.pointerCount,
2997 motionEntry.pointerProperties, usingCoords);
2998 reportTouchEventForStatistics(motionEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002999 break;
3000 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003001
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003002 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003003 const FocusEntry& focusEntry = static_cast<const FocusEntry&>(eventEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003004 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003005 focusEntry.id,
3006 focusEntry.hasFocus,
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003007 mInTouchMode);
3008 break;
3009 }
3010
Prabir Pradhan99987712020-11-10 18:43:05 -08003011 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3012 const auto& captureEntry =
3013 static_cast<const PointerCaptureChangedEntry&>(eventEntry);
3014 status = connection->inputPublisher
3015 .publishCaptureEvent(dispatchEntry->seq, captureEntry.id,
3016 captureEntry.pointerCaptureEnabled);
3017 break;
3018 }
3019
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003020 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003021 case EventEntry::Type::DEVICE_RESET:
3022 case EventEntry::Type::SENSOR: {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003023 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
Chris Yef59a2f42020-10-16 12:55:26 -07003024 NamedEnum::string(eventEntry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003025 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003026 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003027 }
3028
3029 // Check the result.
3030 if (status) {
3031 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003032 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003033 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003034 "This is unexpected because the wait queue is empty, so the pipe "
3035 "should be empty and we shouldn't have any problems writing an "
3036 "event to it, status=%d",
3037 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003038 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3039 } else {
3040 // Pipe is full and we are waiting for the app to finish process some events
3041 // before sending more events to it.
3042#if DEBUG_DISPATCH_CYCLE
3043 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003044 "waiting for the application to catch up",
3045 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003046#endif
Michael Wrightd02c5b62014-02-10 15:10:22 -08003047 }
3048 } else {
3049 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003050 "status=%d",
3051 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003052 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3053 }
3054 return;
3055 }
3056
3057 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003058 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
3059 connection->outboundQueue.end(),
3060 dispatchEntry));
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003061 traceOutboundQueueLength(connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003062 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003063 if (connection->responsive) {
3064 mAnrTracker.insert(dispatchEntry->timeoutTime,
3065 connection->inputChannel->getConnectionToken());
3066 }
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003067 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003068 }
3069}
3070
chaviw09c8d2d2020-08-24 15:48:26 -07003071std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
3072 size_t size;
3073 switch (event.type) {
3074 case VerifiedInputEvent::Type::KEY: {
3075 size = sizeof(VerifiedKeyEvent);
3076 break;
3077 }
3078 case VerifiedInputEvent::Type::MOTION: {
3079 size = sizeof(VerifiedMotionEvent);
3080 break;
3081 }
3082 }
3083 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
3084 return mHmacKeyManager.sign(start, size);
3085}
3086
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003087const std::array<uint8_t, 32> InputDispatcher::getSignature(
3088 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
3089 int32_t actionMasked = dispatchEntry.resolvedAction & AMOTION_EVENT_ACTION_MASK;
3090 if ((actionMasked == AMOTION_EVENT_ACTION_UP) || (actionMasked == AMOTION_EVENT_ACTION_DOWN)) {
3091 // Only sign events up and down events as the purely move events
3092 // are tied to their up/down counterparts so signing would be redundant.
3093 VerifiedMotionEvent verifiedEvent = verifiedMotionEventFromMotionEntry(motionEntry);
3094 verifiedEvent.actionMasked = actionMasked;
3095 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
chaviw09c8d2d2020-08-24 15:48:26 -07003096 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003097 }
3098 return INVALID_HMAC;
3099}
3100
3101const std::array<uint8_t, 32> InputDispatcher::getSignature(
3102 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
3103 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
3104 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
3105 verifiedEvent.action = dispatchEntry.resolvedAction;
chaviw09c8d2d2020-08-24 15:48:26 -07003106 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003107}
3108
Michael Wrightd02c5b62014-02-10 15:10:22 -08003109void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003110 const sp<Connection>& connection, uint32_t seq,
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10003111 bool handled, nsecs_t consumeTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003112#if DEBUG_DISPATCH_CYCLE
3113 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003114 connection->getInputChannelName().c_str(), seq, toString(handled));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003115#endif
3116
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003117 if (connection->status == Connection::STATUS_BROKEN ||
3118 connection->status == Connection::STATUS_ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003119 return;
3120 }
3121
3122 // Notify other system components and prepare to start the next dispatch cycle.
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10003123 onDispatchCycleFinishedLocked(currentTime, connection, seq, handled, consumeTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003124}
3125
3126void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003127 const sp<Connection>& connection,
3128 bool notify) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003129#if DEBUG_DISPATCH_CYCLE
3130 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003131 connection->getInputChannelName().c_str(), toString(notify));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003132#endif
3133
3134 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003135 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003136 traceOutboundQueueLength(connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003137 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003138 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003139
3140 // The connection appears to be unrecoverably broken.
3141 // Ignore already broken or zombie connections.
3142 if (connection->status == Connection::STATUS_NORMAL) {
3143 connection->status = Connection::STATUS_BROKEN;
3144
3145 if (notify) {
3146 // Notify other system components.
3147 onDispatchCycleBrokenLocked(currentTime, connection);
3148 }
3149 }
3150}
3151
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003152void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
3153 while (!queue.empty()) {
3154 DispatchEntry* dispatchEntry = queue.front();
3155 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003156 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003157 }
3158}
3159
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003160void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003161 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003162 decrementPendingForegroundDispatches(*(dispatchEntry->eventEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003163 }
3164 delete dispatchEntry;
3165}
3166
3167int InputDispatcher::handleReceiveCallback(int fd, int events, void* data) {
3168 InputDispatcher* d = static_cast<InputDispatcher*>(data);
3169
3170 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003171 std::scoped_lock _l(d->mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003172
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003173 if (d->mConnectionsByFd.find(fd) == d->mConnectionsByFd.end()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003174 ALOGE("Received spurious receive callback for unknown input channel. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003175 "fd=%d, events=0x%x",
3176 fd, events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003177 return 0; // remove the callback
3178 }
3179
3180 bool notify;
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003181 sp<Connection> connection = d->mConnectionsByFd[fd];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003182 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
3183 if (!(events & ALOOPER_EVENT_INPUT)) {
3184 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003185 "events=0x%x",
3186 connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003187 return 1;
3188 }
3189
3190 nsecs_t currentTime = now();
3191 bool gotOne = false;
3192 status_t status;
3193 for (;;) {
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10003194 std::function<void(uint32_t seq, bool handled, nsecs_t consumeTime)> callback =
3195 std::bind(&InputDispatcher::finishDispatchCycleLocked, d, currentTime,
3196 connection, std::placeholders::_1, std::placeholders::_2,
3197 std::placeholders::_3);
3198
3199 status = connection->inputPublisher.receiveFinishedSignal(callback);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003200 if (status) {
3201 break;
3202 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003203 gotOne = true;
3204 }
3205 if (gotOne) {
3206 d->runCommandsLockedInterruptible();
3207 if (status == WOULD_BLOCK) {
3208 return 1;
3209 }
3210 }
3211
3212 notify = status != DEAD_OBJECT || !connection->monitor;
3213 if (notify) {
3214 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003215 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003216 }
3217 } else {
3218 // Monitor channels are never explicitly unregistered.
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003219 // We do it automatically when the remote endpoint is closed so don't warn about them.
arthurhungd352cb32020-04-28 17:09:28 +08003220 const bool stillHaveWindowHandle =
3221 d->getWindowHandleLocked(connection->inputChannel->getConnectionToken()) !=
3222 nullptr;
3223 notify = !connection->monitor && stillHaveWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003224 if (notify) {
3225 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003226 "events=0x%x",
3227 connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003228 }
3229 }
3230
Garfield Tan15601662020-09-22 15:32:38 -07003231 // Remove the channel.
3232 d->removeInputChannelLocked(connection->inputChannel->getConnectionToken(), notify);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003233 return 0; // remove the callback
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003234 } // release lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08003235}
3236
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003237void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08003238 const CancelationOptions& options) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +00003239 for (const auto& [fd, connection] : mConnectionsByFd) {
3240 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003241 }
3242}
3243
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003244void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003245 const CancelationOptions& options) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003246 synthesizeCancelationEventsForMonitorsLocked(options, mGlobalMonitorsByDisplay);
3247 synthesizeCancelationEventsForMonitorsLocked(options, mGestureMonitorsByDisplay);
3248}
3249
3250void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
3251 const CancelationOptions& options,
3252 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
3253 for (const auto& it : monitorsByDisplay) {
3254 const std::vector<Monitor>& monitors = it.second;
3255 for (const Monitor& monitor : monitors) {
3256 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003257 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003258 }
3259}
3260
Michael Wrightd02c5b62014-02-10 15:10:22 -08003261void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003262 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07003263 sp<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003264 if (connection == nullptr) {
3265 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003266 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003267
3268 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003269}
3270
3271void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
3272 const sp<Connection>& connection, const CancelationOptions& options) {
3273 if (connection->status == Connection::STATUS_BROKEN) {
3274 return;
3275 }
3276
3277 nsecs_t currentTime = now();
3278
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003279 std::vector<std::unique_ptr<EventEntry>> cancelationEvents =
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07003280 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003281
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003282 if (cancelationEvents.empty()) {
3283 return;
3284 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003285#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003286 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
3287 "with reality: %s, mode=%d.",
3288 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
3289 options.mode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003290#endif
Svet Ganov5d3bc372020-01-26 23:11:07 -08003291
3292 InputTarget target;
3293 sp<InputWindowHandle> windowHandle =
3294 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3295 if (windowHandle != nullptr) {
3296 const InputWindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003297 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003298 target.globalScaleFactor = windowInfo->globalScaleFactor;
3299 }
3300 target.inputChannel = connection->inputChannel;
3301 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3302
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003303 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003304 std::unique_ptr<EventEntry> cancelationEventEntry = std::move(cancelationEvents[i]);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003305 switch (cancelationEventEntry->type) {
3306 case EventEntry::Type::KEY: {
3307 logOutboundKeyDetails("cancel - ",
3308 static_cast<const KeyEntry&>(*cancelationEventEntry));
3309 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003310 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003311 case EventEntry::Type::MOTION: {
3312 logOutboundMotionDetails("cancel - ",
3313 static_cast<const MotionEntry&>(*cancelationEventEntry));
3314 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003315 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003316 case EventEntry::Type::FOCUS:
3317 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3318 LOG_ALWAYS_FATAL("Canceling %s events is not supported",
Chris Yef59a2f42020-10-16 12:55:26 -07003319 NamedEnum::string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003320 break;
3321 }
3322 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003323 case EventEntry::Type::DEVICE_RESET:
3324 case EventEntry::Type::SENSOR: {
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003325 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Chris Yef59a2f42020-10-16 12:55:26 -07003326 NamedEnum::string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003327 break;
3328 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003329 }
3330
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003331 enqueueDispatchEntryLocked(connection, std::move(cancelationEventEntry), target,
3332 InputTarget::FLAG_DISPATCH_AS_IS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003333 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003334
3335 startDispatchCycleLocked(currentTime, connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003336}
3337
Svet Ganov5d3bc372020-01-26 23:11:07 -08003338void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
3339 const sp<Connection>& connection) {
3340 if (connection->status == Connection::STATUS_BROKEN) {
3341 return;
3342 }
3343
3344 nsecs_t currentTime = now();
3345
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003346 std::vector<std::unique_ptr<EventEntry>> downEvents =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003347 connection->inputState.synthesizePointerDownEvents(currentTime);
3348
3349 if (downEvents.empty()) {
3350 return;
3351 }
3352
3353#if DEBUG_OUTBOUND_EVENT_DETAILS
3354 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
3355 connection->getInputChannelName().c_str(), downEvents.size());
3356#endif
3357
3358 InputTarget target;
3359 sp<InputWindowHandle> windowHandle =
3360 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3361 if (windowHandle != nullptr) {
3362 const InputWindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003363 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003364 target.globalScaleFactor = windowInfo->globalScaleFactor;
3365 }
3366 target.inputChannel = connection->inputChannel;
3367 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3368
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003369 for (std::unique_ptr<EventEntry>& downEventEntry : downEvents) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003370 switch (downEventEntry->type) {
3371 case EventEntry::Type::MOTION: {
3372 logOutboundMotionDetails("down - ",
3373 static_cast<const MotionEntry&>(*downEventEntry));
3374 break;
3375 }
3376
3377 case EventEntry::Type::KEY:
3378 case EventEntry::Type::FOCUS:
3379 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08003380 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07003381 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3382 case EventEntry::Type::SENSOR: {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003383 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Chris Yef59a2f42020-10-16 12:55:26 -07003384 NamedEnum::string(downEventEntry->type).c_str());
Svet Ganov5d3bc372020-01-26 23:11:07 -08003385 break;
3386 }
3387 }
3388
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003389 enqueueDispatchEntryLocked(connection, std::move(downEventEntry), target,
3390 InputTarget::FLAG_DISPATCH_AS_IS);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003391 }
3392
3393 startDispatchCycleLocked(currentTime, connection);
3394}
3395
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003396std::unique_ptr<MotionEntry> InputDispatcher::splitMotionEvent(
3397 const MotionEntry& originalMotionEntry, BitSet32 pointerIds) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003398 ALOG_ASSERT(pointerIds.value != 0);
3399
3400 uint32_t splitPointerIndexMap[MAX_POINTERS];
3401 PointerProperties splitPointerProperties[MAX_POINTERS];
3402 PointerCoords splitPointerCoords[MAX_POINTERS];
3403
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003404 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003405 uint32_t splitPointerCount = 0;
3406
3407 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003408 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003409 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003410 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003411 uint32_t pointerId = uint32_t(pointerProperties.id);
3412 if (pointerIds.hasBit(pointerId)) {
3413 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
3414 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
3415 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003416 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003417 splitPointerCount += 1;
3418 }
3419 }
3420
3421 if (splitPointerCount != pointerIds.count()) {
3422 // This is bad. We are missing some of the pointers that we expected to deliver.
3423 // Most likely this indicates that we received an ACTION_MOVE events that has
3424 // different pointer ids than we expected based on the previous ACTION_DOWN
3425 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
3426 // in this way.
3427 ALOGW("Dropping split motion event because the pointer count is %d but "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003428 "we expected there to be %d pointers. This probably means we received "
3429 "a broken sequence of pointer ids from the input device.",
3430 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07003431 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003432 }
3433
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003434 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003435 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003436 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
3437 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003438 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
3439 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003440 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003441 uint32_t pointerId = uint32_t(pointerProperties.id);
3442 if (pointerIds.hasBit(pointerId)) {
3443 if (pointerIds.count() == 1) {
3444 // The first/last pointer went down/up.
3445 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003446 ? AMOTION_EVENT_ACTION_DOWN
arthurhungea3f4fc2020-12-21 23:18:53 +08003447 : (originalMotionEntry.flags & AMOTION_EVENT_FLAG_CANCELED) != 0
3448 ? AMOTION_EVENT_ACTION_CANCEL
3449 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003450 } else {
3451 // A secondary pointer went down/up.
3452 uint32_t splitPointerIndex = 0;
3453 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
3454 splitPointerIndex += 1;
3455 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003456 action = maskedAction |
3457 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003458 }
3459 } else {
3460 // An unrelated pointer changed.
3461 action = AMOTION_EVENT_ACTION_MOVE;
3462 }
3463 }
3464
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003465 int32_t newId = mIdGenerator.nextId();
3466 if (ATRACE_ENABLED()) {
3467 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
3468 ") to MotionEvent(id=0x%" PRIx32 ").",
3469 originalMotionEntry.id, newId);
3470 ATRACE_NAME(message.c_str());
3471 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003472 std::unique_ptr<MotionEntry> splitMotionEntry =
3473 std::make_unique<MotionEntry>(newId, originalMotionEntry.eventTime,
3474 originalMotionEntry.deviceId, originalMotionEntry.source,
3475 originalMotionEntry.displayId,
3476 originalMotionEntry.policyFlags, action,
3477 originalMotionEntry.actionButton,
3478 originalMotionEntry.flags, originalMotionEntry.metaState,
3479 originalMotionEntry.buttonState,
3480 originalMotionEntry.classification,
3481 originalMotionEntry.edgeFlags,
3482 originalMotionEntry.xPrecision,
3483 originalMotionEntry.yPrecision,
3484 originalMotionEntry.xCursorPosition,
3485 originalMotionEntry.yCursorPosition,
3486 originalMotionEntry.downTime, splitPointerCount,
3487 splitPointerProperties, splitPointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003488
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003489 if (originalMotionEntry.injectionState) {
3490 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003491 splitMotionEntry->injectionState->refCount += 1;
3492 }
3493
3494 return splitMotionEntry;
3495}
3496
3497void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
3498#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003499 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003500#endif
3501
3502 bool needWake;
3503 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003504 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003505
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003506 std::unique_ptr<ConfigurationChangedEntry> newEntry =
3507 std::make_unique<ConfigurationChangedEntry>(args->id, args->eventTime);
3508 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003509 } // release lock
3510
3511 if (needWake) {
3512 mLooper->wake();
3513 }
3514}
3515
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003516/**
3517 * If one of the meta shortcuts is detected, process them here:
3518 * Meta + Backspace -> generate BACK
3519 * Meta + Enter -> generate HOME
3520 * This will potentially overwrite keyCode and metaState.
3521 */
3522void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003523 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003524 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
3525 int32_t newKeyCode = AKEYCODE_UNKNOWN;
3526 if (keyCode == AKEYCODE_DEL) {
3527 newKeyCode = AKEYCODE_BACK;
3528 } else if (keyCode == AKEYCODE_ENTER) {
3529 newKeyCode = AKEYCODE_HOME;
3530 }
3531 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003532 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003533 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003534 mReplacedKeys[replacement] = newKeyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003535 keyCode = newKeyCode;
3536 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3537 }
3538 } else if (action == AKEY_EVENT_ACTION_UP) {
3539 // In order to maintain a consistent stream of up and down events, check to see if the key
3540 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
3541 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003542 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003543 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003544 auto replacementIt = mReplacedKeys.find(replacement);
3545 if (replacementIt != mReplacedKeys.end()) {
3546 keyCode = replacementIt->second;
3547 mReplacedKeys.erase(replacementIt);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003548 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3549 }
3550 }
3551}
3552
Michael Wrightd02c5b62014-02-10 15:10:22 -08003553void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
3554#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003555 ALOGD("notifyKey - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
3556 "policyFlags=0x%x, action=0x%x, "
3557 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
3558 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
3559 args->action, args->flags, args->keyCode, args->scanCode, args->metaState,
3560 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003561#endif
3562 if (!validateKeyEvent(args->action)) {
3563 return;
3564 }
3565
3566 uint32_t policyFlags = args->policyFlags;
3567 int32_t flags = args->flags;
3568 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07003569 // InputDispatcher tracks and generates key repeats on behalf of
3570 // whatever notifies it, so repeatCount should always be set to 0
3571 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003572 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
3573 policyFlags |= POLICY_FLAG_VIRTUAL;
3574 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
3575 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003576 if (policyFlags & POLICY_FLAG_FUNCTION) {
3577 metaState |= AMETA_FUNCTION_ON;
3578 }
3579
3580 policyFlags |= POLICY_FLAG_TRUSTED;
3581
Michael Wright78f24442014-08-06 15:55:28 -07003582 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003583 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07003584
Michael Wrightd02c5b62014-02-10 15:10:22 -08003585 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003586 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08003587 args->action, flags, keyCode, args->scanCode, metaState, repeatCount,
3588 args->downTime, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003589
Michael Wright2b3c3302018-03-02 17:19:13 +00003590 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003591 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003592 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3593 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003594 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003595 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003596
Michael Wrightd02c5b62014-02-10 15:10:22 -08003597 bool needWake;
3598 { // acquire lock
3599 mLock.lock();
3600
3601 if (shouldSendKeyToInputFilterLocked(args)) {
3602 mLock.unlock();
3603
3604 policyFlags |= POLICY_FLAG_FILTERED;
3605 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3606 return; // event was consumed by the filter
3607 }
3608
3609 mLock.lock();
3610 }
3611
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003612 std::unique_ptr<KeyEntry> newEntry =
3613 std::make_unique<KeyEntry>(args->id, args->eventTime, args->deviceId, args->source,
3614 args->displayId, policyFlags, args->action, flags,
3615 keyCode, args->scanCode, metaState, repeatCount,
3616 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003617
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003618 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003619 mLock.unlock();
3620 } // release lock
3621
3622 if (needWake) {
3623 mLooper->wake();
3624 }
3625}
3626
3627bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
3628 return mInputFilterEnabled;
3629}
3630
3631void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
3632#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003633 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
3634 "displayId=%" PRId32 ", policyFlags=0x%x, "
Garfield Tan00f511d2019-06-12 16:55:40 -07003635 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
3636 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
Garfield Tanab0ab9c2019-07-10 18:58:28 -07003637 "yCursorPosition=%f, downTime=%" PRId64,
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003638 args->id, args->eventTime, args->deviceId, args->source, args->displayId,
3639 args->policyFlags, args->action, args->actionButton, args->flags, args->metaState,
3640 args->buttonState, args->edgeFlags, args->xPrecision, args->yPrecision,
3641 args->xCursorPosition, args->yCursorPosition, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003642 for (uint32_t i = 0; i < args->pointerCount; i++) {
3643 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003644 "x=%f, y=%f, pressure=%f, size=%f, "
3645 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
3646 "orientation=%f",
3647 i, args->pointerProperties[i].id, args->pointerProperties[i].toolType,
3648 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
3649 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
3650 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
3651 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
3652 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
3653 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
3654 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
3655 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
3656 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003657 }
3658#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003659 if (!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
3660 args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003661 return;
3662 }
3663
3664 uint32_t policyFlags = args->policyFlags;
3665 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003666
3667 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08003668 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003669 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3670 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003671 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003672 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003673
3674 bool needWake;
3675 { // acquire lock
3676 mLock.lock();
3677
3678 if (shouldSendMotionToInputFilterLocked(args)) {
3679 mLock.unlock();
3680
3681 MotionEvent event;
chaviw9eaa22c2020-07-01 16:21:27 -07003682 ui::Transform transform;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003683 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
3684 args->action, args->actionButton, args->flags, args->edgeFlags,
chaviw9eaa22c2020-07-01 16:21:27 -07003685 args->metaState, args->buttonState, args->classification, transform,
3686 args->xPrecision, args->yPrecision, args->xCursorPosition,
3687 args->yCursorPosition, args->downTime, args->eventTime,
3688 args->pointerCount, args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003689
3690 policyFlags |= POLICY_FLAG_FILTERED;
3691 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3692 return; // event was consumed by the filter
3693 }
3694
3695 mLock.lock();
3696 }
3697
3698 // Just enqueue a new motion event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003699 std::unique_ptr<MotionEntry> newEntry =
3700 std::make_unique<MotionEntry>(args->id, args->eventTime, args->deviceId,
3701 args->source, args->displayId, policyFlags,
3702 args->action, args->actionButton, args->flags,
3703 args->metaState, args->buttonState,
3704 args->classification, args->edgeFlags,
3705 args->xPrecision, args->yPrecision,
3706 args->xCursorPosition, args->yCursorPosition,
3707 args->downTime, args->pointerCount,
3708 args->pointerProperties, args->pointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003709
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003710 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003711 mLock.unlock();
3712 } // release lock
3713
3714 if (needWake) {
3715 mLooper->wake();
3716 }
3717}
3718
Chris Yef59a2f42020-10-16 12:55:26 -07003719void InputDispatcher::notifySensor(const NotifySensorArgs* args) {
3720#if DEBUG_INBOUND_EVENT_DETAILS
3721 ALOGD("notifySensor - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
3722 " sensorType=%s",
3723 args->id, args->eventTime, args->deviceId, args->source,
3724 NamedEnum::string(args->sensorType).c_str());
3725#endif
3726
3727 bool needWake;
3728 { // acquire lock
3729 mLock.lock();
3730
3731 // Just enqueue a new sensor event.
3732 std::unique_ptr<SensorEntry> newEntry =
3733 std::make_unique<SensorEntry>(args->id, args->eventTime, args->deviceId,
3734 args->source, 0 /* policyFlags*/, args->hwTimestamp,
3735 args->sensorType, args->accuracy,
3736 args->accuracyChanged, args->values);
3737
3738 needWake = enqueueInboundEventLocked(std::move(newEntry));
3739 mLock.unlock();
3740 } // release lock
3741
3742 if (needWake) {
3743 mLooper->wake();
3744 }
3745}
3746
Chris Yefb552902021-02-03 17:18:37 -08003747void InputDispatcher::notifyVibratorState(const NotifyVibratorStateArgs* args) {
3748#if DEBUG_INBOUND_EVENT_DETAILS
3749 ALOGD("notifyVibratorState - eventTime=%" PRId64 ", device=%d, isOn=%d", args->eventTime,
3750 args->deviceId, args->isOn);
3751#endif
3752 mPolicy->notifyVibratorState(args->deviceId, args->isOn);
3753}
3754
Michael Wrightd02c5b62014-02-10 15:10:22 -08003755bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08003756 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003757}
3758
3759void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
3760#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003761 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003762 "switchMask=0x%08x",
3763 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003764#endif
3765
3766 uint32_t policyFlags = args->policyFlags;
3767 policyFlags |= POLICY_FLAG_TRUSTED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003768 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003769}
3770
3771void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
3772#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003773 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
3774 args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003775#endif
3776
3777 bool needWake;
3778 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003779 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003780
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003781 std::unique_ptr<DeviceResetEntry> newEntry =
3782 std::make_unique<DeviceResetEntry>(args->id, args->eventTime, args->deviceId);
3783 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003784 } // release lock
3785
3786 if (needWake) {
3787 mLooper->wake();
3788 }
3789}
3790
Prabir Pradhan7e186182020-11-10 13:56:45 -08003791void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs* args) {
3792#if DEBUG_INBOUND_EVENT_DETAILS
3793 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args->eventTime,
3794 args->enabled ? "true" : "false");
3795#endif
3796
Prabir Pradhan99987712020-11-10 18:43:05 -08003797 bool needWake;
3798 { // acquire lock
3799 std::scoped_lock _l(mLock);
3800 auto entry = std::make_unique<PointerCaptureChangedEntry>(args->id, args->eventTime,
3801 args->enabled);
3802 needWake = enqueueInboundEventLocked(std::move(entry));
3803 } // release lock
3804
3805 if (needWake) {
3806 mLooper->wake();
3807 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08003808}
3809
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003810InputEventInjectionResult InputDispatcher::injectInputEvent(
3811 const InputEvent* event, int32_t injectorPid, int32_t injectorUid,
3812 InputEventInjectionSync syncMode, std::chrono::milliseconds timeout, uint32_t policyFlags) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003813#if DEBUG_INBOUND_EVENT_DETAILS
3814 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003815 "syncMode=%d, timeout=%lld, policyFlags=0x%08x",
3816 event->getType(), injectorPid, injectorUid, syncMode, timeout.count(), policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003817#endif
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003818 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003819
3820 policyFlags |= POLICY_FLAG_INJECTED;
3821 if (hasInjectionPermission(injectorPid, injectorUid)) {
3822 policyFlags |= POLICY_FLAG_TRUSTED;
3823 }
3824
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003825 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003826 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003827 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003828 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
3829 int32_t action = incomingKey.getAction();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003830 if (!validateKeyEvent(action)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003831 return InputEventInjectionResult::FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003832 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003833
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003834 int32_t flags = incomingKey.getFlags();
3835 int32_t keyCode = incomingKey.getKeyCode();
3836 int32_t metaState = incomingKey.getMetaState();
3837 accelerateMetaShortcuts(VIRTUAL_KEYBOARD_ID, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003838 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003839 KeyEvent keyEvent;
Garfield Tan4cc839f2020-01-24 11:26:14 -08003840 keyEvent.initialize(incomingKey.getId(), VIRTUAL_KEYBOARD_ID, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003841 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
3842 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
3843 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003844
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003845 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
3846 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00003847 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003848
3849 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
3850 android::base::Timer t;
3851 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
3852 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3853 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
3854 std::to_string(t.duration().count()).c_str());
3855 }
3856 }
3857
3858 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003859 std::unique_ptr<KeyEntry> injectedEntry =
3860 std::make_unique<KeyEntry>(incomingKey.getId(), incomingKey.getEventTime(),
3861 VIRTUAL_KEYBOARD_ID, incomingKey.getSource(),
3862 incomingKey.getDisplayId(), policyFlags, action,
3863 flags, keyCode, incomingKey.getScanCode(), metaState,
3864 incomingKey.getRepeatCount(),
3865 incomingKey.getDownTime());
3866 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003867 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003868 }
3869
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003870 case AINPUT_EVENT_TYPE_MOTION: {
3871 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
3872 int32_t action = motionEvent->getAction();
3873 size_t pointerCount = motionEvent->getPointerCount();
3874 const PointerProperties* pointerProperties = motionEvent->getPointerProperties();
3875 int32_t actionButton = motionEvent->getActionButton();
3876 int32_t displayId = motionEvent->getDisplayId();
3877 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003878 return InputEventInjectionResult::FAILED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003879 }
3880
3881 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
3882 nsecs_t eventTime = motionEvent->getEventTime();
3883 android::base::Timer t;
3884 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
3885 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3886 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
3887 std::to_string(t.duration().count()).c_str());
3888 }
3889 }
3890
3891 mLock.lock();
3892 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
3893 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003894 std::unique_ptr<MotionEntry> injectedEntry =
3895 std::make_unique<MotionEntry>(motionEvent->getId(), *sampleEventTimes,
3896 VIRTUAL_KEYBOARD_ID, motionEvent->getSource(),
3897 motionEvent->getDisplayId(), policyFlags, action,
3898 actionButton, motionEvent->getFlags(),
3899 motionEvent->getMetaState(),
3900 motionEvent->getButtonState(),
3901 motionEvent->getClassification(),
3902 motionEvent->getEdgeFlags(),
3903 motionEvent->getXPrecision(),
3904 motionEvent->getYPrecision(),
3905 motionEvent->getRawXCursorPosition(),
3906 motionEvent->getRawYCursorPosition(),
3907 motionEvent->getDownTime(),
3908 uint32_t(pointerCount), pointerProperties,
3909 samplePointerCoords, motionEvent->getXOffset(),
3910 motionEvent->getYOffset());
3911 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003912 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
3913 sampleEventTimes += 1;
3914 samplePointerCoords += pointerCount;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003915 std::unique_ptr<MotionEntry> nextInjectedEntry =
3916 std::make_unique<MotionEntry>(motionEvent->getId(), *sampleEventTimes,
3917 VIRTUAL_KEYBOARD_ID, motionEvent->getSource(),
3918 motionEvent->getDisplayId(), policyFlags,
3919 action, actionButton, motionEvent->getFlags(),
3920 motionEvent->getMetaState(),
3921 motionEvent->getButtonState(),
3922 motionEvent->getClassification(),
3923 motionEvent->getEdgeFlags(),
3924 motionEvent->getXPrecision(),
3925 motionEvent->getYPrecision(),
3926 motionEvent->getRawXCursorPosition(),
3927 motionEvent->getRawYCursorPosition(),
3928 motionEvent->getDownTime(),
3929 uint32_t(pointerCount), pointerProperties,
3930 samplePointerCoords,
3931 motionEvent->getXOffset(),
3932 motionEvent->getYOffset());
3933 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003934 }
3935 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003936 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003937
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003938 default:
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08003939 ALOGW("Cannot inject %s events", inputEventTypeToString(event->getType()));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003940 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003941 }
3942
3943 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003944 if (syncMode == InputEventInjectionSync::NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003945 injectionState->injectionIsAsync = true;
3946 }
3947
3948 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003949 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003950
3951 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003952 while (!injectedEntries.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003953 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003954 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003955 }
3956
3957 mLock.unlock();
3958
3959 if (needWake) {
3960 mLooper->wake();
3961 }
3962
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003963 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003964 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003965 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003966
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003967 if (syncMode == InputEventInjectionSync::NONE) {
3968 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003969 } else {
3970 for (;;) {
3971 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003972 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003973 break;
3974 }
3975
3976 nsecs_t remainingTimeout = endTime - now();
3977 if (remainingTimeout <= 0) {
3978#if DEBUG_INJECTION
3979 ALOGD("injectInputEvent - Timed out waiting for injection result "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003980 "to become available.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003981#endif
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003982 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003983 break;
3984 }
3985
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003986 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003987 }
3988
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003989 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
3990 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003991 while (injectionState->pendingForegroundDispatches != 0) {
3992#if DEBUG_INJECTION
3993 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003994 injectionState->pendingForegroundDispatches);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003995#endif
3996 nsecs_t remainingTimeout = endTime - now();
3997 if (remainingTimeout <= 0) {
3998#if DEBUG_INJECTION
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003999 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
4000 "dispatches to finish.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004001#endif
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004002 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004003 break;
4004 }
4005
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004006 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004007 }
4008 }
4009 }
4010
4011 injectionState->release();
4012 } // release lock
4013
4014#if DEBUG_INJECTION
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004015 ALOGD("injectInputEvent - Finished with result %d. injectorPid=%d, injectorUid=%d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004016 injectionResult, injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004017#endif
4018
4019 return injectionResult;
4020}
4021
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004022std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05004023 std::array<uint8_t, 32> calculatedHmac;
4024 std::unique_ptr<VerifiedInputEvent> result;
4025 switch (event.getType()) {
4026 case AINPUT_EVENT_TYPE_KEY: {
4027 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
4028 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
4029 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004030 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05004031 break;
4032 }
4033 case AINPUT_EVENT_TYPE_MOTION: {
4034 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
4035 VerifiedMotionEvent verifiedMotionEvent =
4036 verifiedMotionEventFromMotionEvent(motionEvent);
4037 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004038 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05004039 break;
4040 }
4041 default: {
4042 ALOGE("Cannot verify events of type %" PRId32, event.getType());
4043 return nullptr;
4044 }
4045 }
4046 if (calculatedHmac == INVALID_HMAC) {
4047 return nullptr;
4048 }
4049 if (calculatedHmac != event.getHmac()) {
4050 return nullptr;
4051 }
4052 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004053}
4054
Michael Wrightd02c5b62014-02-10 15:10:22 -08004055bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004056 return injectorUid == 0 ||
4057 mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004058}
4059
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004060void InputDispatcher::setInjectionResult(EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004061 InputEventInjectionResult injectionResult) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004062 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004063 if (injectionState) {
4064#if DEBUG_INJECTION
4065 ALOGD("Setting input event injection result to %d. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004066 "injectorPid=%d, injectorUid=%d",
4067 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004068#endif
4069
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004070 if (injectionState->injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004071 // Log the outcome since the injector did not wait for the injection result.
4072 switch (injectionResult) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004073 case InputEventInjectionResult::SUCCEEDED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004074 ALOGV("Asynchronous input event injection succeeded.");
4075 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004076 case InputEventInjectionResult::FAILED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004077 ALOGW("Asynchronous input event injection failed.");
4078 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004079 case InputEventInjectionResult::PERMISSION_DENIED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004080 ALOGW("Asynchronous input event injection permission denied.");
4081 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004082 case InputEventInjectionResult::TIMED_OUT:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004083 ALOGW("Asynchronous input event injection timed out.");
4084 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004085 case InputEventInjectionResult::PENDING:
4086 ALOGE("Setting result to 'PENDING' for asynchronous injection");
4087 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004088 }
4089 }
4090
4091 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004092 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004093 }
4094}
4095
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004096void InputDispatcher::incrementPendingForegroundDispatches(EventEntry& entry) {
4097 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004098 if (injectionState) {
4099 injectionState->pendingForegroundDispatches += 1;
4100 }
4101}
4102
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004103void InputDispatcher::decrementPendingForegroundDispatches(EventEntry& entry) {
4104 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004105 if (injectionState) {
4106 injectionState->pendingForegroundDispatches -= 1;
4107
4108 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004109 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004110 }
4111 }
4112}
4113
Vishnu Nairad321cd2020-08-20 16:40:21 -07004114const std::vector<sp<InputWindowHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004115 int32_t displayId) const {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004116 static const std::vector<sp<InputWindowHandle>> EMPTY_WINDOW_HANDLES;
4117 auto it = mWindowHandlesByDisplay.find(displayId);
4118 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08004119}
4120
Michael Wrightd02c5b62014-02-10 15:10:22 -08004121sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08004122 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08004123 if (windowHandleToken == nullptr) {
4124 return nullptr;
4125 }
4126
Arthur Hungb92218b2018-08-14 12:00:21 +08004127 for (auto& it : mWindowHandlesByDisplay) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004128 const std::vector<sp<InputWindowHandle>>& windowHandles = it.second;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004129 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004130 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004131 return windowHandle;
4132 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004133 }
4134 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004135 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004136}
4137
Vishnu Nairad321cd2020-08-20 16:40:21 -07004138sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(const sp<IBinder>& windowHandleToken,
4139 int displayId) const {
4140 if (windowHandleToken == nullptr) {
4141 return nullptr;
4142 }
4143
4144 for (const sp<InputWindowHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
4145 if (windowHandle->getToken() == windowHandleToken) {
4146 return windowHandle;
4147 }
4148 }
4149 return nullptr;
4150}
4151
4152sp<InputWindowHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
Vishnu Nairc519ff72021-01-21 08:23:08 -08004153 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(displayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07004154 return getWindowHandleLocked(focusedToken, displayId);
4155}
4156
Mady Mellor017bcd12020-06-23 19:12:00 +00004157bool InputDispatcher::hasWindowHandleLocked(const sp<InputWindowHandle>& windowHandle) const {
4158 for (auto& it : mWindowHandlesByDisplay) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004159 const std::vector<sp<InputWindowHandle>>& windowHandles = it.second;
Mady Mellor017bcd12020-06-23 19:12:00 +00004160 for (const sp<InputWindowHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08004161 if (handle->getId() == windowHandle->getId() &&
4162 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004163 if (windowHandle->getInfo()->displayId != it.first) {
4164 ALOGE("Found window %s in display %" PRId32
4165 ", but it should belong to display %" PRId32,
4166 windowHandle->getName().c_str(), it.first,
4167 windowHandle->getInfo()->displayId);
4168 }
4169 return true;
Arthur Hungb92218b2018-08-14 12:00:21 +08004170 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004171 }
4172 }
4173 return false;
4174}
4175
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004176bool InputDispatcher::hasResponsiveConnectionLocked(InputWindowHandle& windowHandle) const {
4177 sp<Connection> connection = getConnectionLocked(windowHandle.getToken());
4178 const bool noInputChannel =
4179 windowHandle.getInfo()->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
4180 if (connection != nullptr && noInputChannel) {
4181 ALOGW("%s has feature NO_INPUT_CHANNEL, but it matched to connection %s",
4182 windowHandle.getName().c_str(), connection->inputChannel->getName().c_str());
4183 return false;
4184 }
4185
4186 if (connection == nullptr) {
4187 if (!noInputChannel) {
4188 ALOGI("Could not find connection for %s", windowHandle.getName().c_str());
4189 }
4190 return false;
4191 }
4192 if (!connection->responsive) {
4193 ALOGW("Window %s is not responsive", windowHandle.getName().c_str());
4194 return false;
4195 }
4196 return true;
4197}
4198
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004199std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
4200 const sp<IBinder>& token) const {
Robert Carr5c8a0262018-10-03 16:30:44 -07004201 size_t count = mInputChannelsByToken.count(token);
4202 if (count == 0) {
4203 return nullptr;
4204 }
4205 return mInputChannelsByToken.at(token);
4206}
4207
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004208void InputDispatcher::updateWindowHandlesForDisplayLocked(
4209 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
4210 if (inputWindowHandles.empty()) {
4211 // Remove all handles on a display if there are no windows left.
4212 mWindowHandlesByDisplay.erase(displayId);
4213 return;
4214 }
4215
4216 // Since we compare the pointer of input window handles across window updates, we need
4217 // to make sure the handle object for the same window stays unchanged across updates.
4218 const std::vector<sp<InputWindowHandle>>& oldHandles = getWindowHandlesLocked(displayId);
chaviwaf87b3e2019-10-01 16:59:28 -07004219 std::unordered_map<int32_t /*id*/, sp<InputWindowHandle>> oldHandlesById;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004220 for (const sp<InputWindowHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07004221 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004222 }
4223
4224 std::vector<sp<InputWindowHandle>> newHandles;
4225 for (const sp<InputWindowHandle>& handle : inputWindowHandles) {
4226 if (!handle->updateInfo()) {
4227 // handle no longer valid
4228 continue;
4229 }
4230
4231 const InputWindowInfo* info = handle->getInfo();
4232 if ((getInputChannelLocked(handle->getToken()) == nullptr &&
4233 info->portalToDisplayId == ADISPLAY_ID_NONE)) {
4234 const bool noInputChannel =
Michael Wright44753b12020-07-08 13:48:11 +01004235 info->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
4236 const bool canReceiveInput = !info->flags.test(InputWindowInfo::Flag::NOT_TOUCHABLE) ||
4237 !info->flags.test(InputWindowInfo::Flag::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004238 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07004239 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004240 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07004241 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004242 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004243 }
4244
4245 if (info->displayId != displayId) {
4246 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
4247 handle->getName().c_str(), displayId, info->displayId);
4248 continue;
4249 }
4250
Robert Carredd13602020-04-13 17:24:34 -07004251 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
4252 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviwaf87b3e2019-10-01 16:59:28 -07004253 const sp<InputWindowHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004254 oldHandle->updateFrom(handle);
4255 newHandles.push_back(oldHandle);
4256 } else {
4257 newHandles.push_back(handle);
4258 }
4259 }
4260
4261 // Insert or replace
4262 mWindowHandlesByDisplay[displayId] = newHandles;
4263}
4264
Arthur Hung72d8dc32020-03-28 00:48:39 +00004265void InputDispatcher::setInputWindows(
4266 const std::unordered_map<int32_t, std::vector<sp<InputWindowHandle>>>& handlesPerDisplay) {
4267 { // acquire lock
4268 std::scoped_lock _l(mLock);
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004269 for (const auto& [displayId, handles] : handlesPerDisplay) {
4270 setInputWindowsLocked(handles, displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004271 }
4272 }
4273 // Wake up poll loop since it may need to make new input dispatching choices.
4274 mLooper->wake();
4275}
4276
Arthur Hungb92218b2018-08-14 12:00:21 +08004277/**
4278 * Called from InputManagerService, update window handle list by displayId that can receive input.
4279 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
4280 * If set an empty list, remove all handles from the specific display.
4281 * For focused handle, check if need to change and send a cancel event to previous one.
4282 * For removed handle, check if need to send a cancel event if already in touch.
4283 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00004284void InputDispatcher::setInputWindowsLocked(
4285 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004286 if (DEBUG_FOCUS) {
4287 std::string windowList;
4288 for (const sp<InputWindowHandle>& iwh : inputWindowHandles) {
4289 windowList += iwh->getName() + " ";
4290 }
4291 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
4292 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004293
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004294 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
4295 for (const sp<InputWindowHandle>& window : inputWindowHandles) {
4296 const bool noInputWindow =
4297 window->getInfo()->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
4298 if (noInputWindow && window->getToken() != nullptr) {
4299 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
4300 window->getName().c_str());
4301 window->releaseChannel();
4302 }
4303 }
4304
Arthur Hung72d8dc32020-03-28 00:48:39 +00004305 // Copy old handles for release if they are no longer present.
4306 const std::vector<sp<InputWindowHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004307
Arthur Hung72d8dc32020-03-28 00:48:39 +00004308 updateWindowHandlesForDisplayLocked(inputWindowHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004309
Vishnu Nair958da932020-08-21 17:12:37 -07004310 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
4311 if (mLastHoverWindowHandle &&
4312 std::find(windowHandles.begin(), windowHandles.end(), mLastHoverWindowHandle) ==
4313 windowHandles.end()) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004314 mLastHoverWindowHandle = nullptr;
4315 }
4316
Vishnu Nairc519ff72021-01-21 08:23:08 -08004317 std::optional<FocusResolver::FocusChanges> changes =
4318 mFocusResolver.setInputWindows(displayId, windowHandles);
4319 if (changes) {
4320 onFocusChangedLocked(*changes);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004321 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004322
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004323 std::unordered_map<int32_t, TouchState>::iterator stateIt =
4324 mTouchStatesByDisplay.find(displayId);
4325 if (stateIt != mTouchStatesByDisplay.end()) {
4326 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00004327 for (size_t i = 0; i < state.windows.size();) {
4328 TouchedWindow& touchedWindow = state.windows[i];
Mady Mellor017bcd12020-06-23 19:12:00 +00004329 if (!hasWindowHandleLocked(touchedWindow.windowHandle)) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004330 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004331 ALOGD("Touched window was removed: %s in display %" PRId32,
4332 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004333 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004334 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00004335 getInputChannelLocked(touchedWindow.windowHandle->getToken());
4336 if (touchedInputChannel != nullptr) {
4337 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4338 "touched window was removed");
4339 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004340 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004341 state.windows.erase(state.windows.begin() + i);
4342 } else {
4343 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004344 }
4345 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004346 }
Arthur Hung25e2af12020-03-26 12:58:37 +00004347
Arthur Hung72d8dc32020-03-28 00:48:39 +00004348 // Release information for windows that are no longer present.
4349 // This ensures that unused input channels are released promptly.
4350 // Otherwise, they might stick around until the window handle is destroyed
4351 // which might not happen until the next GC.
4352 for (const sp<InputWindowHandle>& oldWindowHandle : oldWindowHandles) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004353 if (!hasWindowHandleLocked(oldWindowHandle)) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004354 if (DEBUG_FOCUS) {
4355 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00004356 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004357 oldWindowHandle->releaseChannel();
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004358 // To avoid making too many calls into the compat framework, only
4359 // check for window flags when windows are going away.
4360 // TODO(b/157929241) : delete this. This is only needed temporarily
4361 // in order to gather some data about the flag usage
4362 if (oldWindowHandle->getInfo()->flags.test(InputWindowInfo::Flag::SLIPPERY)) {
4363 ALOGW("%s has FLAG_SLIPPERY. Please report this in b/157929241",
4364 oldWindowHandle->getName().c_str());
4365 if (mCompatService != nullptr) {
4366 mCompatService->reportChangeByUid(IInputConstants::BLOCK_FLAG_SLIPPERY,
4367 oldWindowHandle->getInfo()->ownerUid);
4368 }
4369 }
Arthur Hung25e2af12020-03-26 12:58:37 +00004370 }
chaviw291d88a2019-02-14 10:33:58 -08004371 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004372}
4373
4374void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07004375 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004376 if (DEBUG_FOCUS) {
4377 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
4378 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
4379 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004380 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004381 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004382
Chris Yea209fde2020-07-22 13:54:51 -07004383 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08004384 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004385
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004386 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
4387 return; // This application is already focused. No need to wake up or change anything.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004388 }
4389
Chris Yea209fde2020-07-22 13:54:51 -07004390 // Set the new application handle.
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004391 if (inputApplicationHandle != nullptr) {
4392 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
4393 } else {
4394 mFocusedApplicationHandlesByDisplay.erase(displayId);
4395 }
4396
4397 // No matter what the old focused application was, stop waiting on it because it is
4398 // no longer focused.
4399 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004400 } // release lock
4401
4402 // Wake up poll loop since it may need to make new input dispatching choices.
4403 mLooper->wake();
4404}
4405
Tiger Huang721e26f2018-07-24 22:26:19 +08004406/**
4407 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
4408 * the display not specified.
4409 *
4410 * We track any unreleased events for each window. If a window loses the ability to receive the
4411 * released event, we will send a cancel event to it. So when the focused display is changed, we
4412 * cancel all the unreleased display-unspecified events for the focused window on the old focused
4413 * display. The display-specified events won't be affected.
4414 */
4415void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004416 if (DEBUG_FOCUS) {
4417 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
4418 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004419 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004420 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08004421
4422 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004423 sp<IBinder> oldFocusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08004424 mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07004425 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004426 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07004427 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08004428 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004429 CancelationOptions
4430 options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
4431 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004432 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08004433 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
4434 }
4435 }
4436 mFocusedDisplayId = displayId;
4437
Chris Ye3c2d6f52020-08-09 10:39:48 -07004438 // Find new focused window and validate
Vishnu Nairc519ff72021-01-21 08:23:08 -08004439 sp<IBinder> newFocusedWindowToken = mFocusResolver.getFocusedWindowToken(displayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07004440 notifyFocusChangedLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08004441
Vishnu Nairad321cd2020-08-20 16:40:21 -07004442 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08004443 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairc519ff72021-01-21 08:23:08 -08004444 if (mFocusResolver.hasFocusedWindowTokens()) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004445 ALOGE("But another display has a focused window\n%s",
Vishnu Nairc519ff72021-01-21 08:23:08 -08004446 mFocusResolver.dumpFocusedWindows().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08004447 }
4448 }
4449 }
4450
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004451 if (DEBUG_FOCUS) {
4452 logDispatchStateLocked();
4453 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004454 } // release lock
4455
4456 // Wake up poll loop since it may need to make new input dispatching choices.
4457 mLooper->wake();
4458}
4459
Michael Wrightd02c5b62014-02-10 15:10:22 -08004460void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004461 if (DEBUG_FOCUS) {
4462 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
4463 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004464
4465 bool changed;
4466 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004467 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004468
4469 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
4470 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004471 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004472 }
4473
4474 if (mDispatchEnabled && !enabled) {
4475 resetAndDropEverythingLocked("dispatcher is being disabled");
4476 }
4477
4478 mDispatchEnabled = enabled;
4479 mDispatchFrozen = frozen;
4480 changed = true;
4481 } else {
4482 changed = false;
4483 }
4484
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004485 if (DEBUG_FOCUS) {
4486 logDispatchStateLocked();
4487 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004488 } // release lock
4489
4490 if (changed) {
4491 // Wake up poll loop since it may need to make new input dispatching choices.
4492 mLooper->wake();
4493 }
4494}
4495
4496void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004497 if (DEBUG_FOCUS) {
4498 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
4499 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004500
4501 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004502 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004503
4504 if (mInputFilterEnabled == enabled) {
4505 return;
4506 }
4507
4508 mInputFilterEnabled = enabled;
4509 resetAndDropEverythingLocked("input filter is being enabled or disabled");
4510 } // release lock
4511
4512 // Wake up poll loop since there might be work to do to drop everything.
4513 mLooper->wake();
4514}
4515
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08004516void InputDispatcher::setInTouchMode(bool inTouchMode) {
4517 std::scoped_lock lock(mLock);
4518 mInTouchMode = inTouchMode;
4519}
4520
Bernardo Rufinoea97d182020-08-19 14:43:14 +01004521void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
4522 if (opacity < 0 || opacity > 1) {
4523 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
4524 return;
4525 }
4526
4527 std::scoped_lock lock(mLock);
4528 mMaximumObscuringOpacityForTouch = opacity;
4529}
4530
4531void InputDispatcher::setBlockUntrustedTouchesMode(BlockUntrustedTouchesMode mode) {
4532 std::scoped_lock lock(mLock);
4533 mBlockUntrustedTouchesMode = mode;
4534}
4535
chaviwfbe5d9c2018-12-26 12:23:37 -08004536bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken) {
4537 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004538 if (DEBUG_FOCUS) {
4539 ALOGD("Trivial transfer to same window.");
4540 }
chaviwfbe5d9c2018-12-26 12:23:37 -08004541 return true;
4542 }
4543
Michael Wrightd02c5b62014-02-10 15:10:22 -08004544 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004545 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004546
chaviwfbe5d9c2018-12-26 12:23:37 -08004547 sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromToken);
4548 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toToken);
Yi Kong9b14ac62018-07-17 13:48:38 -07004549 if (fromWindowHandle == nullptr || toWindowHandle == nullptr) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004550 ALOGW("Cannot transfer focus because from or to window not found.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004551 return false;
4552 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004553 if (DEBUG_FOCUS) {
4554 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
4555 fromWindowHandle->getName().c_str(), toWindowHandle->getName().c_str());
4556 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004557 if (fromWindowHandle->getInfo()->displayId != toWindowHandle->getInfo()->displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004558 if (DEBUG_FOCUS) {
4559 ALOGD("Cannot transfer focus because windows are on different displays.");
4560 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004561 return false;
4562 }
4563
4564 bool found = false;
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004565 for (std::pair<const int32_t, TouchState>& pair : mTouchStatesByDisplay) {
4566 TouchState& state = pair.second;
Jeff Brownf086ddb2014-02-11 14:28:48 -08004567 for (size_t i = 0; i < state.windows.size(); i++) {
4568 const TouchedWindow& touchedWindow = state.windows[i];
4569 if (touchedWindow.windowHandle == fromWindowHandle) {
4570 int32_t oldTargetFlags = touchedWindow.targetFlags;
4571 BitSet32 pointerIds = touchedWindow.pointerIds;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004572
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004573 state.windows.erase(state.windows.begin() + i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004574
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004575 int32_t newTargetFlags = oldTargetFlags &
4576 (InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_SPLIT |
4577 InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004578 state.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004579
Jeff Brownf086ddb2014-02-11 14:28:48 -08004580 found = true;
4581 goto Found;
4582 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004583 }
4584 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004585 Found:
Michael Wrightd02c5b62014-02-10 15:10:22 -08004586
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004587 if (!found) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004588 if (DEBUG_FOCUS) {
4589 ALOGD("Focus transfer failed because from window did not have focus.");
4590 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004591 return false;
4592 }
4593
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004594 sp<Connection> fromConnection = getConnectionLocked(fromToken);
4595 sp<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004596 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004597 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004598 CancelationOptions
4599 options(CancelationOptions::CANCEL_POINTER_EVENTS,
4600 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004601 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004602 synthesizePointerDownEventsForConnectionLocked(toConnection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004603 }
4604
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004605 if (DEBUG_FOCUS) {
4606 logDispatchStateLocked();
4607 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004608 } // release lock
4609
4610 // Wake up poll loop since it may need to make new input dispatching choices.
4611 mLooper->wake();
4612 return true;
4613}
4614
4615void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004616 if (DEBUG_FOCUS) {
4617 ALOGD("Resetting and dropping all events (%s).", reason);
4618 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004619
4620 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
4621 synthesizeCancelationEventsForAllConnectionsLocked(options);
4622
4623 resetKeyRepeatLocked();
4624 releasePendingEventLocked();
4625 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004626 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004627
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004628 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08004629 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004630 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07004631 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004632}
4633
4634void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004635 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004636 dumpDispatchStateLocked(dump);
4637
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004638 std::istringstream stream(dump);
4639 std::string line;
4640
4641 while (std::getline(stream, line, '\n')) {
4642 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004643 }
4644}
4645
Prabir Pradhan99987712020-11-10 18:43:05 -08004646std::string InputDispatcher::dumpPointerCaptureStateLocked() {
4647 std::string dump;
4648
4649 dump += StringPrintf(INDENT "FocusedWindowRequestedPointerCapture: %s\n",
4650 toString(mFocusedWindowRequestedPointerCapture));
4651
4652 std::string windowName = "None";
4653 if (mWindowTokenWithPointerCapture) {
4654 const sp<InputWindowHandle> captureWindowHandle =
4655 getWindowHandleLocked(mWindowTokenWithPointerCapture);
4656 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
4657 : "token has capture without window";
4658 }
4659 dump += StringPrintf(INDENT "CurrentWindowWithPointerCapture: %s\n", windowName.c_str());
4660
4661 return dump;
4662}
4663
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004664void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07004665 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
4666 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
4667 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08004668 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004669
Tiger Huang721e26f2018-07-24 22:26:19 +08004670 if (!mFocusedApplicationHandlesByDisplay.empty()) {
4671 dump += StringPrintf(INDENT "FocusedApplications:\n");
4672 for (auto& it : mFocusedApplicationHandlesByDisplay) {
4673 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07004674 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05004675 const std::chrono::duration timeout =
4676 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004677 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004678 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05004679 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08004680 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004681 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08004682 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004683 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004684
Vishnu Nairc519ff72021-01-21 08:23:08 -08004685 dump += mFocusResolver.dump();
Prabir Pradhan99987712020-11-10 18:43:05 -08004686 dump += dumpPointerCaptureStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004687
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004688 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004689 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004690 for (const std::pair<int32_t, TouchState>& pair : mTouchStatesByDisplay) {
4691 const TouchState& state = pair.second;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004692 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004693 state.displayId, toString(state.down), toString(state.split),
4694 state.deviceId, state.source);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004695 if (!state.windows.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004696 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004697 for (size_t i = 0; i < state.windows.size(); i++) {
4698 const TouchedWindow& touchedWindow = state.windows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004699 dump += StringPrintf(INDENT4
4700 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
4701 i, touchedWindow.windowHandle->getName().c_str(),
4702 touchedWindow.pointerIds.value, touchedWindow.targetFlags);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004703 }
4704 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004705 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004706 }
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004707 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004708 dump += INDENT3 "Portal windows:\n";
4709 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004710 const sp<InputWindowHandle> portalWindowHandle = state.portalWindows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004711 dump += StringPrintf(INDENT4 "%zu: name='%s'\n", i,
4712 portalWindowHandle->getName().c_str());
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004713 }
4714 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004715 }
4716 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004717 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004718 }
4719
Arthur Hungb92218b2018-08-14 12:00:21 +08004720 if (!mWindowHandlesByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004721 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004722 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
Arthur Hung3b413f22018-10-26 18:05:34 +08004723 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", it.first);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004724 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004725 dump += INDENT2 "Windows:\n";
4726 for (size_t i = 0; i < windowHandles.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004727 const sp<InputWindowHandle>& windowHandle = windowHandles[i];
Arthur Hungb92218b2018-08-14 12:00:21 +08004728 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004729
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00004730 dump += StringPrintf(INDENT3 "%zu: name='%s', id=%" PRId32 ", displayId=%d, "
Vishnu Nair47074b82020-08-14 11:54:47 -07004731 "portalToDisplayId=%d, paused=%s, focusable=%s, "
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00004732 "hasWallpaper=%s, visible=%s, alpha=%.2f, "
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00004733 "flags=%s, type=%s, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004734 "frame=[%d,%d][%d,%d], globalScale=%f, "
Bernardo Rufino49d99e42021-01-18 15:16:59 +00004735 "applicationInfo.name=%s, "
4736 "applicationInfo.token=%s, "
chaviw1ff3d1e2020-07-01 15:53:47 -07004737 "touchableRegion=",
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00004738 i, windowInfo->name.c_str(), windowInfo->id,
4739 windowInfo->displayId, windowInfo->portalToDisplayId,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004740 toString(windowInfo->paused),
Vishnu Nair47074b82020-08-14 11:54:47 -07004741 toString(windowInfo->focusable),
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004742 toString(windowInfo->hasWallpaper),
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00004743 toString(windowInfo->visible), windowInfo->alpha,
Michael Wright8759d672020-07-21 00:46:45 +01004744 windowInfo->flags.string().c_str(),
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00004745 NamedEnum::string(windowInfo->type).c_str(),
Michael Wright44753b12020-07-08 13:48:11 +01004746 windowInfo->frameLeft, windowInfo->frameTop,
4747 windowInfo->frameRight, windowInfo->frameBottom,
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004748 windowInfo->globalScaleFactor,
Bernardo Rufino49d99e42021-01-18 15:16:59 +00004749 windowInfo->applicationInfo.name.c_str(),
4750 toString(windowInfo->applicationInfo.token).c_str());
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00004751 dump += dumpRegion(windowInfo->touchableRegion);
Michael Wright44753b12020-07-08 13:48:11 +01004752 dump += StringPrintf(", inputFeatures=%s",
4753 windowInfo->inputFeatures.string().c_str());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004754 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%" PRId64
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00004755 "ms, trustedOverlay=%s, hasToken=%s, "
4756 "touchOcclusionMode=%s\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004757 windowInfo->ownerPid, windowInfo->ownerUid,
Bernardo Rufinoc2f1fad2020-11-04 17:30:57 +00004758 millis(windowInfo->dispatchingTimeout),
4759 toString(windowInfo->trustedOverlay),
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00004760 toString(windowInfo->token != nullptr),
4761 toString(windowInfo->touchOcclusionMode).c_str());
chaviw85b44202020-07-24 11:46:21 -07004762 windowInfo->transform.dump(dump, "transform", INDENT4);
Arthur Hungb92218b2018-08-14 12:00:21 +08004763 }
4764 } else {
4765 dump += INDENT2 "Windows: <none>\n";
4766 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004767 }
4768 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08004769 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004770 }
4771
Michael Wright3dd60e22019-03-27 22:06:44 +00004772 if (!mGlobalMonitorsByDisplay.empty() || !mGestureMonitorsByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004773 for (auto& it : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004774 const std::vector<Monitor>& monitors = it.second;
4775 dump += StringPrintf(INDENT "Global monitors in display %" PRId32 ":\n", it.first);
4776 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004777 }
4778 for (auto& it : mGestureMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004779 const std::vector<Monitor>& monitors = it.second;
4780 dump += StringPrintf(INDENT "Gesture monitors in display %" PRId32 ":\n", it.first);
4781 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004782 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004783 } else {
Michael Wright3dd60e22019-03-27 22:06:44 +00004784 dump += INDENT "Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004785 }
4786
4787 nsecs_t currentTime = now();
4788
4789 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004790 if (!mRecentQueue.empty()) {
4791 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004792 for (std::shared_ptr<EventEntry>& entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004793 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05004794 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004795 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004796 }
4797 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004798 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004799 }
4800
4801 // Dump event currently being dispatched.
4802 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004803 dump += INDENT "PendingEvent:\n";
4804 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05004805 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004806 dump += StringPrintf(", age=%" PRId64 "ms\n",
4807 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004808 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004809 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004810 }
4811
4812 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004813 if (!mInboundQueue.empty()) {
4814 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004815 for (std::shared_ptr<EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004816 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05004817 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004818 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004819 }
4820 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004821 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004822 }
4823
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004824 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004825 dump += INDENT "ReplacedKeys:\n";
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004826 for (const std::pair<KeyReplacement, int32_t>& pair : mReplacedKeys) {
4827 const KeyReplacement& replacement = pair.first;
4828 int32_t newKeyCode = pair.second;
4829 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004830 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07004831 }
4832 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004833 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07004834 }
4835
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004836 if (!mConnectionsByFd.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004837 dump += INDENT "Connections:\n";
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004838 for (const auto& pair : mConnectionsByFd) {
4839 const sp<Connection>& connection = pair.second;
4840 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004841 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004842 pair.first, connection->getInputChannelName().c_str(),
4843 connection->getWindowName().c_str(), connection->getStatusLabel(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004844 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004845
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004846 if (!connection->outboundQueue.empty()) {
4847 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
4848 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05004849 dump += dumpQueue(connection->outboundQueue, currentTime);
4850
Michael Wrightd02c5b62014-02-10 15:10:22 -08004851 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004852 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004853 }
4854
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004855 if (!connection->waitQueue.empty()) {
4856 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
4857 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05004858 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004859 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004860 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004861 }
4862 }
4863 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004864 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004865 }
4866
4867 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004868 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
4869 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004870 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004871 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004872 }
4873
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004874 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004875 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
4876 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
4877 ns2ms(mConfig.keyRepeatTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004878}
4879
Michael Wright3dd60e22019-03-27 22:06:44 +00004880void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
4881 const size_t numMonitors = monitors.size();
4882 for (size_t i = 0; i < numMonitors; i++) {
4883 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004884 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00004885 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
4886 dump += "\n";
4887 }
4888}
4889
Garfield Tan15601662020-09-22 15:32:38 -07004890base::Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(
4891 const std::string& name) {
4892#if DEBUG_CHANNEL_CREATION
4893 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004894#endif
4895
Garfield Tan15601662020-09-22 15:32:38 -07004896 std::shared_ptr<InputChannel> serverChannel;
4897 std::unique_ptr<InputChannel> clientChannel;
4898 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
4899
4900 if (result) {
4901 return base::Error(result) << "Failed to open input channel pair with name " << name;
4902 }
4903
Michael Wrightd02c5b62014-02-10 15:10:22 -08004904 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004905 std::scoped_lock _l(mLock);
Garfield Tan15601662020-09-22 15:32:38 -07004906 sp<Connection> connection = new Connection(serverChannel, false /*monitor*/, mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004907
Garfield Tan15601662020-09-22 15:32:38 -07004908 int fd = serverChannel->getFd();
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004909 mConnectionsByFd[fd] = connection;
Garfield Tan15601662020-09-22 15:32:38 -07004910 mInputChannelsByToken[serverChannel->getConnectionToken()] = serverChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004911
Michael Wrightd02c5b62014-02-10 15:10:22 -08004912 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
4913 } // release lock
4914
4915 // Wake the looper because some connections have changed.
4916 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07004917 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004918}
4919
Garfield Tan15601662020-09-22 15:32:38 -07004920base::Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(
Siarhei Vishniakou58cfc602020-12-14 23:21:30 +00004921 int32_t displayId, bool isGestureMonitor, const std::string& name, int32_t pid) {
Garfield Tan15601662020-09-22 15:32:38 -07004922 std::shared_ptr<InputChannel> serverChannel;
4923 std::unique_ptr<InputChannel> clientChannel;
4924 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
4925 if (result) {
4926 return base::Error(result) << "Failed to open input channel pair with name " << name;
4927 }
4928
Michael Wright3dd60e22019-03-27 22:06:44 +00004929 { // acquire lock
4930 std::scoped_lock _l(mLock);
4931
4932 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07004933 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
4934 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00004935 }
4936
Garfield Tan15601662020-09-22 15:32:38 -07004937 sp<Connection> connection = new Connection(serverChannel, true /*monitor*/, mIdGenerator);
Michael Wright3dd60e22019-03-27 22:06:44 +00004938
Garfield Tan15601662020-09-22 15:32:38 -07004939 const int fd = serverChannel->getFd();
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004940 mConnectionsByFd[fd] = connection;
Garfield Tan15601662020-09-22 15:32:38 -07004941 mInputChannelsByToken[serverChannel->getConnectionToken()] = serverChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00004942
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004943 auto& monitorsByDisplay =
4944 isGestureMonitor ? mGestureMonitorsByDisplay : mGlobalMonitorsByDisplay;
Siarhei Vishniakou58cfc602020-12-14 23:21:30 +00004945 monitorsByDisplay[displayId].emplace_back(serverChannel, pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00004946
4947 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
Michael Wright3dd60e22019-03-27 22:06:44 +00004948 }
Garfield Tan15601662020-09-22 15:32:38 -07004949
Michael Wright3dd60e22019-03-27 22:06:44 +00004950 // Wake the looper because some connections have changed.
4951 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07004952 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00004953}
4954
Garfield Tan15601662020-09-22 15:32:38 -07004955status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004956 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004957 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004958
Garfield Tan15601662020-09-22 15:32:38 -07004959 status_t status = removeInputChannelLocked(connectionToken, false /*notify*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004960 if (status) {
4961 return status;
4962 }
4963 } // release lock
4964
4965 // Wake the poll loop because removing the connection may have changed the current
4966 // synchronization state.
4967 mLooper->wake();
4968 return OK;
4969}
4970
Garfield Tan15601662020-09-22 15:32:38 -07004971status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
4972 bool notify) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004973 sp<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004974 if (connection == nullptr) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00004975 // Connection can be removed via socket hang up or an explicit call to 'removeInputChannel'
Michael Wrightd02c5b62014-02-10 15:10:22 -08004976 return BAD_VALUE;
4977 }
4978
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004979 removeConnectionLocked(connection);
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004980 mInputChannelsByToken.erase(connectionToken);
Robert Carr5c8a0262018-10-03 16:30:44 -07004981
Michael Wrightd02c5b62014-02-10 15:10:22 -08004982 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004983 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004984 }
4985
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004986 mLooper->removeFd(connection->inputChannel->getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004987
4988 nsecs_t currentTime = now();
4989 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
4990
4991 connection->status = Connection::STATUS_ZOMBIE;
4992 return OK;
4993}
4994
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004995void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
4996 removeMonitorChannelLocked(connectionToken, mGlobalMonitorsByDisplay);
4997 removeMonitorChannelLocked(connectionToken, mGestureMonitorsByDisplay);
Michael Wright3dd60e22019-03-27 22:06:44 +00004998}
4999
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005000void InputDispatcher::removeMonitorChannelLocked(
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005001 const sp<IBinder>& connectionToken,
Michael Wright3dd60e22019-03-27 22:06:44 +00005002 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005003 for (auto it = monitorsByDisplay.begin(); it != monitorsByDisplay.end();) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005004 std::vector<Monitor>& monitors = it->second;
5005 const size_t numMonitors = monitors.size();
5006 for (size_t i = 0; i < numMonitors; i++) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005007 if (monitors[i].inputChannel->getConnectionToken() == connectionToken) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005008 monitors.erase(monitors.begin() + i);
5009 break;
5010 }
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005011 }
Michael Wright3dd60e22019-03-27 22:06:44 +00005012 if (monitors.empty()) {
5013 it = monitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005014 } else {
5015 ++it;
5016 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005017 }
5018}
5019
Michael Wright3dd60e22019-03-27 22:06:44 +00005020status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
5021 { // acquire lock
5022 std::scoped_lock _l(mLock);
5023 std::optional<int32_t> foundDisplayId = findGestureMonitorDisplayByTokenLocked(token);
5024
5025 if (!foundDisplayId) {
5026 ALOGW("Attempted to pilfer pointers from an un-registered monitor or invalid token");
5027 return BAD_VALUE;
5028 }
5029 int32_t displayId = foundDisplayId.value();
5030
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005031 std::unordered_map<int32_t, TouchState>::iterator stateIt =
5032 mTouchStatesByDisplay.find(displayId);
5033 if (stateIt == mTouchStatesByDisplay.end()) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005034 ALOGW("Failed to pilfer pointers: no pointers on display %" PRId32 ".", displayId);
5035 return BAD_VALUE;
5036 }
5037
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005038 TouchState& state = stateIt->second;
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005039 std::shared_ptr<InputChannel> requestingChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005040 std::optional<int32_t> foundDeviceId;
5041 for (const TouchedMonitor& touchedMonitor : state.gestureMonitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005042 if (touchedMonitor.monitor.inputChannel->getConnectionToken() == token) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005043 requestingChannel = touchedMonitor.monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005044 foundDeviceId = state.deviceId;
5045 }
5046 }
5047 if (!foundDeviceId || !state.down) {
5048 ALOGW("Attempted to pilfer points from a monitor without any on-going pointer streams."
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005049 " Ignoring.");
Michael Wright3dd60e22019-03-27 22:06:44 +00005050 return BAD_VALUE;
5051 }
5052 int32_t deviceId = foundDeviceId.value();
5053
5054 // Send cancel events to all the input channels we're stealing from.
5055 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005056 "gesture monitor stole pointer stream");
Michael Wright3dd60e22019-03-27 22:06:44 +00005057 options.deviceId = deviceId;
5058 options.displayId = displayId;
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005059 std::string canceledWindows = "[";
Michael Wright3dd60e22019-03-27 22:06:44 +00005060 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005061 std::shared_ptr<InputChannel> channel =
5062 getInputChannelLocked(window.windowHandle->getToken());
Michael Wright3a240c42019-12-10 20:53:41 +00005063 if (channel != nullptr) {
5064 synthesizeCancelationEventsForInputChannelLocked(channel, options);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005065 canceledWindows += channel->getName() + ", ";
Michael Wright3a240c42019-12-10 20:53:41 +00005066 }
Michael Wright3dd60e22019-03-27 22:06:44 +00005067 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005068 canceledWindows += "]";
5069 ALOGI("Monitor %s is stealing touch from %s", requestingChannel->getName().c_str(),
5070 canceledWindows.c_str());
5071
Michael Wright3dd60e22019-03-27 22:06:44 +00005072 // Then clear the current touch state so we stop dispatching to them as well.
5073 state.filterNonMonitors();
5074 }
5075 return OK;
5076}
5077
Prabir Pradhan99987712020-11-10 18:43:05 -08005078void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
5079 { // acquire lock
5080 std::scoped_lock _l(mLock);
5081 if (DEBUG_FOCUS) {
5082 const sp<InputWindowHandle> windowHandle = getWindowHandleLocked(windowToken);
5083 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
5084 windowHandle != nullptr ? windowHandle->getName().c_str()
5085 : "token without window");
5086 }
5087
Vishnu Nairc519ff72021-01-21 08:23:08 -08005088 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08005089 if (focusedToken != windowToken) {
5090 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
5091 enabled ? "enable" : "disable");
5092 return;
5093 }
5094
5095 if (enabled == mFocusedWindowRequestedPointerCapture) {
5096 ALOGW("Ignoring request to %s Pointer Capture: "
5097 "window has %s requested pointer capture.",
5098 enabled ? "enable" : "disable", enabled ? "already" : "not");
5099 return;
5100 }
5101
5102 mFocusedWindowRequestedPointerCapture = enabled;
5103 setPointerCaptureLocked(enabled);
5104 } // release lock
5105
5106 // Wake the thread to process command entries.
5107 mLooper->wake();
5108}
5109
Michael Wright3dd60e22019-03-27 22:06:44 +00005110std::optional<int32_t> InputDispatcher::findGestureMonitorDisplayByTokenLocked(
5111 const sp<IBinder>& token) {
5112 for (const auto& it : mGestureMonitorsByDisplay) {
5113 const std::vector<Monitor>& monitors = it.second;
5114 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005115 if (monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005116 return it.first;
5117 }
5118 }
5119 }
5120 return std::nullopt;
5121}
5122
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005123std::optional<int32_t> InputDispatcher::findMonitorPidByTokenLocked(const sp<IBinder>& token) {
5124 std::optional<int32_t> gesturePid = findMonitorPidByToken(mGestureMonitorsByDisplay, token);
5125 if (gesturePid.has_value()) {
5126 return gesturePid;
5127 }
5128 return findMonitorPidByToken(mGlobalMonitorsByDisplay, token);
5129}
5130
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005131sp<Connection> InputDispatcher::getConnectionLocked(const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005132 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005133 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08005134 }
5135
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005136 for (const auto& pair : mConnectionsByFd) {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005137 const sp<Connection>& connection = pair.second;
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005138 if (connection->inputChannel->getConnectionToken() == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005139 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005140 }
5141 }
Robert Carr4e670e52018-08-15 13:26:12 -07005142
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005143 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005144}
5145
Siarhei Vishniakouad991402020-10-28 11:40:09 -05005146std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
5147 sp<Connection> connection = getConnectionLocked(connectionToken);
5148 if (connection == nullptr) {
5149 return "<nullptr>";
5150 }
5151 return connection->getInputChannelName();
5152}
5153
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005154void InputDispatcher::removeConnectionLocked(const sp<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005155 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005156 removeByValue(mConnectionsByFd, connection);
5157}
5158
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005159void InputDispatcher::onDispatchCycleFinishedLocked(nsecs_t currentTime,
5160 const sp<Connection>& connection, uint32_t seq,
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10005161 bool handled, nsecs_t consumeTime) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005162 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5163 &InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005164 commandEntry->connection = connection;
5165 commandEntry->eventTime = currentTime;
5166 commandEntry->seq = seq;
5167 commandEntry->handled = handled;
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10005168 commandEntry->consumeTime = consumeTime;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005169 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005170}
5171
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005172void InputDispatcher::onDispatchCycleBrokenLocked(nsecs_t currentTime,
5173 const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005174 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005175 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005176
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005177 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5178 &InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005179 commandEntry->connection = connection;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005180 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005181}
5182
Vishnu Nairad321cd2020-08-20 16:40:21 -07005183void InputDispatcher::notifyFocusChangedLocked(const sp<IBinder>& oldToken,
5184 const sp<IBinder>& newToken) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005185 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5186 &InputDispatcher::doNotifyFocusChangedLockedInterruptible);
chaviw0c06c6e2019-01-09 13:27:07 -08005187 commandEntry->oldToken = oldToken;
5188 commandEntry->newToken = newToken;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005189 postCommandLocked(std::move(commandEntry));
Robert Carrf759f162018-11-13 12:57:11 -08005190}
5191
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005192void InputDispatcher::onAnrLocked(const sp<Connection>& connection) {
5193 if (connection == nullptr) {
5194 LOG_ALWAYS_FATAL("Caller must check for nullness");
5195 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005196 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
5197 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005198 if (connection->waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005199 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005200 connection->inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005201 return;
5202 }
5203 /**
5204 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
5205 * may not be the one that caused the timeout to occur. One possibility is that window timeout
5206 * has changed. This could cause newer entries to time out before the already dispatched
5207 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
5208 * processes the events linearly. So providing information about the oldest entry seems to be
5209 * most useful.
5210 */
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005211 DispatchEntry* oldestEntry = *connection->waitQueue.begin();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005212 const nsecs_t currentWait = now() - oldestEntry->deliveryTime;
5213 std::string reason =
5214 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005215 connection->inputChannel->getName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005216 ns2ms(currentWait),
5217 oldestEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005218 sp<IBinder> connectionToken = connection->inputChannel->getConnectionToken();
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06005219 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005220
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005221 processConnectionUnresponsiveLocked(*connection, std::move(reason));
5222
5223 // Stop waking up for events on this connection, it is already unresponsive
5224 cancelEventsForAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005225}
5226
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005227void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
5228 std::string reason =
5229 StringPrintf("%s does not have a focused window", application->getName().c_str());
5230 updateLastAnrStateLocked(*application, reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005231
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005232 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5233 &InputDispatcher::doNotifyNoFocusedWindowAnrLockedInterruptible);
5234 commandEntry->inputApplicationHandle = std::move(application);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005235 postCommandLocked(std::move(commandEntry));
5236}
5237
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00005238void InputDispatcher::onUntrustedTouchLocked(const std::string& obscuringPackage) {
5239 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5240 &InputDispatcher::doNotifyUntrustedTouchLockedInterruptible);
5241 commandEntry->obscuringPackage = obscuringPackage;
5242 postCommandLocked(std::move(commandEntry));
5243}
5244
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005245void InputDispatcher::updateLastAnrStateLocked(const sp<InputWindowHandle>& window,
5246 const std::string& reason) {
5247 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
5248 updateLastAnrStateLocked(windowLabel, reason);
5249}
5250
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005251void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
5252 const std::string& reason) {
5253 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005254 updateLastAnrStateLocked(windowLabel, reason);
5255}
5256
5257void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
5258 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005259 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07005260 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005261 struct tm tm;
5262 localtime_r(&t, &tm);
5263 char timestr[64];
5264 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005265 mLastAnrState.clear();
5266 mLastAnrState += INDENT "ANR:\n";
5267 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005268 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
5269 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005270 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005271}
5272
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005273void InputDispatcher::doNotifyConfigurationChangedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005274 mLock.unlock();
5275
5276 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
5277
5278 mLock.lock();
5279}
5280
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005281void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005282 sp<Connection> connection = commandEntry->connection;
5283
5284 if (connection->status != Connection::STATUS_ZOMBIE) {
5285 mLock.unlock();
5286
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005287 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005288
5289 mLock.lock();
5290 }
5291}
5292
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005293void InputDispatcher::doNotifyFocusChangedLockedInterruptible(CommandEntry* commandEntry) {
chaviw0c06c6e2019-01-09 13:27:07 -08005294 sp<IBinder> oldToken = commandEntry->oldToken;
5295 sp<IBinder> newToken = commandEntry->newToken;
Robert Carrf759f162018-11-13 12:57:11 -08005296 mLock.unlock();
chaviw0c06c6e2019-01-09 13:27:07 -08005297 mPolicy->notifyFocusChanged(oldToken, newToken);
Robert Carrf759f162018-11-13 12:57:11 -08005298 mLock.lock();
5299}
5300
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005301void InputDispatcher::doNotifyNoFocusedWindowAnrLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005302 mLock.unlock();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005303
5304 mPolicy->notifyNoFocusedWindowAnr(commandEntry->inputApplicationHandle);
5305
5306 mLock.lock();
5307}
5308
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005309void InputDispatcher::doNotifyWindowUnresponsiveLockedInterruptible(CommandEntry* commandEntry) {
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005310 mLock.unlock();
5311
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005312 mPolicy->notifyWindowUnresponsive(commandEntry->connectionToken, commandEntry->reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005313
5314 mLock.lock();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005315}
5316
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005317void InputDispatcher::doNotifyMonitorUnresponsiveLockedInterruptible(CommandEntry* commandEntry) {
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005318 mLock.unlock();
5319
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005320 mPolicy->notifyMonitorUnresponsive(commandEntry->pid, commandEntry->reason);
5321
5322 mLock.lock();
5323}
5324
5325void InputDispatcher::doNotifyWindowResponsiveLockedInterruptible(CommandEntry* commandEntry) {
5326 mLock.unlock();
5327
5328 mPolicy->notifyWindowResponsive(commandEntry->connectionToken);
5329
5330 mLock.lock();
5331}
5332
5333void InputDispatcher::doNotifyMonitorResponsiveLockedInterruptible(CommandEntry* commandEntry) {
5334 mLock.unlock();
5335
5336 mPolicy->notifyMonitorResponsive(commandEntry->pid);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005337
5338 mLock.lock();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005339}
5340
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00005341void InputDispatcher::doNotifyUntrustedTouchLockedInterruptible(CommandEntry* commandEntry) {
5342 mLock.unlock();
5343
5344 mPolicy->notifyUntrustedTouch(commandEntry->obscuringPackage);
5345
5346 mLock.lock();
5347}
5348
Michael Wrightd02c5b62014-02-10 15:10:22 -08005349void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
5350 CommandEntry* commandEntry) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005351 KeyEntry& entry = *(commandEntry->keyEntry);
5352 KeyEvent event = createKeyEvent(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005353
5354 mLock.unlock();
5355
Michael Wright2b3c3302018-03-02 17:19:13 +00005356 android::base::Timer t;
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06005357 const sp<IBinder>& token = commandEntry->connectionToken;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005358 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(token, &event, entry.policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00005359 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
5360 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005361 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00005362 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005363
5364 mLock.lock();
5365
5366 if (delay < 0) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005367 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005368 } else if (!delay) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005369 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005370 } else {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005371 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
5372 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005373 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005374}
5375
chaviwfd6d3512019-03-25 13:23:49 -07005376void InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible(CommandEntry* commandEntry) {
5377 mLock.unlock();
5378 mPolicy->onPointerDownOutsideFocus(commandEntry->newToken);
5379 mLock.lock();
5380}
5381
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005382/**
5383 * Connection is responsive if it has no events in the waitQueue that are older than the
5384 * current time.
5385 */
5386static bool isConnectionResponsive(const Connection& connection) {
5387 const nsecs_t currentTime = now();
5388 for (const DispatchEntry* entry : connection.waitQueue) {
5389 if (entry->timeoutTime < currentTime) {
5390 return false;
5391 }
5392 }
5393 return true;
5394}
5395
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005396void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005397 sp<Connection> connection = commandEntry->connection;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005398 const nsecs_t finishTime = commandEntry->eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005399 uint32_t seq = commandEntry->seq;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005400 const bool handled = commandEntry->handled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005401
5402 // Handle post-event policy actions.
Garfield Tane84e6f92019-08-29 17:28:41 -07005403 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005404 if (dispatchEntryIt == connection->waitQueue.end()) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005405 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005406 }
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005407 DispatchEntry* dispatchEntry = *dispatchEntryIt;
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07005408 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005409 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005410 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
5411 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005412 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07005413 reportDispatchStatistics(std::chrono::nanoseconds(eventDuration), *connection, handled);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005414
5415 bool restartEvent;
Siarhei Vishniakou49483272019-10-22 13:13:47 -07005416 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005417 KeyEntry& keyEntry = static_cast<KeyEntry&>(*(dispatchEntry->eventEntry));
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005418 restartEvent =
5419 afterKeyEventLockedInterruptible(connection, dispatchEntry, keyEntry, handled);
Siarhei Vishniakou49483272019-10-22 13:13:47 -07005420 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005421 MotionEntry& motionEntry = static_cast<MotionEntry&>(*(dispatchEntry->eventEntry));
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005422 restartEvent = afterMotionEventLockedInterruptible(connection, dispatchEntry, motionEntry,
5423 handled);
5424 } else {
5425 restartEvent = false;
5426 }
5427
5428 // Dequeue the event and start the next cycle.
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07005429 // Because the lock might have been released, it is possible that the
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005430 // contents of the wait queue to have been drained, so we need to double-check
5431 // a few things.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005432 dispatchEntryIt = connection->findWaitQueueEntry(seq);
5433 if (dispatchEntryIt != connection->waitQueue.end()) {
5434 dispatchEntry = *dispatchEntryIt;
5435 connection->waitQueue.erase(dispatchEntryIt);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005436 const sp<IBinder>& connectionToken = connection->inputChannel->getConnectionToken();
5437 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005438 if (!connection->responsive) {
5439 connection->responsive = isConnectionResponsive(*connection);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005440 if (connection->responsive) {
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005441 // The connection was unresponsive, and now it's responsive.
5442 processConnectionResponsiveLocked(*connection);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005443 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005444 }
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005445 traceWaitQueueLength(connection);
5446 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005447 connection->outboundQueue.push_front(dispatchEntry);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005448 traceOutboundQueueLength(connection);
5449 } else {
5450 releaseDispatchEntry(dispatchEntry);
5451 }
5452 }
5453
5454 // Start the next dispatch cycle for this connection.
5455 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005456}
5457
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005458void InputDispatcher::sendMonitorUnresponsiveCommandLocked(int32_t pid, std::string reason) {
5459 std::unique_ptr<CommandEntry> monitorUnresponsiveCommand = std::make_unique<CommandEntry>(
5460 &InputDispatcher::doNotifyMonitorUnresponsiveLockedInterruptible);
5461 monitorUnresponsiveCommand->pid = pid;
5462 monitorUnresponsiveCommand->reason = std::move(reason);
5463 postCommandLocked(std::move(monitorUnresponsiveCommand));
5464}
5465
5466void InputDispatcher::sendWindowUnresponsiveCommandLocked(sp<IBinder> connectionToken,
5467 std::string reason) {
5468 std::unique_ptr<CommandEntry> windowUnresponsiveCommand = std::make_unique<CommandEntry>(
5469 &InputDispatcher::doNotifyWindowUnresponsiveLockedInterruptible);
5470 windowUnresponsiveCommand->connectionToken = std::move(connectionToken);
5471 windowUnresponsiveCommand->reason = std::move(reason);
5472 postCommandLocked(std::move(windowUnresponsiveCommand));
5473}
5474
5475void InputDispatcher::sendMonitorResponsiveCommandLocked(int32_t pid) {
5476 std::unique_ptr<CommandEntry> monitorResponsiveCommand = std::make_unique<CommandEntry>(
5477 &InputDispatcher::doNotifyMonitorResponsiveLockedInterruptible);
5478 monitorResponsiveCommand->pid = pid;
5479 postCommandLocked(std::move(monitorResponsiveCommand));
5480}
5481
5482void InputDispatcher::sendWindowResponsiveCommandLocked(sp<IBinder> connectionToken) {
5483 std::unique_ptr<CommandEntry> windowResponsiveCommand = std::make_unique<CommandEntry>(
5484 &InputDispatcher::doNotifyWindowResponsiveLockedInterruptible);
5485 windowResponsiveCommand->connectionToken = std::move(connectionToken);
5486 postCommandLocked(std::move(windowResponsiveCommand));
5487}
5488
5489/**
5490 * Tell the policy that a connection has become unresponsive so that it can start ANR.
5491 * Check whether the connection of interest is a monitor or a window, and add the corresponding
5492 * command entry to the command queue.
5493 */
5494void InputDispatcher::processConnectionUnresponsiveLocked(const Connection& connection,
5495 std::string reason) {
5496 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
5497 if (connection.monitor) {
5498 ALOGW("Monitor %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
5499 reason.c_str());
5500 std::optional<int32_t> pid = findMonitorPidByTokenLocked(connectionToken);
5501 if (!pid.has_value()) {
5502 ALOGE("Could not find unresponsive monitor for connection %s",
5503 connection.inputChannel->getName().c_str());
5504 return;
5505 }
5506 sendMonitorUnresponsiveCommandLocked(pid.value(), std::move(reason));
5507 return;
5508 }
5509 // If not a monitor, must be a window
5510 ALOGW("Window %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
5511 reason.c_str());
5512 sendWindowUnresponsiveCommandLocked(connectionToken, std::move(reason));
5513}
5514
5515/**
5516 * Tell the policy that a connection has become responsive so that it can stop ANR.
5517 */
5518void InputDispatcher::processConnectionResponsiveLocked(const Connection& connection) {
5519 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
5520 if (connection.monitor) {
5521 std::optional<int32_t> pid = findMonitorPidByTokenLocked(connectionToken);
5522 if (!pid.has_value()) {
5523 ALOGE("Could not find responsive monitor for connection %s",
5524 connection.inputChannel->getName().c_str());
5525 return;
5526 }
5527 sendMonitorResponsiveCommandLocked(pid.value());
5528 return;
5529 }
5530 // If not a monitor, must be a window
5531 sendWindowResponsiveCommandLocked(connectionToken);
5532}
5533
Michael Wrightd02c5b62014-02-10 15:10:22 -08005534bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005535 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005536 KeyEntry& keyEntry, bool handled) {
5537 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005538 if (!handled) {
5539 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005540 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005541 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005542 return false;
5543 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005544
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005545 // Get the fallback key state.
5546 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005547 int32_t originalKeyCode = keyEntry.keyCode;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005548 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005549 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005550 connection->inputState.removeFallbackKey(originalKeyCode);
5551 }
5552
5553 if (handled || !dispatchEntry->hasForegroundTarget()) {
5554 // If the application handles the original key for which we previously
5555 // generated a fallback or if the window is not a foreground window,
5556 // then cancel the associated fallback key, if any.
5557 if (fallbackKeyCode != -1) {
5558 // Dispatch the unhandled key to the policy with the cancel flag.
Michael Wrightd02c5b62014-02-10 15:10:22 -08005559#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005560 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005561 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005562 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005563#endif
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005564 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005565 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005566
5567 mLock.unlock();
5568
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005569 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005570 keyEntry.policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005571
5572 mLock.lock();
5573
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005574 // Cancel the fallback key.
5575 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005576 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005577 "application handled the original non-fallback key "
5578 "or is no longer a foreground target, "
5579 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005580 options.keyCode = fallbackKeyCode;
5581 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005582 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005583 connection->inputState.removeFallbackKey(originalKeyCode);
5584 }
5585 } else {
5586 // If the application did not handle a non-fallback key, first check
5587 // that we are in a good state to perform unhandled key event processing
5588 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005589 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005590 if (fallbackKeyCode == -1 && !initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005591#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005592 ALOGD("Unhandled key event: Skipping unhandled key event processing "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005593 "since this is not an initial down. "
5594 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005595 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005596#endif
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 // Dispatch the unhandled key to the policy.
5601#if DEBUG_OUTBOUND_EVENT_DETAILS
5602 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005603 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005604 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005605#endif
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005606 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005607
5608 mLock.unlock();
5609
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005610 bool fallback =
5611 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005612 &event, keyEntry.policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005613
5614 mLock.lock();
5615
5616 if (connection->status != Connection::STATUS_NORMAL) {
5617 connection->inputState.removeFallbackKey(originalKeyCode);
5618 return false;
5619 }
5620
5621 // Latch the fallback keycode for this key on an initial down.
5622 // The fallback keycode cannot change at any other point in the lifecycle.
5623 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005624 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005625 fallbackKeyCode = event.getKeyCode();
5626 } else {
5627 fallbackKeyCode = AKEYCODE_UNKNOWN;
5628 }
5629 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
5630 }
5631
5632 ALOG_ASSERT(fallbackKeyCode != -1);
5633
5634 // Cancel the fallback key if the policy decides not to send it anymore.
5635 // We will continue to dispatch the key to the policy but we will no
5636 // longer dispatch a fallback key to the application.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005637 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
5638 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005639#if DEBUG_OUTBOUND_EVENT_DETAILS
5640 if (fallback) {
5641 ALOGD("Unhandled key event: Policy requested to send key %d"
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005642 "as a fallback for %d, but on the DOWN it had requested "
5643 "to send %d instead. Fallback canceled.",
5644 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005645 } else {
5646 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005647 "but on the DOWN it had requested to send %d. "
5648 "Fallback canceled.",
5649 originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005650 }
5651#endif
5652
5653 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
5654 "canceling fallback, policy no longer desires it");
5655 options.keyCode = fallbackKeyCode;
5656 synthesizeCancelationEventsForConnectionLocked(connection, options);
5657
5658 fallback = false;
5659 fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005660 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005661 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005662 }
5663 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005664
5665#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005666 {
5667 std::string msg;
5668 const KeyedVector<int32_t, int32_t>& fallbackKeys =
5669 connection->inputState.getFallbackKeys();
5670 for (size_t i = 0; i < fallbackKeys.size(); i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005671 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005672 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005673 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005674 fallbackKeys.size(), msg.c_str());
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005675 }
5676#endif
5677
5678 if (fallback) {
5679 // Restart the dispatch cycle using the fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005680 keyEntry.eventTime = event.getEventTime();
5681 keyEntry.deviceId = event.getDeviceId();
5682 keyEntry.source = event.getSource();
5683 keyEntry.displayId = event.getDisplayId();
5684 keyEntry.flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
5685 keyEntry.keyCode = fallbackKeyCode;
5686 keyEntry.scanCode = event.getScanCode();
5687 keyEntry.metaState = event.getMetaState();
5688 keyEntry.repeatCount = event.getRepeatCount();
5689 keyEntry.downTime = event.getDownTime();
5690 keyEntry.syntheticRepeat = false;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005691
5692#if DEBUG_OUTBOUND_EVENT_DETAILS
5693 ALOGD("Unhandled key event: Dispatching fallback key. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005694 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005695 originalKeyCode, fallbackKeyCode, keyEntry.metaState);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005696#endif
5697 return true; // restart the event
5698 } else {
5699#if DEBUG_OUTBOUND_EVENT_DETAILS
5700 ALOGD("Unhandled key event: No fallback key.");
5701#endif
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005702
5703 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005704 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005705 }
5706 }
5707 return false;
5708}
5709
5710bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005711 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005712 MotionEntry& motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005713 return false;
5714}
5715
5716void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
5717 mLock.unlock();
5718
Sean Stoutb4e0a592021-02-23 07:34:53 -08005719 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType,
5720 commandEntry->displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005721
5722 mLock.lock();
5723}
5724
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07005725void InputDispatcher::reportDispatchStatistics(std::chrono::nanoseconds eventDuration,
5726 const Connection& connection, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005727 // TODO Write some statistics about how long we spend waiting.
5728}
5729
Siarhei Vishniakoude4bf152019-08-16 11:12:52 -05005730/**
5731 * Report the touch event latency to the statsd server.
5732 * Input events are reported for statistics if:
5733 * - This is a touchscreen event
5734 * - InputFilter is not enabled
5735 * - Event is not injected or synthesized
5736 *
5737 * Statistics should be reported before calling addValue, to prevent a fresh new sample
5738 * from getting aggregated with the "old" data.
5739 */
5740void InputDispatcher::reportTouchEventForStatistics(const MotionEntry& motionEntry)
5741 REQUIRES(mLock) {
5742 const bool reportForStatistics = (motionEntry.source == AINPUT_SOURCE_TOUCHSCREEN) &&
5743 !(motionEntry.isSynthesized()) && !mInputFilterEnabled;
5744 if (!reportForStatistics) {
5745 return;
5746 }
5747
5748 if (mTouchStatistics.shouldReport()) {
5749 android::util::stats_write(android::util::TOUCH_EVENT_REPORTED, mTouchStatistics.getMin(),
5750 mTouchStatistics.getMax(), mTouchStatistics.getMean(),
5751 mTouchStatistics.getStDev(), mTouchStatistics.getCount());
5752 mTouchStatistics.reset();
5753 }
5754 const float latencyMicros = nanoseconds_to_microseconds(now() - motionEntry.eventTime);
5755 mTouchStatistics.addValue(latencyMicros);
5756}
5757
Michael Wrightd02c5b62014-02-10 15:10:22 -08005758void InputDispatcher::traceInboundQueueLengthLocked() {
5759 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005760 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005761 }
5762}
5763
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08005764void InputDispatcher::traceOutboundQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005765 if (ATRACE_ENABLED()) {
5766 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08005767 snprintf(counterName, sizeof(counterName), "oq:%s", connection->getWindowName().c_str());
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005768 ATRACE_INT(counterName, connection->outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005769 }
5770}
5771
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08005772void InputDispatcher::traceWaitQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005773 if (ATRACE_ENABLED()) {
5774 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08005775 snprintf(counterName, sizeof(counterName), "wq:%s", connection->getWindowName().c_str());
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005776 ATRACE_INT(counterName, connection->waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005777 }
5778}
5779
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005780void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005781 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005782
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005783 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005784 dumpDispatchStateLocked(dump);
5785
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005786 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005787 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005788 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005789 }
5790}
5791
5792void InputDispatcher::monitor() {
5793 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005794 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005795 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005796 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005797}
5798
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08005799/**
5800 * Wake up the dispatcher and wait until it processes all events and commands.
5801 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
5802 * this method can be safely called from any thread, as long as you've ensured that
5803 * the work you are interested in completing has already been queued.
5804 */
5805bool InputDispatcher::waitForIdle() {
5806 /**
5807 * Timeout should represent the longest possible time that a device might spend processing
5808 * events and commands.
5809 */
5810 constexpr std::chrono::duration TIMEOUT = 100ms;
5811 std::unique_lock lock(mLock);
5812 mLooper->wake();
5813 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
5814 return result == std::cv_status::no_timeout;
5815}
5816
Vishnu Naire798b472020-07-23 13:52:21 -07005817/**
5818 * Sets focus to the window identified by the token. This must be called
5819 * after updating any input window handles.
5820 *
5821 * Params:
5822 * request.token - input channel token used to identify the window that should gain focus.
5823 * request.focusedToken - the token that the caller expects currently to be focused. If the
5824 * specified token does not match the currently focused window, this request will be dropped.
5825 * If the specified focused token matches the currently focused window, the call will succeed.
5826 * Set this to "null" if this call should succeed no matter what the currently focused token is.
5827 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
5828 * when requesting the focus change. This determines which request gets
5829 * precedence if there is a focus change request from another source such as pointer down.
5830 */
Vishnu Nair958da932020-08-21 17:12:37 -07005831void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
5832 { // acquire lock
5833 std::scoped_lock _l(mLock);
Vishnu Nairc519ff72021-01-21 08:23:08 -08005834 std::optional<FocusResolver::FocusChanges> changes =
5835 mFocusResolver.setFocusedWindow(request, getWindowHandlesLocked(request.displayId));
5836 if (changes) {
5837 onFocusChangedLocked(*changes);
Vishnu Nair958da932020-08-21 17:12:37 -07005838 }
5839 } // release lock
5840 // Wake up poll loop since it may need to make new input dispatching choices.
5841 mLooper->wake();
5842}
5843
Vishnu Nairc519ff72021-01-21 08:23:08 -08005844void InputDispatcher::onFocusChangedLocked(const FocusResolver::FocusChanges& changes) {
5845 if (changes.oldFocus) {
5846 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(changes.oldFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005847 if (focusedInputChannel) {
5848 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
5849 "focus left window");
5850 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Vishnu Nairc519ff72021-01-21 08:23:08 -08005851 enqueueFocusEventLocked(changes.oldFocus, false /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005852 }
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005853 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08005854 if (changes.newFocus) {
5855 enqueueFocusEventLocked(changes.newFocus, true /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005856 }
5857
Prabir Pradhan99987712020-11-10 18:43:05 -08005858 // If a window has pointer capture, then it must have focus. We need to ensure that this
5859 // contract is upheld when pointer capture is being disabled due to a loss of window focus.
5860 // If the window loses focus before it loses pointer capture, then the window can be in a state
5861 // where it has pointer capture but not focus, violating the contract. Therefore we must
5862 // dispatch the pointer capture event before the focus event. Since focus events are added to
5863 // the front of the queue (above), we add the pointer capture event to the front of the queue
5864 // after the focus events are added. This ensures the pointer capture event ends up at the
5865 // front.
5866 disablePointerCaptureForcedLocked();
5867
Vishnu Nairc519ff72021-01-21 08:23:08 -08005868 if (mFocusedDisplayId == changes.displayId) {
5869 notifyFocusChangedLocked(changes.oldFocus, changes.newFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005870 }
5871}
Vishnu Nair958da932020-08-21 17:12:37 -07005872
Prabir Pradhan99987712020-11-10 18:43:05 -08005873void InputDispatcher::disablePointerCaptureForcedLocked() {
5874 if (!mFocusedWindowRequestedPointerCapture && !mWindowTokenWithPointerCapture) {
5875 return;
5876 }
5877
5878 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
5879
5880 if (mFocusedWindowRequestedPointerCapture) {
5881 mFocusedWindowRequestedPointerCapture = false;
5882 setPointerCaptureLocked(false);
5883 }
5884
5885 if (!mWindowTokenWithPointerCapture) {
5886 // No need to send capture changes because no window has capture.
5887 return;
5888 }
5889
5890 if (mPendingEvent != nullptr) {
5891 // Move the pending event to the front of the queue. This will give the chance
5892 // for the pending event to be dropped if it is a captured event.
5893 mInboundQueue.push_front(mPendingEvent);
5894 mPendingEvent = nullptr;
5895 }
5896
5897 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
5898 false /* hasCapture */);
5899 mInboundQueue.push_front(std::move(entry));
5900}
5901
Prabir Pradhan99987712020-11-10 18:43:05 -08005902void InputDispatcher::setPointerCaptureLocked(bool enabled) {
5903 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5904 &InputDispatcher::doSetPointerCaptureLockedInterruptible);
5905 commandEntry->enabled = enabled;
5906 postCommandLocked(std::move(commandEntry));
5907}
5908
5909void InputDispatcher::doSetPointerCaptureLockedInterruptible(
5910 android::inputdispatcher::CommandEntry* commandEntry) {
5911 mLock.unlock();
5912
5913 mPolicy->setPointerCapture(commandEntry->enabled);
5914
5915 mLock.lock();
5916}
5917
Garfield Tane84e6f92019-08-29 17:28:41 -07005918} // namespace android::inputdispatcher