blob: 5984d58f7d127392b7469b0cf4734f90eca26096 [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>
Peter Collingbourneb04b9b82021-02-08 12:09:47 -080051#include <android-base/properties.h>
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080052#include <android-base/stringprintf.h>
Siarhei Vishniakou70622952020-07-30 11:17:23 -050053#include <android/os/IInputConstants.h>
Robert Carr4e670e52018-08-15 13:26:12 -070054#include <binder/Binder.h>
Siarhei Vishniakou2508b872020-12-03 16:33:53 -100055#include <binder/IServiceManager.h>
56#include <com/android/internal/compat/IPlatformCompatNative.h>
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -080057#include <input/InputDevice.h>
Michael Wright44753b12020-07-08 13:48:11 +010058#include <input/InputWindow.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070059#include <log/log.h>
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +000060#include <log/log_event_list.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070061#include <powermanager/PowerManager.h>
Michael Wright44753b12020-07-08 13:48:11 +010062#include <statslog.h>
63#include <unistd.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070064#include <utils/Trace.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080065
Michael Wright44753b12020-07-08 13:48:11 +010066#include <cerrno>
67#include <cinttypes>
68#include <climits>
69#include <cstddef>
70#include <ctime>
71#include <queue>
72#include <sstream>
73
74#include "Connection.h"
Chris Yef59a2f42020-10-16 12:55:26 -070075#include "InputDispatcher.h"
Michael Wright44753b12020-07-08 13:48:11 +010076
Michael Wrightd02c5b62014-02-10 15:10:22 -080077#define INDENT " "
78#define INDENT2 " "
79#define INDENT3 " "
80#define INDENT4 " "
81
Peter Collingbourneb04b9b82021-02-08 12:09:47 -080082using android::base::HwTimeoutMultiplier;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080083using android::base::StringPrintf;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -080084using android::os::BlockUntrustedTouchesMode;
Siarhei Vishniakou2508b872020-12-03 16:33:53 -100085using android::os::IInputConstants;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -080086using android::os::InputEventInjectionResult;
87using android::os::InputEventInjectionSync;
Siarhei Vishniakou2508b872020-12-03 16:33:53 -100088using com::android::internal::compat::IPlatformCompatNative;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080089
Garfield Tane84e6f92019-08-29 17:28:41 -070090namespace android::inputdispatcher {
Michael Wrightd02c5b62014-02-10 15:10:22 -080091
92// Default input dispatching timeout if there is no focused application or paused window
93// from which to determine an appropriate dispatching timeout.
Peter Collingbourneb04b9b82021-02-08 12:09:47 -080094const std::chrono::duration DEFAULT_INPUT_DISPATCHING_TIMEOUT = std::chrono::milliseconds(
95 android::os::IInputConstants::UNMULTIPLIED_DEFAULT_DISPATCHING_TIMEOUT_MILLIS *
96 HwTimeoutMultiplier());
Michael Wrightd02c5b62014-02-10 15:10:22 -080097
98// Amount of time to allow for all pending events to be processed when an app switch
99// key is on the way. This is used to preempt input dispatch and drop input events
100// when an application takes too long to respond and the user has pressed an app switch key.
Michael Wright2b3c3302018-03-02 17:19:13 +0000101constexpr nsecs_t APP_SWITCH_TIMEOUT = 500 * 1000000LL; // 0.5sec
Michael Wrightd02c5b62014-02-10 15:10:22 -0800102
103// Amount of time to allow for an event to be dispatched (measured since its eventTime)
104// before considering it stale and dropping it.
Michael Wright2b3c3302018-03-02 17:19:13 +0000105constexpr nsecs_t STALE_EVENT_TIMEOUT = 10000 * 1000000LL; // 10sec
Michael Wrightd02c5b62014-02-10 15:10:22 -0800106
Michael Wrightd02c5b62014-02-10 15:10:22 -0800107// 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 +0000108constexpr nsecs_t SLOW_EVENT_PROCESSING_WARNING_TIMEOUT = 2000 * 1000000LL; // 2sec
109
110// Log a warning when an interception call takes longer than this to process.
111constexpr std::chrono::milliseconds SLOW_INTERCEPTION_THRESHOLD = 50ms;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800112
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700113// Additional key latency in case a connection is still processing some motion events.
114// This will help with the case when a user touched a button that opens a new window,
115// and gives us the chance to dispatch the key to this new window.
116constexpr std::chrono::nanoseconds KEY_WAITING_FOR_EVENTS_TIMEOUT = 500ms;
117
Michael Wrightd02c5b62014-02-10 15:10:22 -0800118// Number of recent events to keep for debugging purposes.
Michael Wright2b3c3302018-03-02 17:19:13 +0000119constexpr size_t RECENT_QUEUE_MAX_SIZE = 10;
120
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +0000121// Event log tags. See EventLogTags.logtags for reference
122constexpr int LOGTAG_INPUT_INTERACTION = 62000;
123constexpr int LOGTAG_INPUT_FOCUS = 62001;
124
Michael Wrightd02c5b62014-02-10 15:10:22 -0800125static inline nsecs_t now() {
126 return systemTime(SYSTEM_TIME_MONOTONIC);
127}
128
129static inline const char* toString(bool value) {
130 return value ? "true" : "false";
131}
132
Bernardo Rufino49d99e42021-01-18 15:16:59 +0000133static inline const std::string toString(sp<IBinder> binder) {
134 if (binder == nullptr) {
135 return "<null>";
136 }
137 return StringPrintf("%p", binder.get());
138}
139
Michael Wrightd02c5b62014-02-10 15:10:22 -0800140static inline int32_t getMotionEventActionPointerIndex(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700141 return (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) >>
142 AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800143}
144
145static bool isValidKeyAction(int32_t action) {
146 switch (action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700147 case AKEY_EVENT_ACTION_DOWN:
148 case AKEY_EVENT_ACTION_UP:
149 return true;
150 default:
151 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800152 }
153}
154
155static bool validateKeyEvent(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700156 if (!isValidKeyAction(action)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800157 ALOGE("Key event has invalid action code 0x%x", action);
158 return false;
159 }
160 return true;
161}
162
Michael Wright7b159c92015-05-14 14:48:03 +0100163static bool isValidMotionAction(int32_t action, int32_t actionButton, int32_t pointerCount) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800164 switch (action & AMOTION_EVENT_ACTION_MASK) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700165 case AMOTION_EVENT_ACTION_DOWN:
166 case AMOTION_EVENT_ACTION_UP:
167 case AMOTION_EVENT_ACTION_CANCEL:
168 case AMOTION_EVENT_ACTION_MOVE:
169 case AMOTION_EVENT_ACTION_OUTSIDE:
170 case AMOTION_EVENT_ACTION_HOVER_ENTER:
171 case AMOTION_EVENT_ACTION_HOVER_MOVE:
172 case AMOTION_EVENT_ACTION_HOVER_EXIT:
173 case AMOTION_EVENT_ACTION_SCROLL:
174 return true;
175 case AMOTION_EVENT_ACTION_POINTER_DOWN:
176 case AMOTION_EVENT_ACTION_POINTER_UP: {
177 int32_t index = getMotionEventActionPointerIndex(action);
178 return index >= 0 && index < pointerCount;
179 }
180 case AMOTION_EVENT_ACTION_BUTTON_PRESS:
181 case AMOTION_EVENT_ACTION_BUTTON_RELEASE:
182 return actionButton != 0;
183 default:
184 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800185 }
186}
187
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -0500188static int64_t millis(std::chrono::nanoseconds t) {
189 return std::chrono::duration_cast<std::chrono::milliseconds>(t).count();
190}
191
Michael Wright7b159c92015-05-14 14:48:03 +0100192static bool validateMotionEvent(int32_t action, int32_t actionButton, size_t pointerCount,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700193 const PointerProperties* pointerProperties) {
194 if (!isValidMotionAction(action, actionButton, pointerCount)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800195 ALOGE("Motion event has invalid action code 0x%x", action);
196 return false;
197 }
198 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
Narayan Kamath37764c72014-03-27 14:21:09 +0000199 ALOGE("Motion event has invalid pointer count %zu; value must be between 1 and %d.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700200 pointerCount, MAX_POINTERS);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800201 return false;
202 }
203 BitSet32 pointerIdBits;
204 for (size_t i = 0; i < pointerCount; i++) {
205 int32_t id = pointerProperties[i].id;
206 if (id < 0 || id > MAX_POINTER_ID) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700207 ALOGE("Motion event has invalid pointer id %d; value must be between 0 and %d", id,
208 MAX_POINTER_ID);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800209 return false;
210 }
211 if (pointerIdBits.hasBit(id)) {
212 ALOGE("Motion event has duplicate pointer id %d", id);
213 return false;
214 }
215 pointerIdBits.markBit(id);
216 }
217 return true;
218}
219
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000220static std::string dumpRegion(const Region& region) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800221 if (region.isEmpty()) {
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000222 return "<empty>";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800223 }
224
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000225 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800226 bool first = true;
227 Region::const_iterator cur = region.begin();
228 Region::const_iterator const tail = region.end();
229 while (cur != tail) {
230 if (first) {
231 first = false;
232 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800233 dump += "|";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800234 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800235 dump += StringPrintf("[%d,%d][%d,%d]", cur->left, cur->top, cur->right, cur->bottom);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800236 cur++;
237 }
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000238 return dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800239}
240
Siarhei Vishniakou14411c92020-09-18 21:15:05 -0500241static std::string dumpQueue(const std::deque<DispatchEntry*>& queue, nsecs_t currentTime) {
242 constexpr size_t maxEntries = 50; // max events to print
243 constexpr size_t skipBegin = maxEntries / 2;
244 const size_t skipEnd = queue.size() - maxEntries / 2;
245 // skip from maxEntries / 2 ... size() - maxEntries/2
246 // only print from 0 .. skipBegin and then from skipEnd .. size()
247
248 std::string dump;
249 for (size_t i = 0; i < queue.size(); i++) {
250 const DispatchEntry& entry = *queue[i];
251 if (i >= skipBegin && i < skipEnd) {
252 dump += StringPrintf(INDENT4 "<skipped %zu entries>\n", skipEnd - skipBegin);
253 i = skipEnd - 1; // it will be incremented to "skipEnd" by 'continue'
254 continue;
255 }
256 dump.append(INDENT4);
257 dump += entry.eventEntry->getDescription();
258 dump += StringPrintf(", seq=%" PRIu32
259 ", targetFlags=0x%08x, resolvedAction=%d, age=%" PRId64 "ms",
260 entry.seq, entry.targetFlags, entry.resolvedAction,
261 ns2ms(currentTime - entry.eventEntry->eventTime));
262 if (entry.deliveryTime != 0) {
263 // This entry was delivered, so add information on how long we've been waiting
264 dump += StringPrintf(", wait=%" PRId64 "ms", ns2ms(currentTime - entry.deliveryTime));
265 }
266 dump.append("\n");
267 }
268 return dump;
269}
270
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700271/**
272 * Find the entry in std::unordered_map by key, and return it.
273 * If the entry is not found, return a default constructed entry.
274 *
275 * Useful when the entries are vectors, since an empty vector will be returned
276 * if the entry is not found.
277 * Also useful when the entries are sp<>. If an entry is not found, nullptr is returned.
278 */
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700279template <typename K, typename V>
280static V getValueByKey(const std::unordered_map<K, V>& map, K key) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700281 auto it = map.find(key);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700282 return it != map.end() ? it->second : V{};
Tiger Huang721e26f2018-07-24 22:26:19 +0800283}
284
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700285/**
286 * Find the entry in std::unordered_map by value, and remove it.
287 * If more than one entry has the same value, then all matching
288 * key-value pairs will be removed.
289 *
290 * Return true if at least one value has been removed.
291 */
292template <typename K, typename V>
293static bool removeByValue(std::unordered_map<K, V>& map, const V& value) {
294 bool removed = false;
295 for (auto it = map.begin(); it != map.end();) {
296 if (it->second == value) {
297 it = map.erase(it);
298 removed = true;
299 } else {
300 it++;
301 }
302 }
303 return removed;
304}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800305
chaviwaf87b3e2019-10-01 16:59:28 -0700306static bool haveSameToken(const sp<InputWindowHandle>& first, const sp<InputWindowHandle>& second) {
307 if (first == second) {
308 return true;
309 }
310
311 if (first == nullptr || second == nullptr) {
312 return false;
313 }
314
315 return first->getToken() == second->getToken();
316}
317
Bernardo Rufino1ff9d592021-01-18 16:58:57 +0000318static bool haveSameApplicationToken(const InputWindowInfo* first, const InputWindowInfo* second) {
319 if (first == nullptr || second == nullptr) {
320 return false;
321 }
322 return first->applicationInfo.token != nullptr &&
323 first->applicationInfo.token == second->applicationInfo.token;
324}
325
Siarhei Vishniakouadfd4fa2019-12-20 11:02:58 -0800326static bool isStaleEvent(nsecs_t currentTime, const EventEntry& entry) {
327 return currentTime - entry.eventTime >= STALE_EVENT_TIMEOUT;
328}
329
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000330static std::unique_ptr<DispatchEntry> createDispatchEntry(const InputTarget& inputTarget,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700331 std::shared_ptr<EventEntry> eventEntry,
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000332 int32_t inputTargetFlags) {
yunho.shinf4a80b82020-11-16 21:13:57 +0900333 if (eventEntry->type == EventEntry::Type::MOTION) {
334 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
335 if (motionEntry.source & AINPUT_SOURCE_CLASS_JOYSTICK) {
336 const ui::Transform identityTransform;
337 // Use identity transform for joystick events events because they don't depend on
338 // the window info
339 return std::make_unique<DispatchEntry>(eventEntry, inputTargetFlags, identityTransform,
340 1.0f /*globalScaleFactor*/);
341 }
342 }
343
chaviw1ff3d1e2020-07-01 15:53:47 -0700344 if (inputTarget.useDefaultPointerTransform()) {
345 const ui::Transform& transform = inputTarget.getDefaultPointerTransform();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700346 return std::make_unique<DispatchEntry>(eventEntry, inputTargetFlags, transform,
chaviw1ff3d1e2020-07-01 15:53:47 -0700347 inputTarget.globalScaleFactor);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000348 }
349
350 ALOG_ASSERT(eventEntry->type == EventEntry::Type::MOTION);
351 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
352
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700353 std::vector<PointerCoords> pointerCoords;
354 pointerCoords.resize(motionEntry.pointerCount);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000355
356 // Use the first pointer information to normalize all other pointers. This could be any pointer
357 // as long as all other pointers are normalized to the same value and the final DispatchEntry
chaviw1ff3d1e2020-07-01 15:53:47 -0700358 // uses the transform for the normalized pointer.
359 const ui::Transform& firstPointerTransform =
360 inputTarget.pointerTransforms[inputTarget.pointerIds.firstMarkedBit()];
361 ui::Transform inverseFirstTransform = firstPointerTransform.inverse();
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000362
363 // Iterate through all pointers in the event to normalize against the first.
364 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.pointerCount; pointerIndex++) {
365 const PointerProperties& pointerProperties = motionEntry.pointerProperties[pointerIndex];
366 uint32_t pointerId = uint32_t(pointerProperties.id);
chaviw1ff3d1e2020-07-01 15:53:47 -0700367 const ui::Transform& currTransform = inputTarget.pointerTransforms[pointerId];
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000368
369 pointerCoords[pointerIndex].copyFrom(motionEntry.pointerCoords[pointerIndex]);
chaviw1ff3d1e2020-07-01 15:53:47 -0700370 // First, apply the current pointer's transform to update the coordinates into
371 // window space.
372 pointerCoords[pointerIndex].transform(currTransform);
373 // Next, apply the inverse transform of the normalized coordinates so the
374 // current coordinates are transformed into the normalized coordinate space.
375 pointerCoords[pointerIndex].transform(inverseFirstTransform);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000376 }
377
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700378 std::unique_ptr<MotionEntry> combinedMotionEntry =
379 std::make_unique<MotionEntry>(motionEntry.id, motionEntry.eventTime,
380 motionEntry.deviceId, motionEntry.source,
381 motionEntry.displayId, motionEntry.policyFlags,
382 motionEntry.action, motionEntry.actionButton,
383 motionEntry.flags, motionEntry.metaState,
384 motionEntry.buttonState, motionEntry.classification,
385 motionEntry.edgeFlags, motionEntry.xPrecision,
386 motionEntry.yPrecision, motionEntry.xCursorPosition,
387 motionEntry.yCursorPosition, motionEntry.downTime,
388 motionEntry.pointerCount, motionEntry.pointerProperties,
389 pointerCoords.data(), 0 /* xOffset */, 0 /* yOffset */);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000390
391 if (motionEntry.injectionState) {
392 combinedMotionEntry->injectionState = motionEntry.injectionState;
393 combinedMotionEntry->injectionState->refCount += 1;
394 }
395
396 std::unique_ptr<DispatchEntry> dispatchEntry =
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700397 std::make_unique<DispatchEntry>(std::move(combinedMotionEntry), inputTargetFlags,
398 firstPointerTransform, inputTarget.globalScaleFactor);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000399 return dispatchEntry;
400}
401
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -0700402static void addGestureMonitors(const std::vector<Monitor>& monitors,
403 std::vector<TouchedMonitor>& outTouchedMonitors, float xOffset = 0,
404 float yOffset = 0) {
405 if (monitors.empty()) {
406 return;
407 }
408 outTouchedMonitors.reserve(monitors.size() + outTouchedMonitors.size());
409 for (const Monitor& monitor : monitors) {
410 outTouchedMonitors.emplace_back(monitor, xOffset, yOffset);
411 }
412}
413
Garfield Tan15601662020-09-22 15:32:38 -0700414static status_t openInputChannelPair(const std::string& name,
415 std::shared_ptr<InputChannel>& serverChannel,
416 std::unique_ptr<InputChannel>& clientChannel) {
417 std::unique_ptr<InputChannel> uniqueServerChannel;
418 status_t result = InputChannel::openInputChannelPair(name, uniqueServerChannel, clientChannel);
419
420 serverChannel = std::move(uniqueServerChannel);
421 return result;
422}
423
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500424template <typename T>
425static bool sharedPointersEqual(const std::shared_ptr<T>& lhs, const std::shared_ptr<T>& rhs) {
426 if (lhs == nullptr && rhs == nullptr) {
427 return true;
428 }
429 if (lhs == nullptr || rhs == nullptr) {
430 return false;
431 }
432 return *lhs == *rhs;
433}
434
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000435static sp<IPlatformCompatNative> getCompatService() {
436 sp<IBinder> service(defaultServiceManager()->getService(String16("platform_compat_native")));
437 if (service == nullptr) {
438 ALOGE("Failed to link to compat service");
439 return nullptr;
440 }
441 return interface_cast<IPlatformCompatNative>(service);
442}
443
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +0000444static KeyEvent createKeyEvent(const KeyEntry& entry) {
445 KeyEvent event;
446 event.initialize(entry.id, entry.deviceId, entry.source, entry.displayId, INVALID_HMAC,
447 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
448 entry.repeatCount, entry.downTime, entry.eventTime);
449 return event;
450}
451
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000452static std::optional<int32_t> findMonitorPidByToken(
453 const std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay,
454 const sp<IBinder>& token) {
455 for (const auto& it : monitorsByDisplay) {
456 const std::vector<Monitor>& monitors = it.second;
457 for (const Monitor& monitor : monitors) {
458 if (monitor.inputChannel->getConnectionToken() == token) {
459 return monitor.pid;
460 }
461 }
462 }
463 return std::nullopt;
464}
465
Michael Wrightd02c5b62014-02-10 15:10:22 -0800466// --- InputDispatcher ---
467
Garfield Tan00f511d2019-06-12 16:55:40 -0700468InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy)
469 : mPolicy(policy),
470 mPendingEvent(nullptr),
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700471 mLastDropReason(DropReason::NOT_DROPPED),
Garfield Tanff1f1bb2020-01-28 13:24:04 -0800472 mIdGenerator(IdGenerator::Source::INPUT_DISPATCHER),
Garfield Tan00f511d2019-06-12 16:55:40 -0700473 mAppSwitchSawKeyDown(false),
474 mAppSwitchDueTime(LONG_LONG_MAX),
475 mNextUnblockedEvent(nullptr),
476 mDispatchEnabled(false),
477 mDispatchFrozen(false),
478 mInputFilterEnabled(false),
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -0800479 // mInTouchMode will be initialized by the WindowManager to the default device config.
480 // To avoid leaking stack in case that call never comes, and for tests,
481 // initialize it here anyways.
482 mInTouchMode(true),
Bernardo Rufinoea97d182020-08-19 14:43:14 +0100483 mMaximumObscuringOpacityForTouch(1.0f),
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000484 mFocusedDisplayId(ADISPLAY_ID_DEFAULT),
Prabir Pradhan99987712020-11-10 18:43:05 -0800485 mFocusedWindowRequestedPointerCapture(false),
486 mWindowTokenWithPointerCapture(nullptr),
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000487 mCompatService(getCompatService()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800488 mLooper = new Looper(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800489 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800490
Yi Kong9b14ac62018-07-17 13:48:38 -0700491 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800492
493 policy->getDispatcherConfiguration(&mConfig);
494}
495
496InputDispatcher::~InputDispatcher() {
497 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800498 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800499
500 resetKeyRepeatLocked();
501 releasePendingEventLocked();
502 drainInboundQueueLocked();
503 }
504
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700505 while (!mConnectionsByFd.empty()) {
506 sp<Connection> connection = mConnectionsByFd.begin()->second;
Garfield Tan15601662020-09-22 15:32:38 -0700507 removeInputChannel(connection->inputChannel->getConnectionToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800508 }
509}
510
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700511status_t InputDispatcher::start() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700512 if (mThread) {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700513 return ALREADY_EXISTS;
514 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700515 mThread = std::make_unique<InputThread>(
516 "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
517 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700518}
519
520status_t InputDispatcher::stop() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700521 if (mThread && mThread->isCallingThread()) {
522 ALOGE("InputDispatcher cannot be stopped from its own thread!");
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700523 return INVALID_OPERATION;
524 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700525 mThread.reset();
526 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700527}
528
Michael Wrightd02c5b62014-02-10 15:10:22 -0800529void InputDispatcher::dispatchOnce() {
530 nsecs_t nextWakeupTime = LONG_LONG_MAX;
531 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800532 std::scoped_lock _l(mLock);
533 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800534
535 // Run a dispatch loop if there are no pending commands.
536 // The dispatch loop might enqueue commands to run afterwards.
537 if (!haveCommandsLocked()) {
538 dispatchOnceInnerLocked(&nextWakeupTime);
539 }
540
541 // Run all pending commands if there are any.
542 // If any commands were run then force the next poll to wake up immediately.
543 if (runCommandsLockedInterruptible()) {
544 nextWakeupTime = LONG_LONG_MIN;
545 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800546
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700547 // If we are still waiting for ack on some events,
548 // we might have to wake up earlier to check if an app is anr'ing.
549 const nsecs_t nextAnrCheck = processAnrsLocked();
550 nextWakeupTime = std::min(nextWakeupTime, nextAnrCheck);
551
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800552 // We are about to enter an infinitely long sleep, because we have no commands or
553 // pending or queued events
554 if (nextWakeupTime == LONG_LONG_MAX) {
555 mDispatcherEnteredIdle.notify_all();
556 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800557 } // release lock
558
559 // Wait for callback or timeout or wake. (make sure we round up, not down)
560 nsecs_t currentTime = now();
561 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
562 mLooper->pollOnce(timeoutMillis);
563}
564
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700565/**
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500566 * Raise ANR if there is no focused window.
567 * Before the ANR is raised, do a final state check:
568 * 1. The currently focused application must be the same one we are waiting for.
569 * 2. Ensure we still don't have a focused window.
570 */
571void InputDispatcher::processNoFocusedWindowAnrLocked() {
572 // Check if the application that we are waiting for is still focused.
573 std::shared_ptr<InputApplicationHandle> focusedApplication =
574 getValueByKey(mFocusedApplicationHandlesByDisplay, mAwaitedApplicationDisplayId);
575 if (focusedApplication == nullptr ||
576 focusedApplication->getApplicationToken() !=
577 mAwaitedFocusedApplication->getApplicationToken()) {
578 // Unexpected because we should have reset the ANR timer when focused application changed
579 ALOGE("Waited for a focused window, but focused application has already changed to %s",
580 focusedApplication->getName().c_str());
581 return; // The focused application has changed.
582 }
583
584 const sp<InputWindowHandle>& focusedWindowHandle =
585 getFocusedWindowHandleLocked(mAwaitedApplicationDisplayId);
586 if (focusedWindowHandle != nullptr) {
587 return; // We now have a focused window. No need for ANR.
588 }
589 onAnrLocked(mAwaitedFocusedApplication);
590}
591
592/**
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700593 * Check if any of the connections' wait queues have events that are too old.
594 * If we waited for events to be ack'ed for more than the window timeout, raise an ANR.
595 * Return the time at which we should wake up next.
596 */
597nsecs_t InputDispatcher::processAnrsLocked() {
598 const nsecs_t currentTime = now();
599 nsecs_t nextAnrCheck = LONG_LONG_MAX;
600 // Check if we are waiting for a focused window to appear. Raise ANR if waited too long
601 if (mNoFocusedWindowTimeoutTime.has_value() && mAwaitedFocusedApplication != nullptr) {
602 if (currentTime >= *mNoFocusedWindowTimeoutTime) {
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500603 processNoFocusedWindowAnrLocked();
Chris Yea209fde2020-07-22 13:54:51 -0700604 mAwaitedFocusedApplication.reset();
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500605 mNoFocusedWindowTimeoutTime = std::nullopt;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700606 return LONG_LONG_MIN;
607 } else {
Siarhei Vishniakou38a6d272020-10-20 20:29:33 -0500608 // Keep waiting. We will drop the event when mNoFocusedWindowTimeoutTime comes.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700609 nextAnrCheck = *mNoFocusedWindowTimeoutTime;
610 }
611 }
612
613 // Check if any connection ANRs are due
614 nextAnrCheck = std::min(nextAnrCheck, mAnrTracker.firstTimeout());
615 if (currentTime < nextAnrCheck) { // most likely scenario
616 return nextAnrCheck; // everything is normal. Let's check again at nextAnrCheck
617 }
618
619 // If we reached here, we have an unresponsive connection.
620 sp<Connection> connection = getConnectionLocked(mAnrTracker.firstToken());
621 if (connection == nullptr) {
622 ALOGE("Could not find connection for entry %" PRId64, mAnrTracker.firstTimeout());
623 return nextAnrCheck;
624 }
625 connection->responsive = false;
626 // Stop waking up for this unresponsive connection
627 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000628 onAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700629 return LONG_LONG_MIN;
630}
631
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500632std::chrono::nanoseconds InputDispatcher::getDispatchingTimeoutLocked(const sp<IBinder>& token) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700633 sp<InputWindowHandle> window = getWindowHandleLocked(token);
634 if (window != nullptr) {
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500635 return window->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700636 }
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500637 return DEFAULT_INPUT_DISPATCHING_TIMEOUT;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700638}
639
Michael Wrightd02c5b62014-02-10 15:10:22 -0800640void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
641 nsecs_t currentTime = now();
642
Jeff Browndc5992e2014-04-11 01:27:26 -0700643 // Reset the key repeat timer whenever normal dispatch is suspended while the
644 // device is in a non-interactive state. This is to ensure that we abort a key
645 // repeat if the device is just coming out of sleep.
646 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800647 resetKeyRepeatLocked();
648 }
649
650 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
651 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +0100652 if (DEBUG_FOCUS) {
653 ALOGD("Dispatch frozen. Waiting some more.");
654 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800655 return;
656 }
657
658 // Optimize latency of app switches.
659 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
660 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
661 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
662 if (mAppSwitchDueTime < *nextWakeupTime) {
663 *nextWakeupTime = mAppSwitchDueTime;
664 }
665
666 // Ready to start a new event.
667 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700668 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700669 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800670 if (isAppSwitchDue) {
671 // The inbound queue is empty so the app switch key we were waiting
672 // for will never arrive. Stop waiting for it.
673 resetPendingAppSwitchLocked(false);
674 isAppSwitchDue = false;
675 }
676
677 // Synthesize a key repeat if appropriate.
678 if (mKeyRepeatState.lastKeyEntry) {
679 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
680 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
681 } else {
682 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
683 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
684 }
685 }
686 }
687
688 // Nothing to do if there is no pending event.
689 if (!mPendingEvent) {
690 return;
691 }
692 } else {
693 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700694 mPendingEvent = mInboundQueue.front();
695 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800696 traceInboundQueueLengthLocked();
697 }
698
699 // Poke user activity for this event.
700 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700701 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800702 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800703 }
704
705 // Now we have an event to dispatch.
706 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700707 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800708 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700709 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800710 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700711 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800712 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700713 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800714 }
715
716 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700717 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800718 }
719
720 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700721 case EventEntry::Type::CONFIGURATION_CHANGED: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700722 const ConfigurationChangedEntry& typedEntry =
723 static_cast<const ConfigurationChangedEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700724 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700725 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700726 break;
727 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800728
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700729 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700730 const DeviceResetEntry& typedEntry =
731 static_cast<const DeviceResetEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700732 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700733 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700734 break;
735 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800736
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100737 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700738 std::shared_ptr<FocusEntry> typedEntry =
739 std::static_pointer_cast<FocusEntry>(mPendingEvent);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100740 dispatchFocusLocked(currentTime, typedEntry);
741 done = true;
742 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
743 break;
744 }
745
Prabir Pradhan99987712020-11-10 18:43:05 -0800746 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
747 const auto typedEntry =
748 std::static_pointer_cast<PointerCaptureChangedEntry>(mPendingEvent);
749 dispatchPointerCaptureChangedLocked(currentTime, typedEntry, dropReason);
750 done = true;
751 break;
752 }
753
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700754 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700755 std::shared_ptr<KeyEntry> keyEntry = std::static_pointer_cast<KeyEntry>(mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700756 if (isAppSwitchDue) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700757 if (isAppSwitchKeyEvent(*keyEntry)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700758 resetPendingAppSwitchLocked(true);
759 isAppSwitchDue = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700760 } else if (dropReason == DropReason::NOT_DROPPED) {
761 dropReason = DropReason::APP_SWITCH;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700762 }
763 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700764 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *keyEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700765 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700766 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700767 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
768 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700769 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700770 done = dispatchKeyLocked(currentTime, keyEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700771 break;
772 }
773
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700774 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700775 std::shared_ptr<MotionEntry> motionEntry =
776 std::static_pointer_cast<MotionEntry>(mPendingEvent);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700777 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
778 dropReason = DropReason::APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800779 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700780 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *motionEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700781 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700782 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700783 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
784 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700785 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700786 done = dispatchMotionLocked(currentTime, motionEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700787 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800788 }
Chris Yef59a2f42020-10-16 12:55:26 -0700789
790 case EventEntry::Type::SENSOR: {
791 std::shared_ptr<SensorEntry> sensorEntry =
792 std::static_pointer_cast<SensorEntry>(mPendingEvent);
793 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
794 dropReason = DropReason::APP_SWITCH;
795 }
796 // Sensor timestamps use SYSTEM_TIME_BOOTTIME time base, so we can't use
797 // 'currentTime' here, get SYSTEM_TIME_BOOTTIME instead.
798 nsecs_t bootTime = systemTime(SYSTEM_TIME_BOOTTIME);
799 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(bootTime, *sensorEntry)) {
800 dropReason = DropReason::STALE;
801 }
802 dispatchSensorLocked(currentTime, sensorEntry, &dropReason, nextWakeupTime);
803 done = true;
804 break;
805 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800806 }
807
808 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700809 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700810 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800811 }
Michael Wright3a981722015-06-10 15:26:13 +0100812 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800813
814 releasePendingEventLocked();
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700815 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -0800816 }
817}
818
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700819/**
820 * Return true if the events preceding this incoming motion event should be dropped
821 * Return false otherwise (the default behaviour)
822 */
823bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700824 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700825 (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700826
827 // Optimize case where the current application is unresponsive and the user
828 // decides to touch a window in a different application.
829 // If the application takes too long to catch up then we drop all events preceding
830 // the touch into the other window.
831 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700832 int32_t displayId = motionEntry.displayId;
833 int32_t x = static_cast<int32_t>(
834 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
835 int32_t y = static_cast<int32_t>(
836 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
837 sp<InputWindowHandle> touchedWindowHandle =
838 findTouchedWindowAtLocked(displayId, x, y, nullptr);
839 if (touchedWindowHandle != nullptr &&
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700840 touchedWindowHandle->getApplicationToken() !=
841 mAwaitedFocusedApplication->getApplicationToken()) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700842 // User touched a different application than the one we are waiting on.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700843 ALOGI("Pruning input queue because user touched a different application while waiting "
844 "for %s",
845 mAwaitedFocusedApplication->getName().c_str());
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700846 return true;
847 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700848
849 // Alternatively, maybe there's a gesture monitor that could handle this event
850 std::vector<TouchedMonitor> gestureMonitors =
851 findTouchedGestureMonitorsLocked(displayId, {});
852 for (TouchedMonitor& gestureMonitor : gestureMonitors) {
853 sp<Connection> connection =
854 getConnectionLocked(gestureMonitor.monitor.inputChannel->getConnectionToken());
Siarhei Vishniakou34ed4d42020-06-18 00:43:02 +0000855 if (connection != nullptr && connection->responsive) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700856 // This monitor could take more input. Drop all events preceding this
857 // event, so that gesture monitor could get a chance to receive the stream
858 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
859 "responsive gesture monitor that may handle the event",
860 mAwaitedFocusedApplication->getName().c_str());
861 return true;
862 }
863 }
864 }
865
866 // Prevent getting stuck: if we have a pending key event, and some motion events that have not
867 // yet been processed by some connections, the dispatcher will wait for these motion
868 // events to be processed before dispatching the key event. This is because these motion events
869 // may cause a new window to be launched, which the user might expect to receive focus.
870 // To prevent waiting forever for such events, just send the key to the currently focused window
871 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
872 ALOGD("Received a new pointer down event, stop waiting for events to process and "
873 "just send the pending key event to the focused window.");
874 mKeyIsWaitingForEventsTimeout = now();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700875 }
876 return false;
877}
878
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700879bool InputDispatcher::enqueueInboundEventLocked(std::unique_ptr<EventEntry> newEntry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700880 bool needWake = mInboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700881 mInboundQueue.push_back(std::move(newEntry));
882 EventEntry& entry = *(mInboundQueue.back());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800883 traceInboundQueueLengthLocked();
884
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700885 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700886 case EventEntry::Type::KEY: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700887 // Optimize app switch latency.
888 // If the application takes too long to catch up then we drop all events preceding
889 // the app switch key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700890 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700891 if (isAppSwitchKeyEvent(keyEntry)) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700892 if (keyEntry.action == AKEY_EVENT_ACTION_DOWN) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700893 mAppSwitchSawKeyDown = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700894 } else if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700895 if (mAppSwitchSawKeyDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800896#if DEBUG_APP_SWITCH
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700897 ALOGD("App switch is pending!");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800898#endif
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700899 mAppSwitchDueTime = keyEntry.eventTime + APP_SWITCH_TIMEOUT;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700900 mAppSwitchSawKeyDown = false;
901 needWake = true;
902 }
903 }
904 }
905 break;
906 }
907
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700908 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700909 if (shouldPruneInboundQueueLocked(static_cast<MotionEntry&>(entry))) {
910 mNextUnblockedEvent = mInboundQueue.back();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700911 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800912 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700913 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800914 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100915 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700916 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
917 break;
918 }
919 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -0800920 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -0700921 case EventEntry::Type::SENSOR:
Prabir Pradhan99987712020-11-10 18:43:05 -0800922 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700923 // nothing to do
924 break;
925 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800926 }
927
928 return needWake;
929}
930
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700931void InputDispatcher::addRecentEventLocked(std::shared_ptr<EventEntry> entry) {
Chris Yef59a2f42020-10-16 12:55:26 -0700932 // Do not store sensor event in recent queue to avoid flooding the queue.
933 if (entry->type != EventEntry::Type::SENSOR) {
934 mRecentQueue.push_back(entry);
935 }
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700936 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700937 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800938 }
939}
940
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700941sp<InputWindowHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, int32_t x,
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700942 int32_t y, TouchState* touchState,
943 bool addOutsideTargets,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700944 bool addPortalWindows) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700945 if ((addPortalWindows || addOutsideTargets) && touchState == nullptr) {
946 LOG_ALWAYS_FATAL(
947 "Must provide a valid touch state if adding portal windows or outside targets");
948 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800949 // Traverse windows from front to back to find touched window.
Vishnu Nairad321cd2020-08-20 16:40:21 -0700950 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800951 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800952 const InputWindowInfo* windowInfo = windowHandle->getInfo();
953 if (windowInfo->displayId == displayId) {
Michael Wright44753b12020-07-08 13:48:11 +0100954 auto flags = windowInfo->flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800955
956 if (windowInfo->visible) {
Michael Wright44753b12020-07-08 13:48:11 +0100957 if (!flags.test(InputWindowInfo::Flag::NOT_TOUCHABLE)) {
958 bool isTouchModal = !flags.test(InputWindowInfo::Flag::NOT_FOCUSABLE) &&
959 !flags.test(InputWindowInfo::Flag::NOT_TOUCH_MODAL);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800960 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800961 int32_t portalToDisplayId = windowInfo->portalToDisplayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700962 if (portalToDisplayId != ADISPLAY_ID_NONE &&
963 portalToDisplayId != displayId) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800964 if (addPortalWindows) {
965 // For the monitoring channels of the display.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700966 touchState->addPortalWindow(windowHandle);
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800967 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700968 return findTouchedWindowAtLocked(portalToDisplayId, x, y, touchState,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700969 addOutsideTargets, addPortalWindows);
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800970 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800971 // Found window.
972 return windowHandle;
973 }
974 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800975
Michael Wright44753b12020-07-08 13:48:11 +0100976 if (addOutsideTargets && flags.test(InputWindowInfo::Flag::WATCH_OUTSIDE_TOUCH)) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700977 touchState->addOrUpdateWindow(windowHandle,
978 InputTarget::FLAG_DISPATCH_AS_OUTSIDE,
979 BitSet32(0));
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800980 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800981 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800982 }
983 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700984 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800985}
986
Garfield Tane84e6f92019-08-29 17:28:41 -0700987std::vector<TouchedMonitor> InputDispatcher::findTouchedGestureMonitorsLocked(
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -0700988 int32_t displayId, const std::vector<sp<InputWindowHandle>>& portalWindows) const {
Michael Wright3dd60e22019-03-27 22:06:44 +0000989 std::vector<TouchedMonitor> touchedMonitors;
990
991 std::vector<Monitor> monitors = getValueByKey(mGestureMonitorsByDisplay, displayId);
992 addGestureMonitors(monitors, touchedMonitors);
993 for (const sp<InputWindowHandle>& portalWindow : portalWindows) {
994 const InputWindowInfo* windowInfo = portalWindow->getInfo();
995 monitors = getValueByKey(mGestureMonitorsByDisplay, windowInfo->portalToDisplayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700996 addGestureMonitors(monitors, touchedMonitors, -windowInfo->frameLeft,
997 -windowInfo->frameTop);
Michael Wright3dd60e22019-03-27 22:06:44 +0000998 }
999 return touchedMonitors;
1000}
1001
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001002void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001003 const char* reason;
1004 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001005 case DropReason::POLICY:
Michael Wrightd02c5b62014-02-10 15:10:22 -08001006#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001007 ALOGD("Dropped event because policy consumed it.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001008#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001009 reason = "inbound event was dropped because the policy consumed it";
1010 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001011 case DropReason::DISABLED:
1012 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001013 ALOGI("Dropped event because input dispatch is disabled.");
1014 }
1015 reason = "inbound event was dropped because input dispatch is disabled";
1016 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001017 case DropReason::APP_SWITCH:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001018 ALOGI("Dropped event because of pending overdue app switch.");
1019 reason = "inbound event was dropped because of pending overdue app switch";
1020 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001021 case DropReason::BLOCKED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001022 ALOGI("Dropped event because the current application is not responding and the user "
1023 "has started interacting with a different application.");
1024 reason = "inbound event was dropped because the current application is not responding "
1025 "and the user has started interacting with a different application";
1026 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001027 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001028 ALOGI("Dropped event because it is stale.");
1029 reason = "inbound event was dropped because it is stale";
1030 break;
Prabir Pradhan99987712020-11-10 18:43:05 -08001031 case DropReason::NO_POINTER_CAPTURE:
1032 ALOGI("Dropped event because there is no window with Pointer Capture.");
1033 reason = "inbound event was dropped because there is no window with Pointer Capture";
1034 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001035 case DropReason::NOT_DROPPED: {
1036 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001037 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001038 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001039 }
1040
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001041 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001042 case EventEntry::Type::KEY: {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001043 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
1044 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001045 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001046 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001047 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001048 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1049 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001050 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
1051 synthesizeCancelationEventsForAllConnectionsLocked(options);
1052 } else {
1053 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
1054 synthesizeCancelationEventsForAllConnectionsLocked(options);
1055 }
1056 break;
1057 }
Chris Yef59a2f42020-10-16 12:55:26 -07001058 case EventEntry::Type::SENSOR: {
1059 break;
1060 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001061 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
1062 break;
1063 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001064 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001065 case EventEntry::Type::CONFIGURATION_CHANGED:
1066 case EventEntry::Type::DEVICE_RESET: {
Chris Yef59a2f42020-10-16 12:55:26 -07001067 LOG_ALWAYS_FATAL("Should not drop %s events", NamedEnum::string(entry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001068 break;
1069 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001070 }
1071}
1072
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001073static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001074 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
1075 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001076}
1077
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001078bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
1079 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
1080 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
1081 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001082}
1083
1084bool InputDispatcher::isAppSwitchPendingLocked() {
1085 return mAppSwitchDueTime != LONG_LONG_MAX;
1086}
1087
1088void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
1089 mAppSwitchDueTime = LONG_LONG_MAX;
1090
1091#if DEBUG_APP_SWITCH
1092 if (handled) {
1093 ALOGD("App switch has arrived.");
1094 } else {
1095 ALOGD("App switch was abandoned.");
1096 }
1097#endif
1098}
1099
Michael Wrightd02c5b62014-02-10 15:10:22 -08001100bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001101 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001102}
1103
1104bool InputDispatcher::runCommandsLockedInterruptible() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001105 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001106 return false;
1107 }
1108
1109 do {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001110 std::unique_ptr<CommandEntry> commandEntry = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001111 mCommandQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001112 Command command = commandEntry->command;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001113 command(*this, commandEntry.get()); // commands are implicitly 'LockedInterruptible'
Michael Wrightd02c5b62014-02-10 15:10:22 -08001114
1115 commandEntry->connection.clear();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001116 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001117 return true;
1118}
1119
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001120void InputDispatcher::postCommandLocked(std::unique_ptr<CommandEntry> commandEntry) {
1121 mCommandQueue.push_back(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001122}
1123
1124void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001125 while (!mInboundQueue.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001126 std::shared_ptr<EventEntry> entry = mInboundQueue.front();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001127 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001128 releaseInboundEventLocked(entry);
1129 }
1130 traceInboundQueueLengthLocked();
1131}
1132
1133void InputDispatcher::releasePendingEventLocked() {
1134 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001135 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -07001136 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001137 }
1138}
1139
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001140void InputDispatcher::releaseInboundEventLocked(std::shared_ptr<EventEntry> entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001141 InjectionState* injectionState = entry->injectionState;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001142 if (injectionState && injectionState->injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001143#if DEBUG_DISPATCH_CYCLE
1144 ALOGD("Injected inbound event was dropped.");
1145#endif
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001146 setInjectionResult(*entry, InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001147 }
1148 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001149 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001150 }
1151 addRecentEventLocked(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001152}
1153
1154void InputDispatcher::resetKeyRepeatLocked() {
1155 if (mKeyRepeatState.lastKeyEntry) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001156 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001157 }
1158}
1159
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001160std::shared_ptr<KeyEntry> InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
1161 std::shared_ptr<KeyEntry> entry = mKeyRepeatState.lastKeyEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001162
Michael Wright2e732952014-09-24 13:26:59 -07001163 uint32_t policyFlags = entry->policyFlags &
1164 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001165
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001166 std::shared_ptr<KeyEntry> newEntry =
1167 std::make_unique<KeyEntry>(mIdGenerator.nextId(), currentTime, entry->deviceId,
1168 entry->source, entry->displayId, policyFlags, entry->action,
1169 entry->flags, entry->keyCode, entry->scanCode,
1170 entry->metaState, entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001171
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001172 newEntry->syntheticRepeat = true;
1173 mKeyRepeatState.lastKeyEntry = newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001174 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001175 return newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001176}
1177
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001178bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001179 const ConfigurationChangedEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001180#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001181 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry.eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001182#endif
1183
1184 // Reset key repeating in case a keyboard device was added or removed or something.
1185 resetKeyRepeatLocked();
1186
1187 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001188 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
1189 &InputDispatcher::doNotifyConfigurationChangedLockedInterruptible);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001190 commandEntry->eventTime = entry.eventTime;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001191 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001192 return true;
1193}
1194
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001195bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime,
1196 const DeviceResetEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001197#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001198 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry.eventTime,
1199 entry.deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001200#endif
1201
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001202 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, "device was reset");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001203 options.deviceId = entry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001204 synthesizeCancelationEventsForAllConnectionsLocked(options);
1205 return true;
1206}
1207
Vishnu Nairad321cd2020-08-20 16:40:21 -07001208void InputDispatcher::enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus,
Vishnu Nairc519ff72021-01-21 08:23:08 -08001209 const std::string& reason) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001210 if (mPendingEvent != nullptr) {
1211 // Move the pending event to the front of the queue. This will give the chance
1212 // for the pending event to get dispatched to the newly focused window
1213 mInboundQueue.push_front(mPendingEvent);
1214 mPendingEvent = nullptr;
1215 }
1216
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001217 std::unique_ptr<FocusEntry> focusEntry =
1218 std::make_unique<FocusEntry>(mIdGenerator.nextId(), now(), windowToken, hasFocus,
1219 reason);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001220
1221 // This event should go to the front of the queue, but behind all other focus events
1222 // Find the last focus event, and insert right after it
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001223 std::deque<std::shared_ptr<EventEntry>>::reverse_iterator it =
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001224 std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001225 [](const std::shared_ptr<EventEntry>& event) {
1226 return event->type == EventEntry::Type::FOCUS;
1227 });
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001228
1229 // Maintain the order of focus events. Insert the entry after all other focus events.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001230 mInboundQueue.insert(it.base(), std::move(focusEntry));
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001231}
1232
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001233void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime, std::shared_ptr<FocusEntry> entry) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05001234 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001235 if (channel == nullptr) {
1236 return; // Window has gone away
1237 }
1238 InputTarget target;
1239 target.inputChannel = channel;
1240 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1241 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001242 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
1243 channel->getName();
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001244 std::string reason = std::string("reason=").append(entry->reason);
1245 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001246 dispatchEventLocked(currentTime, entry, {target});
1247}
1248
Prabir Pradhan99987712020-11-10 18:43:05 -08001249void InputDispatcher::dispatchPointerCaptureChangedLocked(
1250 nsecs_t currentTime, const std::shared_ptr<PointerCaptureChangedEntry>& entry,
1251 DropReason& dropReason) {
1252 const bool haveWindowWithPointerCapture = mWindowTokenWithPointerCapture != nullptr;
Prabir Pradhan167e6d92021-02-04 16:18:17 -08001253 if (entry->pointerCaptureEnabled && haveWindowWithPointerCapture) {
1254 LOG_ALWAYS_FATAL("Pointer Capture has already been enabled for the window.");
1255 }
1256 if (!entry->pointerCaptureEnabled && !haveWindowWithPointerCapture) {
Prabir Pradhan99987712020-11-10 18:43:05 -08001257 // Pointer capture was already forcefully disabled because of focus change.
1258 dropReason = DropReason::NOT_DROPPED;
1259 return;
1260 }
1261
1262 // Set drop reason for early returns
1263 dropReason = DropReason::NO_POINTER_CAPTURE;
1264
1265 sp<IBinder> token;
1266 if (entry->pointerCaptureEnabled) {
1267 // Enable Pointer Capture
1268 if (!mFocusedWindowRequestedPointerCapture) {
1269 // This can happen if a window requests capture and immediately releases capture.
1270 ALOGW("No window requested Pointer Capture.");
1271 return;
1272 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08001273 token = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08001274 LOG_ALWAYS_FATAL_IF(!token, "Cannot find focused window for Pointer Capture.");
1275 mWindowTokenWithPointerCapture = token;
1276 } else {
1277 // Disable Pointer Capture
1278 token = mWindowTokenWithPointerCapture;
1279 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan7d030382020-12-21 07:58:35 -08001280 if (mFocusedWindowRequestedPointerCapture) {
1281 mFocusedWindowRequestedPointerCapture = false;
1282 setPointerCaptureLocked(false);
1283 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001284 }
1285
1286 auto channel = getInputChannelLocked(token);
1287 if (channel == nullptr) {
1288 // Window has gone away, clean up Pointer Capture state.
1289 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan7d030382020-12-21 07:58:35 -08001290 if (mFocusedWindowRequestedPointerCapture) {
1291 mFocusedWindowRequestedPointerCapture = false;
1292 setPointerCaptureLocked(false);
1293 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001294 return;
1295 }
1296 InputTarget target;
1297 target.inputChannel = channel;
1298 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1299 entry->dispatchInProgress = true;
1300 dispatchEventLocked(currentTime, entry, {target});
1301
1302 dropReason = DropReason::NOT_DROPPED;
1303}
1304
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001305bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, std::shared_ptr<KeyEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001306 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001307 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001308 if (!entry->dispatchInProgress) {
1309 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1310 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1311 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1312 if (mKeyRepeatState.lastKeyEntry &&
Chris Ye2ad95392020-09-01 13:44:44 -07001313 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode &&
Michael Wrightd02c5b62014-02-10 15:10:22 -08001314 // We have seen two identical key downs in a row which indicates that the device
1315 // driver is automatically generating key repeats itself. We take note of the
1316 // repeat here, but we disable our own next key repeat timer since it is clear that
1317 // we will not need to synthesize key repeats ourselves.
Chris Ye2ad95392020-09-01 13:44:44 -07001318 mKeyRepeatState.lastKeyEntry->deviceId == entry->deviceId) {
1319 // Make sure we don't get key down from a different device. If a different
1320 // device Id has same key pressed down, the new device Id will replace the
1321 // current one to hold the key repeat with repeat count reset.
1322 // In the future when got a KEY_UP on the device id, drop it and do not
1323 // stop the key repeat on current device.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001324 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1325 resetKeyRepeatLocked();
1326 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
1327 } else {
1328 // Not a repeat. Save key down state in case we do see a repeat later.
1329 resetKeyRepeatLocked();
1330 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1331 }
1332 mKeyRepeatState.lastKeyEntry = entry;
Chris Ye2ad95392020-09-01 13:44:44 -07001333 } else if (entry->action == AKEY_EVENT_ACTION_UP && mKeyRepeatState.lastKeyEntry &&
1334 mKeyRepeatState.lastKeyEntry->deviceId != entry->deviceId) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001335 // The key on device 'deviceId' is still down, do not stop key repeat
Chris Ye2ad95392020-09-01 13:44:44 -07001336#if DEBUG_INBOUND_EVENT_DETAILS
1337 ALOGD("deviceId=%d got KEY_UP as stale", entry->deviceId);
1338#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001339 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001340 resetKeyRepeatLocked();
1341 }
1342
1343 if (entry->repeatCount == 1) {
1344 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1345 } else {
1346 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1347 }
1348
1349 entry->dispatchInProgress = true;
1350
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001351 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001352 }
1353
1354 // Handle case where the policy asked us to try again later last time.
1355 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
1356 if (currentTime < entry->interceptKeyWakeupTime) {
1357 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1358 *nextWakeupTime = entry->interceptKeyWakeupTime;
1359 }
1360 return false; // wait until next wakeup
1361 }
1362 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
1363 entry->interceptKeyWakeupTime = 0;
1364 }
1365
1366 // Give the policy a chance to intercept the key.
1367 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
1368 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001369 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
Siarhei Vishniakou49a350a2019-07-26 18:44:23 -07001370 &InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible);
Vishnu Nairad321cd2020-08-20 16:40:21 -07001371 sp<IBinder> focusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08001372 mFocusResolver.getFocusedWindowToken(getTargetDisplayId(*entry));
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06001373 commandEntry->connectionToken = focusedWindowToken;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001374 commandEntry->keyEntry = entry;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001375 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001376 return false; // wait for the command to run
1377 } else {
1378 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
1379 }
1380 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001381 if (*dropReason == DropReason::NOT_DROPPED) {
1382 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001383 }
1384 }
1385
1386 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001387 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001388 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001389 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1390 : InputEventInjectionResult::FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001391 mReporter->reportDroppedKey(entry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001392 return true;
1393 }
1394
1395 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001396 std::vector<InputTarget> inputTargets;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001397 InputEventInjectionResult injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001398 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001399 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001400 return false;
1401 }
1402
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001403 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001404 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001405 return true;
1406 }
1407
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001408 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001409 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001410
1411 // Dispatch the key.
1412 dispatchEventLocked(currentTime, entry, inputTargets);
1413 return true;
1414}
1415
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001416void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001417#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01001418 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001419 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1420 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001421 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1422 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
1423 entry.repeatCount, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001424#endif
1425}
1426
Chris Yef59a2f42020-10-16 12:55:26 -07001427void InputDispatcher::doNotifySensorLockedInterruptible(CommandEntry* commandEntry) {
1428 mLock.unlock();
1429
1430 const std::shared_ptr<SensorEntry>& entry = commandEntry->sensorEntry;
1431 if (entry->accuracyChanged) {
1432 mPolicy->notifySensorAccuracy(entry->deviceId, entry->sensorType, entry->accuracy);
1433 }
1434 mPolicy->notifySensorEvent(entry->deviceId, entry->sensorType, entry->accuracy,
1435 entry->hwTimestamp, entry->values);
1436 mLock.lock();
1437}
1438
1439void InputDispatcher::dispatchSensorLocked(nsecs_t currentTime, std::shared_ptr<SensorEntry> entry,
1440 DropReason* dropReason, nsecs_t* nextWakeupTime) {
1441#if DEBUG_OUTBOUND_EVENT_DETAILS
1442 ALOGD("notifySensorEvent eventTime=%" PRId64 ", hwTimestamp=%" PRId64 ", deviceId=%d, "
1443 "source=0x%x, sensorType=%s",
1444 entry->eventTime, entry->hwTimestamp, entry->deviceId, entry->source,
1445 NamedEnum::string(sensorType).c_str());
1446#endif
1447 std::unique_ptr<CommandEntry> commandEntry =
1448 std::make_unique<CommandEntry>(&InputDispatcher::doNotifySensorLockedInterruptible);
1449 commandEntry->sensorEntry = entry;
1450 postCommandLocked(std::move(commandEntry));
1451}
1452
1453bool InputDispatcher::flushSensor(int deviceId, InputDeviceSensorType sensorType) {
1454#if DEBUG_OUTBOUND_EVENT_DETAILS
1455 ALOGD("flushSensor deviceId=%d, sensorType=%s", deviceId,
1456 NamedEnum::string(sensorType).c_str());
1457#endif
1458 { // acquire lock
1459 std::scoped_lock _l(mLock);
1460
1461 for (auto it = mInboundQueue.begin(); it != mInboundQueue.end(); it++) {
1462 std::shared_ptr<EventEntry> entry = *it;
1463 if (entry->type == EventEntry::Type::SENSOR) {
1464 it = mInboundQueue.erase(it);
1465 releaseInboundEventLocked(entry);
1466 }
1467 }
1468 }
1469 return true;
1470}
1471
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001472bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, std::shared_ptr<MotionEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001473 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001474 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001475 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001476 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001477 entry->dispatchInProgress = true;
1478
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001479 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001480 }
1481
1482 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001483 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001484 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001485 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1486 : InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001487 return true;
1488 }
1489
1490 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
1491
1492 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001493 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001494
1495 bool conflictingPointerActions = false;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001496 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001497 if (isPointerEvent) {
1498 // Pointer event. (eg. touchscreen)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001499 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001500 findTouchedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001501 &conflictingPointerActions);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001502 } else {
1503 // Non touch event. (eg. trackball)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001504 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001505 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001506 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001507 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001508 return false;
1509 }
1510
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001511 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001512 if (injectionResult == InputEventInjectionResult::PERMISSION_DENIED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001513 ALOGW("Permission denied, dropping the motion (isPointer=%s)", toString(isPointerEvent));
1514 return true;
1515 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001516 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001517 CancelationOptions::Mode mode(isPointerEvent
1518 ? CancelationOptions::CANCEL_POINTER_EVENTS
1519 : CancelationOptions::CANCEL_NON_POINTER_EVENTS);
1520 CancelationOptions options(mode, "input event injection failed");
1521 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001522 return true;
1523 }
1524
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001525 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001526 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001527
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001528 if (isPointerEvent) {
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07001529 std::unordered_map<int32_t, TouchState>::iterator it =
1530 mTouchStatesByDisplay.find(entry->displayId);
1531 if (it != mTouchStatesByDisplay.end()) {
1532 const TouchState& state = it->second;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001533 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001534 // The event has gone through these portal windows, so we add monitoring targets of
1535 // the corresponding displays as well.
1536 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001537 const InputWindowInfo* windowInfo = state.portalWindows[i]->getInfo();
Michael Wright3dd60e22019-03-27 22:06:44 +00001538 addGlobalMonitoringTargetsLocked(inputTargets, windowInfo->portalToDisplayId,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001539 -windowInfo->frameLeft, -windowInfo->frameTop);
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001540 }
1541 }
1542 }
1543 }
1544
Michael Wrightd02c5b62014-02-10 15:10:22 -08001545 // Dispatch the motion.
1546 if (conflictingPointerActions) {
1547 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001548 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001549 synthesizeCancelationEventsForAllConnectionsLocked(options);
1550 }
1551 dispatchEventLocked(currentTime, entry, inputTargets);
1552 return true;
1553}
1554
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001555void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001556#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08001557 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001558 ", policyFlags=0x%x, "
1559 "action=0x%x, actionButton=0x%x, flags=0x%x, "
1560 "metaState=0x%x, buttonState=0x%x,"
1561 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001562 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1563 entry.action, entry.actionButton, entry.flags, entry.metaState, entry.buttonState,
1564 entry.edgeFlags, entry.xPrecision, entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001565
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001566 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001567 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001568 "x=%f, y=%f, pressure=%f, size=%f, "
1569 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1570 "orientation=%f",
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001571 i, entry.pointerProperties[i].id, entry.pointerProperties[i].toolType,
1572 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1573 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1574 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1575 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1576 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1577 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1578 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1579 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1580 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001581 }
1582#endif
1583}
1584
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001585void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
1586 std::shared_ptr<EventEntry> eventEntry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001587 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001588 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001589#if DEBUG_DISPATCH_CYCLE
1590 ALOGD("dispatchEventToCurrentInputTargets");
1591#endif
1592
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001593 updateInteractionTokensLocked(*eventEntry, inputTargets);
1594
Michael Wrightd02c5b62014-02-10 15:10:22 -08001595 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1596
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001597 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001598
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001599 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001600 sp<Connection> connection =
1601 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001602 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08001603 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001604 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001605 if (DEBUG_FOCUS) {
1606 ALOGD("Dropping event delivery to target with channel '%s' because it "
1607 "is no longer registered with the input dispatcher.",
1608 inputTarget.inputChannel->getName().c_str());
1609 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001610 }
1611 }
1612}
1613
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001614void InputDispatcher::cancelEventsForAnrLocked(const sp<Connection>& connection) {
1615 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
1616 // If the policy decides to close the app, we will get a channel removal event via
1617 // unregisterInputChannel, and will clean up the connection that way. We are already not
1618 // sending new pointers to the connection when it blocked, but focused events will continue to
1619 // pile up.
1620 ALOGW("Canceling events for %s because it is unresponsive",
1621 connection->inputChannel->getName().c_str());
1622 if (connection->status == Connection::STATUS_NORMAL) {
1623 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1624 "application not responding");
1625 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001626 }
1627}
1628
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001629void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001630 if (DEBUG_FOCUS) {
1631 ALOGD("Resetting ANR timeouts.");
1632 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001633
1634 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001635 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07001636 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001637}
1638
Tiger Huang721e26f2018-07-24 22:26:19 +08001639/**
1640 * Get the display id that the given event should go to. If this event specifies a valid display id,
1641 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1642 * Focused display is the display that the user most recently interacted with.
1643 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001644int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001645 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001646 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001647 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001648 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1649 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001650 break;
1651 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001652 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001653 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1654 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001655 break;
1656 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001657 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001658 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001659 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07001660 case EventEntry::Type::DEVICE_RESET:
1661 case EventEntry::Type::SENSOR: {
1662 ALOGE("%s events do not have a target display", NamedEnum::string(entry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001663 return ADISPLAY_ID_NONE;
1664 }
Tiger Huang721e26f2018-07-24 22:26:19 +08001665 }
1666 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1667}
1668
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001669bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
1670 const char* focusedWindowName) {
1671 if (mAnrTracker.empty()) {
1672 // already processed all events that we waited for
1673 mKeyIsWaitingForEventsTimeout = std::nullopt;
1674 return false;
1675 }
1676
1677 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
1678 // Start the timer
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00001679 // Wait to send key because there are unprocessed events that may cause focus to change
Siarhei Vishniakou70622952020-07-30 11:17:23 -05001680 mKeyIsWaitingForEventsTimeout = currentTime +
1681 std::chrono::duration_cast<std::chrono::nanoseconds>(KEY_WAITING_FOR_EVENTS_TIMEOUT)
1682 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001683 return true;
1684 }
1685
1686 // We still have pending events, and already started the timer
1687 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
1688 return true; // Still waiting
1689 }
1690
1691 // Waited too long, and some connection still hasn't processed all motions
1692 // Just send the key to the focused window
1693 ALOGW("Dispatching key to %s even though there are other unprocessed events",
1694 focusedWindowName);
1695 mKeyIsWaitingForEventsTimeout = std::nullopt;
1696 return false;
1697}
1698
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001699InputEventInjectionResult InputDispatcher::findFocusedWindowTargetsLocked(
1700 nsecs_t currentTime, const EventEntry& entry, std::vector<InputTarget>& inputTargets,
1701 nsecs_t* nextWakeupTime) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001702 std::string reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001703
Tiger Huang721e26f2018-07-24 22:26:19 +08001704 int32_t displayId = getTargetDisplayId(entry);
Vishnu Nairad321cd2020-08-20 16:40:21 -07001705 sp<InputWindowHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07001706 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08001707 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1708
Michael Wrightd02c5b62014-02-10 15:10:22 -08001709 // If there is no currently focused window and no focused application
1710 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001711 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
1712 ALOGI("Dropping %s event because there is no focused window or focused application in "
1713 "display %" PRId32 ".",
Chris Yef59a2f42020-10-16 12:55:26 -07001714 NamedEnum::string(entry.type).c_str(), displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001715 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001716 }
1717
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001718 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
1719 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
1720 // start interacting with another application via touch (app switch). This code can be removed
1721 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
1722 // an app is expected to have a focused window.
1723 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
1724 if (!mNoFocusedWindowTimeoutTime.has_value()) {
1725 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001726 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
1727 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
1728 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001729 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05001730 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001731 ALOGW("Waiting because no window has focus but %s may eventually add a "
1732 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001733 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001734 *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001735 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001736 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
1737 // Already raised ANR. Drop the event
1738 ALOGE("Dropping %s event because there is no focused window",
Chris Yef59a2f42020-10-16 12:55:26 -07001739 NamedEnum::string(entry.type).c_str());
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001740 return InputEventInjectionResult::FAILED;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001741 } else {
1742 // Still waiting for the focused window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001743 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001744 }
1745 }
1746
1747 // we have a valid, non-null focused window
1748 resetNoFocusedWindowTimeoutLocked();
1749
Michael Wrightd02c5b62014-02-10 15:10:22 -08001750 // Check permissions.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001751 if (!checkInjectionPermission(focusedWindowHandle, entry.injectionState)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001752 return InputEventInjectionResult::PERMISSION_DENIED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001753 }
1754
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001755 if (focusedWindowHandle->getInfo()->paused) {
1756 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001757 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001758 }
1759
1760 // If the event is a key event, then we must wait for all previous events to
1761 // complete before delivering it because previous events may have the
1762 // side-effect of transferring focus to a different window and we want to
1763 // ensure that the following keys are sent to the new window.
1764 //
1765 // Suppose the user touches a button in a window then immediately presses "A".
1766 // If the button causes a pop-up window to appear then we want to ensure that
1767 // the "A" key is delivered to the new pop-up window. This is because users
1768 // often anticipate pending UI changes when typing on a keyboard.
1769 // To obtain this behavior, we must serialize key events with respect to all
1770 // prior input events.
1771 if (entry.type == EventEntry::Type::KEY) {
1772 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
1773 *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001774 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001775 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001776 }
1777
1778 // Success! Output targets.
Tiger Huang721e26f2018-07-24 22:26:19 +08001779 addWindowTargetLocked(focusedWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001780 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS,
1781 BitSet32(0), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001782
1783 // Done.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001784 return InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001785}
1786
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001787/**
1788 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
1789 * that are currently unresponsive.
1790 */
1791std::vector<TouchedMonitor> InputDispatcher::selectResponsiveMonitorsLocked(
1792 const std::vector<TouchedMonitor>& monitors) const {
1793 std::vector<TouchedMonitor> responsiveMonitors;
1794 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
1795 [this](const TouchedMonitor& monitor) REQUIRES(mLock) {
1796 sp<Connection> connection = getConnectionLocked(
1797 monitor.monitor.inputChannel->getConnectionToken());
1798 if (connection == nullptr) {
1799 ALOGE("Could not find connection for monitor %s",
1800 monitor.monitor.inputChannel->getName().c_str());
1801 return false;
1802 }
1803 if (!connection->responsive) {
1804 ALOGW("Unresponsive monitor %s will not get the new gesture",
1805 connection->inputChannel->getName().c_str());
1806 return false;
1807 }
1808 return true;
1809 });
1810 return responsiveMonitors;
1811}
1812
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001813InputEventInjectionResult InputDispatcher::findTouchedWindowTargetsLocked(
1814 nsecs_t currentTime, const MotionEntry& entry, std::vector<InputTarget>& inputTargets,
1815 nsecs_t* nextWakeupTime, bool* outConflictingPointerActions) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001816 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001817 enum InjectionPermission {
1818 INJECTION_PERMISSION_UNKNOWN,
1819 INJECTION_PERMISSION_GRANTED,
1820 INJECTION_PERMISSION_DENIED
1821 };
1822
Michael Wrightd02c5b62014-02-10 15:10:22 -08001823 // For security reasons, we defer updating the touch state until we are sure that
1824 // event injection will be allowed.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001825 int32_t displayId = entry.displayId;
1826 int32_t action = entry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001827 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
1828
1829 // Update the touch state as needed based on the properties of the touch event.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001830 InputEventInjectionResult injectionResult = InputEventInjectionResult::PENDING;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001831 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
Garfield Tandf26e862020-07-01 20:18:19 -07001832 sp<InputWindowHandle> newHoverWindowHandle(mLastHoverWindowHandle);
1833 sp<InputWindowHandle> newTouchedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001834
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001835 // Copy current touch state into tempTouchState.
1836 // This state will be used to update mTouchStatesByDisplay at the end of this function.
1837 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07001838 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001839 TouchState tempTouchState;
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07001840 std::unordered_map<int32_t, TouchState>::iterator oldStateIt =
1841 mTouchStatesByDisplay.find(displayId);
1842 if (oldStateIt != mTouchStatesByDisplay.end()) {
1843 oldState = &(oldStateIt->second);
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001844 tempTouchState.copyFrom(*oldState);
Jeff Brownf086ddb2014-02-11 14:28:48 -08001845 }
1846
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001847 bool isSplit = tempTouchState.split;
1848 bool switchedDevice = tempTouchState.deviceId >= 0 && tempTouchState.displayId >= 0 &&
1849 (tempTouchState.deviceId != entry.deviceId || tempTouchState.source != entry.source ||
1850 tempTouchState.displayId != displayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001851 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
1852 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
1853 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
1854 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN ||
1855 maskedAction == AMOTION_EVENT_ACTION_SCROLL || isHoverAction);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001856 const bool isFromMouse = entry.source == AINPUT_SOURCE_MOUSE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001857 bool wrongDevice = false;
1858 if (newGesture) {
1859 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001860 if (switchedDevice && tempTouchState.down && !down && !isHoverAction) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001861 ALOGI("Dropping event because a pointer for a different device is already down "
1862 "in display %" PRId32,
1863 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001864 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001865 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001866 switchedDevice = false;
1867 wrongDevice = true;
1868 goto Failed;
1869 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001870 tempTouchState.reset();
1871 tempTouchState.down = down;
1872 tempTouchState.deviceId = entry.deviceId;
1873 tempTouchState.source = entry.source;
1874 tempTouchState.displayId = displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001875 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001876 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001877 ALOGI("Dropping move event because a pointer for a different device is already active "
1878 "in display %" PRId32,
1879 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001880 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001881 injectionResult = InputEventInjectionResult::PERMISSION_DENIED;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001882 switchedDevice = false;
1883 wrongDevice = true;
1884 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001885 }
1886
1887 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
1888 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
1889
Garfield Tan00f511d2019-06-12 16:55:40 -07001890 int32_t x;
1891 int32_t y;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001892 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Garfield Tan00f511d2019-06-12 16:55:40 -07001893 // Always dispatch mouse events to cursor position.
1894 if (isFromMouse) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001895 x = int32_t(entry.xCursorPosition);
1896 y = int32_t(entry.yCursorPosition);
Garfield Tan00f511d2019-06-12 16:55:40 -07001897 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001898 x = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X));
1899 y = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y));
Garfield Tan00f511d2019-06-12 16:55:40 -07001900 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001901 bool isDown = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Garfield Tandf26e862020-07-01 20:18:19 -07001902 newTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001903 findTouchedWindowAtLocked(displayId, x, y, &tempTouchState,
1904 isDown /*addOutsideTargets*/, true /*addPortalWindows*/);
Michael Wright3dd60e22019-03-27 22:06:44 +00001905
1906 std::vector<TouchedMonitor> newGestureMonitors = isDown
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001907 ? findTouchedGestureMonitorsLocked(displayId, tempTouchState.portalWindows)
Michael Wright3dd60e22019-03-27 22:06:44 +00001908 : std::vector<TouchedMonitor>{};
Michael Wrightd02c5b62014-02-10 15:10:22 -08001909
Michael Wrightd02c5b62014-02-10 15:10:22 -08001910 // Figure out whether splitting will be allowed for this window.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001911 if (newTouchedWindowHandle != nullptr &&
1912 newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Garfield Tanaddb02b2019-06-25 16:36:13 -07001913 // New window supports splitting, but we should never split mouse events.
1914 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001915 } else if (isSplit) {
1916 // New window does not support splitting but we have already split events.
1917 // Ignore the new window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001918 newTouchedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001919 }
1920
1921 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001922 if (newTouchedWindowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001923 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001924 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001925 }
1926
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001927 if (newTouchedWindowHandle != nullptr && newTouchedWindowHandle->getInfo()->paused) {
1928 ALOGI("Not sending touch event to %s because it is paused",
1929 newTouchedWindowHandle->getName().c_str());
1930 newTouchedWindowHandle = nullptr;
1931 }
1932
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001933 // Ensure the window has a connection and the connection is responsive
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001934 if (newTouchedWindowHandle != nullptr) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001935 const bool isResponsive = hasResponsiveConnectionLocked(*newTouchedWindowHandle);
1936 if (!isResponsive) {
1937 ALOGW("%s will not receive the new gesture at %" PRIu64,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001938 newTouchedWindowHandle->getName().c_str(), entry.eventTime);
1939 newTouchedWindowHandle = nullptr;
1940 }
1941 }
1942
Bernardo Rufinoea97d182020-08-19 14:43:14 +01001943 // Drop events that can't be trusted due to occlusion
1944 if (newTouchedWindowHandle != nullptr &&
1945 mBlockUntrustedTouchesMode != BlockUntrustedTouchesMode::DISABLED) {
1946 TouchOcclusionInfo occlusionInfo =
1947 computeTouchOcclusionInfoLocked(newTouchedWindowHandle, x, y);
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00001948 if (!isTouchTrustedLocked(occlusionInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00001949 if (DEBUG_TOUCH_OCCLUSION) {
1950 ALOGD("Stack of obscuring windows during untrusted touch (%d, %d):", x, y);
1951 for (const auto& log : occlusionInfo.debugInfo) {
1952 ALOGD("%s", log.c_str());
1953 }
1954 }
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00001955 onUntrustedTouchLocked(occlusionInfo.obscuringPackage);
1956 if (mBlockUntrustedTouchesMode == BlockUntrustedTouchesMode::BLOCK) {
1957 ALOGW("Dropping untrusted touch event due to %s/%d",
1958 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid);
1959 newTouchedWindowHandle = nullptr;
1960 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01001961 }
1962 }
1963
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001964 // Also don't send the new touch event to unresponsive gesture monitors
1965 newGestureMonitors = selectResponsiveMonitorsLocked(newGestureMonitors);
1966
Michael Wright3dd60e22019-03-27 22:06:44 +00001967 if (newTouchedWindowHandle == nullptr && newGestureMonitors.empty()) {
1968 ALOGI("Dropping event because there is no touchable window or gesture monitor at "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001969 "(%d, %d) in display %" PRId32 ".",
1970 x, y, displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001971 injectionResult = InputEventInjectionResult::FAILED;
Michael Wright3dd60e22019-03-27 22:06:44 +00001972 goto Failed;
1973 }
1974
1975 if (newTouchedWindowHandle != nullptr) {
1976 // Set target flags.
1977 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
1978 if (isSplit) {
1979 targetFlags |= InputTarget::FLAG_SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001980 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001981 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1982 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1983 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
1984 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1985 }
1986
1987 // Update hover state.
Garfield Tandf26e862020-07-01 20:18:19 -07001988 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
1989 newHoverWindowHandle = nullptr;
1990 } else if (isHoverAction) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001991 newHoverWindowHandle = newTouchedWindowHandle;
Michael Wright3dd60e22019-03-27 22:06:44 +00001992 }
1993
1994 // Update the temporary touch state.
1995 BitSet32 pointerIds;
1996 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001997 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wright3dd60e22019-03-27 22:06:44 +00001998 pointerIds.markBit(pointerId);
1999 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002000 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002001 }
2002
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002003 tempTouchState.addGestureMonitors(newGestureMonitors);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002004 } else {
2005 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
2006
2007 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002008 if (!tempTouchState.down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002009 if (DEBUG_FOCUS) {
2010 ALOGD("Dropping event because the pointer is not down or we previously "
2011 "dropped the pointer down event in display %" PRId32,
2012 displayId);
2013 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002014 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002015 goto Failed;
2016 }
2017
2018 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002019 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002020 tempTouchState.isSlippery()) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002021 int32_t x = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
2022 int32_t y = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002023
2024 sp<InputWindowHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002025 tempTouchState.getFirstForegroundWindowHandle();
Garfield Tandf26e862020-07-01 20:18:19 -07002026 newTouchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y, &tempTouchState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002027 if (oldTouchedWindowHandle != newTouchedWindowHandle &&
2028 oldTouchedWindowHandle != nullptr && newTouchedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002029 if (DEBUG_FOCUS) {
2030 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
2031 oldTouchedWindowHandle->getName().c_str(),
2032 newTouchedWindowHandle->getName().c_str(), displayId);
2033 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002034 // Make a slippery exit from the old window.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002035 tempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
2036 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT,
2037 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002038
2039 // Make a slippery entrance into the new window.
2040 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
2041 isSplit = true;
2042 }
2043
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002044 int32_t targetFlags =
2045 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002046 if (isSplit) {
2047 targetFlags |= InputTarget::FLAG_SPLIT;
2048 }
2049 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
2050 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002051 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
2052 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002053 }
2054
2055 BitSet32 pointerIds;
2056 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002057 pointerIds.markBit(entry.pointerProperties[0].id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002058 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002059 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002060 }
2061 }
2062 }
2063
2064 if (newHoverWindowHandle != mLastHoverWindowHandle) {
Garfield Tandf26e862020-07-01 20:18:19 -07002065 // Let the previous window know that the hover sequence is over, unless we already did it
2066 // when dispatching it as is to newTouchedWindowHandle.
2067 if (mLastHoverWindowHandle != nullptr &&
2068 (maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT ||
2069 mLastHoverWindowHandle != newTouchedWindowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002070#if DEBUG_HOVER
2071 ALOGD("Sending hover exit event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002072 mLastHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002073#endif
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002074 tempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
2075 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002076 }
2077
Garfield Tandf26e862020-07-01 20:18:19 -07002078 // Let the new window know that the hover sequence is starting, unless we already did it
2079 // when dispatching it as is to newTouchedWindowHandle.
2080 if (newHoverWindowHandle != nullptr &&
2081 (maskedAction != AMOTION_EVENT_ACTION_HOVER_ENTER ||
2082 newHoverWindowHandle != newTouchedWindowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002083#if DEBUG_HOVER
2084 ALOGD("Sending hover enter event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002085 newHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002086#endif
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002087 tempTouchState.addOrUpdateWindow(newHoverWindowHandle,
2088 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER,
2089 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002090 }
2091 }
2092
2093 // Check permission to inject into all touched foreground windows and ensure there
2094 // is at least one touched foreground window.
2095 {
2096 bool haveForegroundWindow = false;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002097 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002098 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
2099 haveForegroundWindow = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002100 if (!checkInjectionPermission(touchedWindow.windowHandle, entry.injectionState)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002101 injectionResult = InputEventInjectionResult::PERMISSION_DENIED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002102 injectionPermission = INJECTION_PERMISSION_DENIED;
2103 goto Failed;
2104 }
2105 }
2106 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002107 bool hasGestureMonitor = !tempTouchState.gestureMonitors.empty();
Michael Wright3dd60e22019-03-27 22:06:44 +00002108 if (!haveForegroundWindow && !hasGestureMonitor) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002109 ALOGI("Dropping event because there is no touched foreground window in display "
2110 "%" PRId32 " or gesture monitor to receive it.",
2111 displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002112 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002113 goto Failed;
2114 }
2115
2116 // Permission granted to injection into all touched foreground windows.
2117 injectionPermission = INJECTION_PERMISSION_GRANTED;
2118 }
2119
2120 // Check whether windows listening for outside touches are owned by the same UID. If it is
2121 // set the policy flag that we will not reveal coordinate information to this window.
2122 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2123 sp<InputWindowHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002124 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002125 if (foregroundWindowHandle) {
2126 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002127 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002128 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2129 sp<InputWindowHandle> inputWindowHandle = touchedWindow.windowHandle;
2130 if (inputWindowHandle->getInfo()->ownerUid != foregroundWindowUid) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002131 tempTouchState.addOrUpdateWindow(inputWindowHandle,
2132 InputTarget::FLAG_ZERO_COORDS,
2133 BitSet32(0));
Michael Wright3dd60e22019-03-27 22:06:44 +00002134 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002135 }
2136 }
2137 }
2138 }
2139
Michael Wrightd02c5b62014-02-10 15:10:22 -08002140 // If this is the first pointer going down and the touched window has a wallpaper
2141 // then also add the touched wallpaper windows so they are locked in for the duration
2142 // of the touch gesture.
2143 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
2144 // engine only supports touch events. We would need to add a mechanism similar
2145 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
2146 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2147 sp<InputWindowHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002148 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002149 if (foregroundWindowHandle && foregroundWindowHandle->getInfo()->hasWallpaper) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07002150 const std::vector<sp<InputWindowHandle>>& windowHandles =
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002151 getWindowHandlesLocked(displayId);
2152 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002153 const InputWindowInfo* info = windowHandle->getInfo();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002154 if (info->displayId == displayId &&
Michael Wright44753b12020-07-08 13:48:11 +01002155 windowHandle->getInfo()->type == InputWindowInfo::Type::WALLPAPER) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002156 tempTouchState
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002157 .addOrUpdateWindow(windowHandle,
2158 InputTarget::FLAG_WINDOW_IS_OBSCURED |
2159 InputTarget::
2160 FLAG_WINDOW_IS_PARTIALLY_OBSCURED |
2161 InputTarget::FLAG_DISPATCH_AS_IS,
2162 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002163 }
2164 }
2165 }
2166 }
2167
2168 // Success! Output targets.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002169 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002170
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002171 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002172 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002173 touchedWindow.pointerIds, inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002174 }
2175
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002176 for (const TouchedMonitor& touchedMonitor : tempTouchState.gestureMonitors) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002177 addMonitoringTargetLocked(touchedMonitor.monitor, touchedMonitor.xOffset,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002178 touchedMonitor.yOffset, inputTargets);
Michael Wright3dd60e22019-03-27 22:06:44 +00002179 }
2180
Michael Wrightd02c5b62014-02-10 15:10:22 -08002181 // Drop the outside or hover touch windows since we will not care about them
2182 // in the next iteration.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002183 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002184
2185Failed:
2186 // Check injection permission once and for all.
2187 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002188 if (checkInjectionPermission(nullptr, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002189 injectionPermission = INJECTION_PERMISSION_GRANTED;
2190 } else {
2191 injectionPermission = INJECTION_PERMISSION_DENIED;
2192 }
2193 }
2194
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002195 if (injectionPermission != INJECTION_PERMISSION_GRANTED) {
2196 return injectionResult;
2197 }
2198
Michael Wrightd02c5b62014-02-10 15:10:22 -08002199 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002200 if (!wrongDevice) {
2201 if (switchedDevice) {
2202 if (DEBUG_FOCUS) {
2203 ALOGD("Conflicting pointer actions: Switched to a different device.");
2204 }
2205 *outConflictingPointerActions = true;
2206 }
2207
2208 if (isHoverAction) {
2209 // Started hovering, therefore no longer down.
2210 if (oldState && oldState->down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002211 if (DEBUG_FOCUS) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002212 ALOGD("Conflicting pointer actions: Hover received while pointer was "
2213 "down.");
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002214 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002215 *outConflictingPointerActions = true;
2216 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002217 tempTouchState.reset();
2218 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2219 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
2220 tempTouchState.deviceId = entry.deviceId;
2221 tempTouchState.source = entry.source;
2222 tempTouchState.displayId = displayId;
2223 }
2224 } else if (maskedAction == AMOTION_EVENT_ACTION_UP ||
2225 maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
2226 // All pointers up or canceled.
2227 tempTouchState.reset();
2228 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2229 // First pointer went down.
2230 if (oldState && oldState->down) {
2231 if (DEBUG_FOCUS) {
2232 ALOGD("Conflicting pointer actions: Down received while already down.");
2233 }
2234 *outConflictingPointerActions = true;
2235 }
2236 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2237 // One pointer went up.
2238 if (isSplit) {
2239 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2240 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002241
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002242 for (size_t i = 0; i < tempTouchState.windows.size();) {
2243 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2244 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
2245 touchedWindow.pointerIds.clearBit(pointerId);
2246 if (touchedWindow.pointerIds.isEmpty()) {
2247 tempTouchState.windows.erase(tempTouchState.windows.begin() + i);
2248 continue;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002249 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002250 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002251 i += 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002252 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002253 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002254 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002255
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002256 // Save changes unless the action was scroll in which case the temporary touch
2257 // state was only valid for this one action.
2258 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
2259 if (tempTouchState.displayId >= 0) {
2260 mTouchStatesByDisplay[displayId] = tempTouchState;
2261 } else {
2262 mTouchStatesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002263 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002264 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002265
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002266 // Update hover state.
2267 mLastHoverWindowHandle = newHoverWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002268 }
2269
Michael Wrightd02c5b62014-02-10 15:10:22 -08002270 return injectionResult;
2271}
2272
2273void InputDispatcher::addWindowTargetLocked(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002274 int32_t targetFlags, BitSet32 pointerIds,
2275 std::vector<InputTarget>& inputTargets) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002276 std::vector<InputTarget>::iterator it =
2277 std::find_if(inputTargets.begin(), inputTargets.end(),
2278 [&windowHandle](const InputTarget& inputTarget) {
2279 return inputTarget.inputChannel->getConnectionToken() ==
2280 windowHandle->getToken();
2281 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002282
Chavi Weingarten114b77f2020-01-15 22:35:10 +00002283 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002284
2285 if (it == inputTargets.end()) {
2286 InputTarget inputTarget;
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05002287 std::shared_ptr<InputChannel> inputChannel =
2288 getInputChannelLocked(windowHandle->getToken());
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002289 if (inputChannel == nullptr) {
2290 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
2291 return;
2292 }
2293 inputTarget.inputChannel = inputChannel;
2294 inputTarget.flags = targetFlags;
2295 inputTarget.globalScaleFactor = windowInfo->globalScaleFactor;
2296 inputTargets.push_back(inputTarget);
2297 it = inputTargets.end() - 1;
2298 }
2299
2300 ALOG_ASSERT(it->flags == targetFlags);
2301 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
2302
chaviw1ff3d1e2020-07-01 15:53:47 -07002303 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002304}
2305
Michael Wright3dd60e22019-03-27 22:06:44 +00002306void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002307 int32_t displayId, float xOffset,
2308 float yOffset) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002309 std::unordered_map<int32_t, std::vector<Monitor>>::const_iterator it =
2310 mGlobalMonitorsByDisplay.find(displayId);
2311
2312 if (it != mGlobalMonitorsByDisplay.end()) {
2313 const std::vector<Monitor>& monitors = it->second;
2314 for (const Monitor& monitor : monitors) {
2315 addMonitoringTargetLocked(monitor, xOffset, yOffset, inputTargets);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002316 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002317 }
2318}
2319
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002320void InputDispatcher::addMonitoringTargetLocked(const Monitor& monitor, float xOffset,
2321 float yOffset,
2322 std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002323 InputTarget target;
2324 target.inputChannel = monitor.inputChannel;
2325 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
chaviw1ff3d1e2020-07-01 15:53:47 -07002326 ui::Transform t;
2327 t.set(xOffset, yOffset);
2328 target.setDefaultPointerTransform(t);
Michael Wright3dd60e22019-03-27 22:06:44 +00002329 inputTargets.push_back(target);
2330}
2331
Michael Wrightd02c5b62014-02-10 15:10:22 -08002332bool InputDispatcher::checkInjectionPermission(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002333 const InjectionState* injectionState) {
2334 if (injectionState &&
2335 (windowHandle == nullptr ||
2336 windowHandle->getInfo()->ownerUid != injectionState->injectorUid) &&
2337 !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002338 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002339 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002340 "owned by uid %d",
2341 injectionState->injectorPid, injectionState->injectorUid,
2342 windowHandle->getName().c_str(), windowHandle->getInfo()->ownerUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002343 } else {
2344 ALOGW("Permission denied: injecting event from pid %d uid %d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002345 injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002346 }
2347 return false;
2348 }
2349 return true;
2350}
2351
Robert Carrc9bf1d32020-04-13 17:21:08 -07002352/**
2353 * Indicate whether one window handle should be considered as obscuring
2354 * another window handle. We only check a few preconditions. Actually
2355 * checking the bounds is left to the caller.
2356 */
2357static bool canBeObscuredBy(const sp<InputWindowHandle>& windowHandle,
2358 const sp<InputWindowHandle>& otherHandle) {
2359 // Compare by token so cloned layers aren't counted
2360 if (haveSameToken(windowHandle, otherHandle)) {
2361 return false;
2362 }
2363 auto info = windowHandle->getInfo();
2364 auto otherInfo = otherHandle->getInfo();
2365 if (!otherInfo->visible) {
2366 return false;
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002367 } else if (otherInfo->alpha == 0 &&
2368 otherInfo->flags.test(InputWindowInfo::Flag::NOT_TOUCHABLE)) {
2369 // Those act as if they were invisible, so we don't need to flag them.
2370 // We do want to potentially flag touchable windows even if they have 0
2371 // opacity, since they can consume touches and alter the effects of the
2372 // user interaction (eg. apps that rely on
2373 // FLAG_WINDOW_IS_PARTIALLY_OBSCURED should still be told about those
2374 // windows), hence we also check for FLAG_NOT_TOUCHABLE.
2375 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00002376 } else if (info->ownerUid == otherInfo->ownerUid) {
2377 // If ownerUid is the same we don't generate occlusion events as there
2378 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002379 return false;
Chris Yefcdff3e2020-05-10 15:16:04 -07002380 } else if (otherInfo->trustedOverlay) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002381 return false;
2382 } else if (otherInfo->displayId != info->displayId) {
2383 return false;
2384 }
2385 return true;
2386}
2387
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002388/**
2389 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
2390 * untrusted, one should check:
2391 *
2392 * 1. If result.hasBlockingOcclusion is true.
2393 * If it's, it means the touch should be blocked due to a window with occlusion mode of
2394 * BLOCK_UNTRUSTED.
2395 *
2396 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
2397 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
2398 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
2399 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
2400 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
2401 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
2402 *
2403 * If neither of those is true, then it means the touch can be allowed.
2404 */
2405InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
2406 const sp<InputWindowHandle>& windowHandle, int32_t x, int32_t y) const {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002407 const InputWindowInfo* windowInfo = windowHandle->getInfo();
2408 int32_t displayId = windowInfo->displayId;
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002409 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2410 TouchOcclusionInfo info;
2411 info.hasBlockingOcclusion = false;
2412 info.obscuringOpacity = 0;
2413 info.obscuringUid = -1;
2414 std::map<int32_t, float> opacityByUid;
2415 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
2416 if (windowHandle == otherHandle) {
2417 break; // All future windows are below us. Exit early.
2418 }
2419 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Bernardo Rufino1ff9d592021-01-18 16:58:57 +00002420 if (canBeObscuredBy(windowHandle, otherHandle) && otherInfo->frameContainsPoint(x, y) &&
2421 !haveSameApplicationToken(windowInfo, otherInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002422 if (DEBUG_TOUCH_OCCLUSION) {
2423 info.debugInfo.push_back(
2424 dumpWindowForTouchOcclusion(otherInfo, /* isTouchedWindow */ false));
2425 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002426 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
2427 // we perform the checks below to see if the touch can be propagated or not based on the
2428 // window's touch occlusion mode
2429 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
2430 info.hasBlockingOcclusion = true;
2431 info.obscuringUid = otherInfo->ownerUid;
2432 info.obscuringPackage = otherInfo->packageName;
2433 break;
2434 }
2435 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
2436 uint32_t uid = otherInfo->ownerUid;
2437 float opacity =
2438 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
2439 // Given windows A and B:
2440 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
2441 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
2442 opacityByUid[uid] = opacity;
2443 if (opacity > info.obscuringOpacity) {
2444 info.obscuringOpacity = opacity;
2445 info.obscuringUid = uid;
2446 info.obscuringPackage = otherInfo->packageName;
2447 }
2448 }
2449 }
2450 }
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002451 if (DEBUG_TOUCH_OCCLUSION) {
2452 info.debugInfo.push_back(
2453 dumpWindowForTouchOcclusion(windowInfo, /* isTouchedWindow */ true));
2454 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002455 return info;
2456}
2457
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002458std::string InputDispatcher::dumpWindowForTouchOcclusion(const InputWindowInfo* info,
2459 bool isTouchedWindow) const {
Bernardo Rufino49d99e42021-01-18 15:16:59 +00002460 return StringPrintf(INDENT2
2461 "* %stype=%s, package=%s/%" PRId32 ", id=%" PRId32 ", mode=%s, alpha=%.2f, "
2462 "frame=[%" PRId32 ",%" PRId32 "][%" PRId32 ",%" PRId32
2463 "], touchableRegion=%s, window={%s}, flags={%s}, inputFeatures={%s}, "
2464 "hasToken=%s, applicationInfo.name=%s, applicationInfo.token=%s\n",
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002465 (isTouchedWindow) ? "[TOUCHED] " : "",
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00002466 NamedEnum::string(info->type, "%" PRId32).c_str(),
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00002467 info->packageName.c_str(), info->ownerUid, info->id,
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00002468 toString(info->touchOcclusionMode).c_str(), info->alpha, info->frameLeft,
2469 info->frameTop, info->frameRight, info->frameBottom,
2470 dumpRegion(info->touchableRegion).c_str(), info->name.c_str(),
Bernardo Rufino49d99e42021-01-18 15:16:59 +00002471 info->flags.string().c_str(), info->inputFeatures.string().c_str(),
2472 toString(info->token != nullptr), info->applicationInfo.name.c_str(),
2473 toString(info->applicationInfo.token).c_str());
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002474}
2475
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002476bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
2477 if (occlusionInfo.hasBlockingOcclusion) {
2478 ALOGW("Untrusted touch due to occlusion by %s/%d", occlusionInfo.obscuringPackage.c_str(),
2479 occlusionInfo.obscuringUid);
2480 return false;
2481 }
2482 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
2483 ALOGW("Untrusted touch due to occlusion by %s/%d (obscuring opacity = "
2484 "%.2f, maximum allowed = %.2f)",
2485 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid,
2486 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
2487 return false;
2488 }
2489 return true;
2490}
2491
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002492bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<InputWindowHandle>& windowHandle,
2493 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002494 int32_t displayId = windowHandle->getInfo()->displayId;
Vishnu Nairad321cd2020-08-20 16:40:21 -07002495 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002496 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002497 if (windowHandle == otherHandle) {
2498 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002499 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002500 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002501 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002502 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002503 return true;
2504 }
2505 }
2506 return false;
2507}
2508
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002509bool InputDispatcher::isWindowObscuredLocked(const sp<InputWindowHandle>& windowHandle) const {
2510 int32_t displayId = windowHandle->getInfo()->displayId;
Vishnu Nairad321cd2020-08-20 16:40:21 -07002511 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002512 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002513 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002514 if (windowHandle == otherHandle) {
2515 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002516 }
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002517 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002518 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002519 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002520 return true;
2521 }
2522 }
2523 return false;
2524}
2525
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002526std::string InputDispatcher::getApplicationWindowLabel(
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05002527 const InputApplicationHandle* applicationHandle,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002528 const sp<InputWindowHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002529 if (applicationHandle != nullptr) {
2530 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002531 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002532 } else {
2533 return applicationHandle->getName();
2534 }
Yi Kong9b14ac62018-07-17 13:48:38 -07002535 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002536 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002537 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002538 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002539 }
2540}
2541
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002542void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Prabir Pradhan99987712020-11-10 18:43:05 -08002543 if (eventEntry.type == EventEntry::Type::FOCUS ||
2544 eventEntry.type == EventEntry::Type::POINTER_CAPTURE_CHANGED) {
2545 // Focus or pointer capture changed events are passed to apps, but do not represent user
2546 // activity.
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002547 return;
2548 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002549 int32_t displayId = getTargetDisplayId(eventEntry);
Vishnu Nairad321cd2020-08-20 16:40:21 -07002550 sp<InputWindowHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Tiger Huang721e26f2018-07-24 22:26:19 +08002551 if (focusedWindowHandle != nullptr) {
2552 const InputWindowInfo* info = focusedWindowHandle->getInfo();
Michael Wright44753b12020-07-08 13:48:11 +01002553 if (info->inputFeatures.test(InputWindowInfo::Feature::DISABLE_USER_ACTIVITY)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002554#if DEBUG_DISPATCH_CYCLE
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002555 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002556#endif
2557 return;
2558 }
2559 }
2560
2561 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002562 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002563 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002564 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
2565 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002566 return;
2567 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002568
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002569 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002570 eventType = USER_ACTIVITY_EVENT_TOUCH;
2571 }
2572 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002573 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002574 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002575 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
2576 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002577 return;
2578 }
2579 eventType = USER_ACTIVITY_EVENT_BUTTON;
2580 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002581 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002582 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002583 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08002584 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07002585 case EventEntry::Type::SENSOR:
Prabir Pradhan99987712020-11-10 18:43:05 -08002586 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002587 LOG_ALWAYS_FATAL("%s events are not user activity",
Chris Yef59a2f42020-10-16 12:55:26 -07002588 NamedEnum::string(eventEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002589 break;
2590 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002591 }
2592
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002593 std::unique_ptr<CommandEntry> commandEntry =
2594 std::make_unique<CommandEntry>(&InputDispatcher::doPokeUserActivityLockedInterruptible);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002595 commandEntry->eventTime = eventEntry.eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002596 commandEntry->userActivityEventType = eventType;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002597 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002598}
2599
2600void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002601 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002602 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002603 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002604 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002605 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002606 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002607 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002608 ATRACE_NAME(message.c_str());
2609 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002610#if DEBUG_DISPATCH_CYCLE
2611 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002612 "globalScaleFactor=%f, pointerIds=0x%x %s",
2613 connection->getInputChannelName().c_str(), inputTarget.flags,
2614 inputTarget.globalScaleFactor, inputTarget.pointerIds.value,
2615 inputTarget.getPointerInfoString().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002616#endif
2617
2618 // Skip this event if the connection status is not normal.
2619 // We don't want to enqueue additional outbound events if the connection is broken.
2620 if (connection->status != Connection::STATUS_NORMAL) {
2621#if DEBUG_DISPATCH_CYCLE
2622 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002623 connection->getInputChannelName().c_str(), connection->getStatusLabel());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002624#endif
2625 return;
2626 }
2627
2628 // Split a motion event if needed.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002629 if (inputTarget.flags & InputTarget::FLAG_SPLIT) {
2630 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
2631 "Entry type %s should not have FLAG_SPLIT",
Chris Yef59a2f42020-10-16 12:55:26 -07002632 NamedEnum::string(eventEntry->type).c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002633
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002634 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002635 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002636 std::unique_ptr<MotionEntry> splitMotionEntry =
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002637 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002638 if (!splitMotionEntry) {
2639 return; // split event was dropped
2640 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002641 if (DEBUG_FOCUS) {
2642 ALOGD("channel '%s' ~ Split motion event.",
2643 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002644 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002645 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002646 enqueueDispatchEntriesLocked(currentTime, connection, std::move(splitMotionEntry),
2647 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002648 return;
2649 }
2650 }
2651
2652 // Not splitting. Enqueue dispatch entries for the event as is.
2653 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
2654}
2655
2656void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002657 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002658 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002659 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002660 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002661 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002662 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002663 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002664 ATRACE_NAME(message.c_str());
2665 }
2666
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002667 bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002668
2669 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07002670 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002671 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002672 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002673 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07002674 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002675 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07002676 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002677 InputTarget::FLAG_DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07002678 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002679 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002680 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002681 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002682
2683 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002684 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002685 startDispatchCycleLocked(currentTime, connection);
2686 }
2687}
2688
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002689void InputDispatcher::enqueueDispatchEntryLocked(const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002690 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002691 const InputTarget& inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002692 int32_t dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002693 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002694 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
2695 connection->getInputChannelName().c_str(),
2696 dispatchModeToString(dispatchMode).c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002697 ATRACE_NAME(message.c_str());
2698 }
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002699 int32_t inputTargetFlags = inputTarget.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002700 if (!(inputTargetFlags & dispatchMode)) {
2701 return;
2702 }
2703 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
2704
2705 // This is a new event.
2706 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002707 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002708 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002709
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002710 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
2711 // different EventEntry than what was passed in.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002712 EventEntry& newEntry = *(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002713 // Apply target flags and update the connection's input state.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002714 switch (newEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002715 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002716 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002717 dispatchEntry->resolvedEventId = keyEntry.id;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002718 dispatchEntry->resolvedAction = keyEntry.action;
2719 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002720
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002721 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
2722 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002723#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002724 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key event",
2725 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002726#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002727 return; // skip the inconsistent event
2728 }
2729 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002730 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002731
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002732 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002733 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002734 // Assign a default value to dispatchEntry that will never be generated by InputReader,
2735 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
2736 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
2737 static_cast<int32_t>(IdGenerator::Source::OTHER);
2738 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002739 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2740 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
2741 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
2742 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
2743 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
2744 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2745 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
2746 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
2747 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
2748 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
2749 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002750 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002751 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002752 }
2753 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002754 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
2755 motionEntry.displayId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002756#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002757 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover enter "
2758 "event",
2759 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002760#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002761 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2762 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002763
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002764 dispatchEntry->resolvedFlags = motionEntry.flags;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002765 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
2766 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
2767 }
2768 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
2769 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2770 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002771
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002772 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
2773 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002774#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002775 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
2776 "event",
2777 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002778#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002779 return; // skip the inconsistent event
2780 }
2781
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002782 dispatchEntry->resolvedEventId =
2783 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
2784 ? mIdGenerator.nextId()
2785 : motionEntry.id;
2786 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
2787 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
2788 ") to MotionEvent(id=0x%" PRIx32 ").",
2789 motionEntry.id, dispatchEntry->resolvedEventId);
2790 ATRACE_NAME(message.c_str());
2791 }
2792
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002793 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002794 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002795
2796 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002797 }
Prabir Pradhan99987712020-11-10 18:43:05 -08002798 case EventEntry::Type::FOCUS:
2799 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002800 break;
2801 }
Chris Yef59a2f42020-10-16 12:55:26 -07002802 case EventEntry::Type::SENSOR: {
2803 LOG_ALWAYS_FATAL("SENSOR events should not go to apps via input channel");
2804 break;
2805 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002806 case EventEntry::Type::CONFIGURATION_CHANGED:
2807 case EventEntry::Type::DEVICE_RESET: {
2808 LOG_ALWAYS_FATAL("%s events should not go to apps",
Chris Yef59a2f42020-10-16 12:55:26 -07002809 NamedEnum::string(newEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002810 break;
2811 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002812 }
2813
2814 // Remember that we are waiting for this dispatch to complete.
2815 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002816 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002817 }
2818
2819 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002820 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002821 traceOutboundQueueLength(connection);
chaviw8c9cf542019-03-25 13:02:48 -07002822}
2823
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00002824/**
2825 * This function is purely for debugging. It helps us understand where the user interaction
2826 * was taking place. For example, if user is touching launcher, we will see a log that user
2827 * started interacting with launcher. In that example, the event would go to the wallpaper as well.
2828 * We will see both launcher and wallpaper in that list.
2829 * Once the interaction with a particular set of connections starts, no new logs will be printed
2830 * until the set of interacted connections changes.
2831 *
2832 * The following items are skipped, to reduce the logspam:
2833 * ACTION_OUTSIDE: any windows that are receiving ACTION_OUTSIDE are not logged
2834 * ACTION_UP: any windows that receive ACTION_UP are not logged (for both keys and motions).
2835 * This includes situations like the soft BACK button key. When the user releases (lifts up the
2836 * finger) the back button, then navigation bar will inject KEYCODE_BACK with ACTION_UP.
2837 * Both of those ACTION_UP events would not be logged
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00002838 */
2839void InputDispatcher::updateInteractionTokensLocked(const EventEntry& entry,
2840 const std::vector<InputTarget>& targets) {
2841 // Skip ACTION_UP events, and all events other than keys and motions
2842 if (entry.type == EventEntry::Type::KEY) {
2843 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
2844 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
2845 return;
2846 }
2847 } else if (entry.type == EventEntry::Type::MOTION) {
2848 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
2849 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
2850 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
2851 return;
2852 }
2853 } else {
2854 return; // Not a key or a motion
2855 }
2856
2857 std::unordered_set<sp<IBinder>, IBinderHash> newConnectionTokens;
2858 std::vector<sp<Connection>> newConnections;
2859 for (const InputTarget& target : targets) {
2860 if ((target.flags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) ==
2861 InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2862 continue; // Skip windows that receive ACTION_OUTSIDE
2863 }
2864
2865 sp<IBinder> token = target.inputChannel->getConnectionToken();
2866 sp<Connection> connection = getConnectionLocked(token);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00002867 if (connection == nullptr) {
2868 continue;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00002869 }
2870 newConnectionTokens.insert(std::move(token));
2871 newConnections.emplace_back(connection);
2872 }
2873 if (newConnectionTokens == mInteractionConnectionTokens) {
2874 return; // no change
2875 }
2876 mInteractionConnectionTokens = newConnectionTokens;
2877
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00002878 std::string targetList;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00002879 for (const sp<Connection>& connection : newConnections) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00002880 targetList += connection->getWindowName() + ", ";
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00002881 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00002882 std::string message = "Interaction with: " + targetList;
2883 if (targetList.empty()) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00002884 message += "<none>";
2885 }
2886 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
2887}
2888
chaviwfd6d3512019-03-25 13:23:49 -07002889void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07002890 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07002891 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07002892 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
2893 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07002894 return;
2895 }
2896
Vishnu Nairc519ff72021-01-21 08:23:08 -08002897 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07002898 if (focusedToken == token) {
2899 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07002900 return;
2901 }
2902
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002903 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
2904 &InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible);
Vishnu Nairad321cd2020-08-20 16:40:21 -07002905 commandEntry->newToken = token;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002906 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002907}
2908
2909void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002910 const sp<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002911 if (ATRACE_ENABLED()) {
2912 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002913 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002914 ATRACE_NAME(message.c_str());
2915 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002916#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002917 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002918#endif
2919
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002920 while (connection->status == Connection::STATUS_NORMAL && !connection->outboundQueue.empty()) {
2921 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002922 dispatchEntry->deliveryTime = currentTime;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05002923 const std::chrono::nanoseconds timeout =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002924 getDispatchingTimeoutLocked(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou70622952020-07-30 11:17:23 -05002925 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002926
2927 // Publish the event.
2928 status_t status;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002929 const EventEntry& eventEntry = *(dispatchEntry->eventEntry);
2930 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002931 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002932 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
2933 std::array<uint8_t, 32> hmac = getSignature(keyEntry, *dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002934
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002935 // Publish the key event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002936 status = connection->inputPublisher
2937 .publishKeyEvent(dispatchEntry->seq,
2938 dispatchEntry->resolvedEventId, keyEntry.deviceId,
2939 keyEntry.source, keyEntry.displayId,
2940 std::move(hmac), dispatchEntry->resolvedAction,
2941 dispatchEntry->resolvedFlags, keyEntry.keyCode,
2942 keyEntry.scanCode, keyEntry.metaState,
2943 keyEntry.repeatCount, keyEntry.downTime,
2944 keyEntry.eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002945 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002946 }
2947
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002948 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002949 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002950
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002951 PointerCoords scaledCoords[MAX_POINTERS];
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002952 const PointerCoords* usingCoords = motionEntry.pointerCoords;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002953
chaviw82357092020-01-28 13:13:06 -08002954 // Set the X and Y offset and X and Y scale depending on the input source.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002955 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) &&
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002956 !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
2957 float globalScaleFactor = dispatchEntry->globalScaleFactor;
chaviw82357092020-01-28 13:13:06 -08002958 if (globalScaleFactor != 1.0f) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002959 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
2960 scaledCoords[i] = motionEntry.pointerCoords[i];
chaviw82357092020-01-28 13:13:06 -08002961 // Don't apply window scale here since we don't want scale to affect raw
2962 // coordinates. The scale will be sent back to the client and applied
2963 // later when requesting relative coordinates.
2964 scaledCoords[i].scale(globalScaleFactor, 1 /* windowXScale */,
2965 1 /* windowYScale */);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002966 }
2967 usingCoords = scaledCoords;
2968 }
2969 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002970 // We don't want the dispatch target to know.
2971 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002972 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002973 scaledCoords[i].clear();
2974 }
2975 usingCoords = scaledCoords;
2976 }
2977 }
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07002978
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002979 std::array<uint8_t, 32> hmac = getSignature(motionEntry, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002980
2981 // Publish the motion event.
2982 status = connection->inputPublisher
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002983 .publishMotionEvent(dispatchEntry->seq,
2984 dispatchEntry->resolvedEventId,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002985 motionEntry.deviceId, motionEntry.source,
2986 motionEntry.displayId, std::move(hmac),
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002987 dispatchEntry->resolvedAction,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002988 motionEntry.actionButton,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002989 dispatchEntry->resolvedFlags,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002990 motionEntry.edgeFlags, motionEntry.metaState,
2991 motionEntry.buttonState,
2992 motionEntry.classification,
chaviw9eaa22c2020-07-01 16:21:27 -07002993 dispatchEntry->transform,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002994 motionEntry.xPrecision, motionEntry.yPrecision,
2995 motionEntry.xCursorPosition,
2996 motionEntry.yCursorPosition,
2997 motionEntry.downTime, motionEntry.eventTime,
2998 motionEntry.pointerCount,
2999 motionEntry.pointerProperties, usingCoords);
3000 reportTouchEventForStatistics(motionEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003001 break;
3002 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003003
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003004 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003005 const FocusEntry& focusEntry = static_cast<const FocusEntry&>(eventEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003006 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003007 focusEntry.id,
3008 focusEntry.hasFocus,
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003009 mInTouchMode);
3010 break;
3011 }
3012
Prabir Pradhan99987712020-11-10 18:43:05 -08003013 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3014 const auto& captureEntry =
3015 static_cast<const PointerCaptureChangedEntry&>(eventEntry);
3016 status = connection->inputPublisher
3017 .publishCaptureEvent(dispatchEntry->seq, captureEntry.id,
3018 captureEntry.pointerCaptureEnabled);
3019 break;
3020 }
3021
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003022 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003023 case EventEntry::Type::DEVICE_RESET:
3024 case EventEntry::Type::SENSOR: {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003025 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
Chris Yef59a2f42020-10-16 12:55:26 -07003026 NamedEnum::string(eventEntry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003027 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003028 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003029 }
3030
3031 // Check the result.
3032 if (status) {
3033 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003034 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003035 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003036 "This is unexpected because the wait queue is empty, so the pipe "
3037 "should be empty and we shouldn't have any problems writing an "
3038 "event to it, status=%d",
3039 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003040 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3041 } else {
3042 // Pipe is full and we are waiting for the app to finish process some events
3043 // before sending more events to it.
3044#if DEBUG_DISPATCH_CYCLE
3045 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003046 "waiting for the application to catch up",
3047 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003048#endif
Michael Wrightd02c5b62014-02-10 15:10:22 -08003049 }
3050 } else {
3051 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003052 "status=%d",
3053 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003054 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3055 }
3056 return;
3057 }
3058
3059 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003060 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
3061 connection->outboundQueue.end(),
3062 dispatchEntry));
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003063 traceOutboundQueueLength(connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003064 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003065 if (connection->responsive) {
3066 mAnrTracker.insert(dispatchEntry->timeoutTime,
3067 connection->inputChannel->getConnectionToken());
3068 }
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003069 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003070 }
3071}
3072
chaviw09c8d2d2020-08-24 15:48:26 -07003073std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
3074 size_t size;
3075 switch (event.type) {
3076 case VerifiedInputEvent::Type::KEY: {
3077 size = sizeof(VerifiedKeyEvent);
3078 break;
3079 }
3080 case VerifiedInputEvent::Type::MOTION: {
3081 size = sizeof(VerifiedMotionEvent);
3082 break;
3083 }
3084 }
3085 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
3086 return mHmacKeyManager.sign(start, size);
3087}
3088
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003089const std::array<uint8_t, 32> InputDispatcher::getSignature(
3090 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
3091 int32_t actionMasked = dispatchEntry.resolvedAction & AMOTION_EVENT_ACTION_MASK;
3092 if ((actionMasked == AMOTION_EVENT_ACTION_UP) || (actionMasked == AMOTION_EVENT_ACTION_DOWN)) {
3093 // Only sign events up and down events as the purely move events
3094 // are tied to their up/down counterparts so signing would be redundant.
3095 VerifiedMotionEvent verifiedEvent = verifiedMotionEventFromMotionEntry(motionEntry);
3096 verifiedEvent.actionMasked = actionMasked;
3097 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
chaviw09c8d2d2020-08-24 15:48:26 -07003098 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003099 }
3100 return INVALID_HMAC;
3101}
3102
3103const std::array<uint8_t, 32> InputDispatcher::getSignature(
3104 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
3105 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
3106 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
3107 verifiedEvent.action = dispatchEntry.resolvedAction;
chaviw09c8d2d2020-08-24 15:48:26 -07003108 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003109}
3110
Michael Wrightd02c5b62014-02-10 15:10:22 -08003111void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003112 const sp<Connection>& connection, uint32_t seq,
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10003113 bool handled, nsecs_t consumeTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003114#if DEBUG_DISPATCH_CYCLE
3115 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003116 connection->getInputChannelName().c_str(), seq, toString(handled));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003117#endif
3118
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003119 if (connection->status == Connection::STATUS_BROKEN ||
3120 connection->status == Connection::STATUS_ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003121 return;
3122 }
3123
3124 // Notify other system components and prepare to start the next dispatch cycle.
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10003125 onDispatchCycleFinishedLocked(currentTime, connection, seq, handled, consumeTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003126}
3127
3128void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003129 const sp<Connection>& connection,
3130 bool notify) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003131#if DEBUG_DISPATCH_CYCLE
3132 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003133 connection->getInputChannelName().c_str(), toString(notify));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003134#endif
3135
3136 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003137 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003138 traceOutboundQueueLength(connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003139 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003140 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003141
3142 // The connection appears to be unrecoverably broken.
3143 // Ignore already broken or zombie connections.
3144 if (connection->status == Connection::STATUS_NORMAL) {
3145 connection->status = Connection::STATUS_BROKEN;
3146
3147 if (notify) {
3148 // Notify other system components.
3149 onDispatchCycleBrokenLocked(currentTime, connection);
3150 }
3151 }
3152}
3153
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003154void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
3155 while (!queue.empty()) {
3156 DispatchEntry* dispatchEntry = queue.front();
3157 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003158 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003159 }
3160}
3161
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003162void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003163 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003164 decrementPendingForegroundDispatches(*(dispatchEntry->eventEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003165 }
3166 delete dispatchEntry;
3167}
3168
3169int InputDispatcher::handleReceiveCallback(int fd, int events, void* data) {
3170 InputDispatcher* d = static_cast<InputDispatcher*>(data);
3171
3172 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003173 std::scoped_lock _l(d->mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003174
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003175 if (d->mConnectionsByFd.find(fd) == d->mConnectionsByFd.end()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003176 ALOGE("Received spurious receive callback for unknown input channel. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003177 "fd=%d, events=0x%x",
3178 fd, events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003179 return 0; // remove the callback
3180 }
3181
3182 bool notify;
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003183 sp<Connection> connection = d->mConnectionsByFd[fd];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003184 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
3185 if (!(events & ALOOPER_EVENT_INPUT)) {
3186 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003187 "events=0x%x",
3188 connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003189 return 1;
3190 }
3191
3192 nsecs_t currentTime = now();
3193 bool gotOne = false;
3194 status_t status;
3195 for (;;) {
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10003196 std::function<void(uint32_t seq, bool handled, nsecs_t consumeTime)> callback =
3197 std::bind(&InputDispatcher::finishDispatchCycleLocked, d, currentTime,
3198 connection, std::placeholders::_1, std::placeholders::_2,
3199 std::placeholders::_3);
3200
3201 status = connection->inputPublisher.receiveFinishedSignal(callback);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003202 if (status) {
3203 break;
3204 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003205 gotOne = true;
3206 }
3207 if (gotOne) {
3208 d->runCommandsLockedInterruptible();
3209 if (status == WOULD_BLOCK) {
3210 return 1;
3211 }
3212 }
3213
3214 notify = status != DEAD_OBJECT || !connection->monitor;
3215 if (notify) {
3216 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003217 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003218 }
3219 } else {
3220 // Monitor channels are never explicitly unregistered.
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003221 // We do it automatically when the remote endpoint is closed so don't warn about them.
arthurhungd352cb32020-04-28 17:09:28 +08003222 const bool stillHaveWindowHandle =
3223 d->getWindowHandleLocked(connection->inputChannel->getConnectionToken()) !=
3224 nullptr;
3225 notify = !connection->monitor && stillHaveWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003226 if (notify) {
3227 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003228 "events=0x%x",
3229 connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003230 }
3231 }
3232
Garfield Tan15601662020-09-22 15:32:38 -07003233 // Remove the channel.
3234 d->removeInputChannelLocked(connection->inputChannel->getConnectionToken(), notify);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003235 return 0; // remove the callback
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003236 } // release lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08003237}
3238
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003239void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08003240 const CancelationOptions& options) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +00003241 for (const auto& [fd, connection] : mConnectionsByFd) {
3242 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003243 }
3244}
3245
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003246void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003247 const CancelationOptions& options) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003248 synthesizeCancelationEventsForMonitorsLocked(options, mGlobalMonitorsByDisplay);
3249 synthesizeCancelationEventsForMonitorsLocked(options, mGestureMonitorsByDisplay);
3250}
3251
3252void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
3253 const CancelationOptions& options,
3254 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
3255 for (const auto& it : monitorsByDisplay) {
3256 const std::vector<Monitor>& monitors = it.second;
3257 for (const Monitor& monitor : monitors) {
3258 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003259 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003260 }
3261}
3262
Michael Wrightd02c5b62014-02-10 15:10:22 -08003263void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003264 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07003265 sp<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003266 if (connection == nullptr) {
3267 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003268 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003269
3270 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003271}
3272
3273void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
3274 const sp<Connection>& connection, const CancelationOptions& options) {
3275 if (connection->status == Connection::STATUS_BROKEN) {
3276 return;
3277 }
3278
3279 nsecs_t currentTime = now();
3280
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003281 std::vector<std::unique_ptr<EventEntry>> cancelationEvents =
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07003282 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003283
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003284 if (cancelationEvents.empty()) {
3285 return;
3286 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003287#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003288 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
3289 "with reality: %s, mode=%d.",
3290 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
3291 options.mode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003292#endif
Svet Ganov5d3bc372020-01-26 23:11:07 -08003293
3294 InputTarget target;
3295 sp<InputWindowHandle> windowHandle =
3296 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3297 if (windowHandle != nullptr) {
3298 const InputWindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003299 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003300 target.globalScaleFactor = windowInfo->globalScaleFactor;
3301 }
3302 target.inputChannel = connection->inputChannel;
3303 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3304
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003305 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003306 std::unique_ptr<EventEntry> cancelationEventEntry = std::move(cancelationEvents[i]);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003307 switch (cancelationEventEntry->type) {
3308 case EventEntry::Type::KEY: {
3309 logOutboundKeyDetails("cancel - ",
3310 static_cast<const KeyEntry&>(*cancelationEventEntry));
3311 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003312 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003313 case EventEntry::Type::MOTION: {
3314 logOutboundMotionDetails("cancel - ",
3315 static_cast<const MotionEntry&>(*cancelationEventEntry));
3316 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003317 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003318 case EventEntry::Type::FOCUS:
3319 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3320 LOG_ALWAYS_FATAL("Canceling %s events is not supported",
Chris Yef59a2f42020-10-16 12:55:26 -07003321 NamedEnum::string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003322 break;
3323 }
3324 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003325 case EventEntry::Type::DEVICE_RESET:
3326 case EventEntry::Type::SENSOR: {
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003327 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Chris Yef59a2f42020-10-16 12:55:26 -07003328 NamedEnum::string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003329 break;
3330 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003331 }
3332
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003333 enqueueDispatchEntryLocked(connection, std::move(cancelationEventEntry), target,
3334 InputTarget::FLAG_DISPATCH_AS_IS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003335 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003336
3337 startDispatchCycleLocked(currentTime, connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003338}
3339
Svet Ganov5d3bc372020-01-26 23:11:07 -08003340void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
3341 const sp<Connection>& connection) {
3342 if (connection->status == Connection::STATUS_BROKEN) {
3343 return;
3344 }
3345
3346 nsecs_t currentTime = now();
3347
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003348 std::vector<std::unique_ptr<EventEntry>> downEvents =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003349 connection->inputState.synthesizePointerDownEvents(currentTime);
3350
3351 if (downEvents.empty()) {
3352 return;
3353 }
3354
3355#if DEBUG_OUTBOUND_EVENT_DETAILS
3356 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
3357 connection->getInputChannelName().c_str(), downEvents.size());
3358#endif
3359
3360 InputTarget target;
3361 sp<InputWindowHandle> windowHandle =
3362 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3363 if (windowHandle != nullptr) {
3364 const InputWindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003365 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003366 target.globalScaleFactor = windowInfo->globalScaleFactor;
3367 }
3368 target.inputChannel = connection->inputChannel;
3369 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3370
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003371 for (std::unique_ptr<EventEntry>& downEventEntry : downEvents) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003372 switch (downEventEntry->type) {
3373 case EventEntry::Type::MOTION: {
3374 logOutboundMotionDetails("down - ",
3375 static_cast<const MotionEntry&>(*downEventEntry));
3376 break;
3377 }
3378
3379 case EventEntry::Type::KEY:
3380 case EventEntry::Type::FOCUS:
3381 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08003382 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07003383 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3384 case EventEntry::Type::SENSOR: {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003385 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Chris Yef59a2f42020-10-16 12:55:26 -07003386 NamedEnum::string(downEventEntry->type).c_str());
Svet Ganov5d3bc372020-01-26 23:11:07 -08003387 break;
3388 }
3389 }
3390
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003391 enqueueDispatchEntryLocked(connection, std::move(downEventEntry), target,
3392 InputTarget::FLAG_DISPATCH_AS_IS);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003393 }
3394
3395 startDispatchCycleLocked(currentTime, connection);
3396}
3397
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003398std::unique_ptr<MotionEntry> InputDispatcher::splitMotionEvent(
3399 const MotionEntry& originalMotionEntry, BitSet32 pointerIds) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003400 ALOG_ASSERT(pointerIds.value != 0);
3401
3402 uint32_t splitPointerIndexMap[MAX_POINTERS];
3403 PointerProperties splitPointerProperties[MAX_POINTERS];
3404 PointerCoords splitPointerCoords[MAX_POINTERS];
3405
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003406 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003407 uint32_t splitPointerCount = 0;
3408
3409 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003410 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003411 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003412 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003413 uint32_t pointerId = uint32_t(pointerProperties.id);
3414 if (pointerIds.hasBit(pointerId)) {
3415 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
3416 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
3417 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003418 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003419 splitPointerCount += 1;
3420 }
3421 }
3422
3423 if (splitPointerCount != pointerIds.count()) {
3424 // This is bad. We are missing some of the pointers that we expected to deliver.
3425 // Most likely this indicates that we received an ACTION_MOVE events that has
3426 // different pointer ids than we expected based on the previous ACTION_DOWN
3427 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
3428 // in this way.
3429 ALOGW("Dropping split motion event because the pointer count is %d but "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003430 "we expected there to be %d pointers. This probably means we received "
3431 "a broken sequence of pointer ids from the input device.",
3432 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07003433 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003434 }
3435
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003436 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003437 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003438 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
3439 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003440 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
3441 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003442 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003443 uint32_t pointerId = uint32_t(pointerProperties.id);
3444 if (pointerIds.hasBit(pointerId)) {
3445 if (pointerIds.count() == 1) {
3446 // The first/last pointer went down/up.
3447 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003448 ? AMOTION_EVENT_ACTION_DOWN
arthurhungea3f4fc2020-12-21 23:18:53 +08003449 : (originalMotionEntry.flags & AMOTION_EVENT_FLAG_CANCELED) != 0
3450 ? AMOTION_EVENT_ACTION_CANCEL
3451 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003452 } else {
3453 // A secondary pointer went down/up.
3454 uint32_t splitPointerIndex = 0;
3455 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
3456 splitPointerIndex += 1;
3457 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003458 action = maskedAction |
3459 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003460 }
3461 } else {
3462 // An unrelated pointer changed.
3463 action = AMOTION_EVENT_ACTION_MOVE;
3464 }
3465 }
3466
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003467 int32_t newId = mIdGenerator.nextId();
3468 if (ATRACE_ENABLED()) {
3469 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
3470 ") to MotionEvent(id=0x%" PRIx32 ").",
3471 originalMotionEntry.id, newId);
3472 ATRACE_NAME(message.c_str());
3473 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003474 std::unique_ptr<MotionEntry> splitMotionEntry =
3475 std::make_unique<MotionEntry>(newId, originalMotionEntry.eventTime,
3476 originalMotionEntry.deviceId, originalMotionEntry.source,
3477 originalMotionEntry.displayId,
3478 originalMotionEntry.policyFlags, action,
3479 originalMotionEntry.actionButton,
3480 originalMotionEntry.flags, originalMotionEntry.metaState,
3481 originalMotionEntry.buttonState,
3482 originalMotionEntry.classification,
3483 originalMotionEntry.edgeFlags,
3484 originalMotionEntry.xPrecision,
3485 originalMotionEntry.yPrecision,
3486 originalMotionEntry.xCursorPosition,
3487 originalMotionEntry.yCursorPosition,
3488 originalMotionEntry.downTime, splitPointerCount,
3489 splitPointerProperties, splitPointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003490
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003491 if (originalMotionEntry.injectionState) {
3492 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003493 splitMotionEntry->injectionState->refCount += 1;
3494 }
3495
3496 return splitMotionEntry;
3497}
3498
3499void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
3500#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003501 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003502#endif
3503
3504 bool needWake;
3505 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003506 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003507
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003508 std::unique_ptr<ConfigurationChangedEntry> newEntry =
3509 std::make_unique<ConfigurationChangedEntry>(args->id, args->eventTime);
3510 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003511 } // release lock
3512
3513 if (needWake) {
3514 mLooper->wake();
3515 }
3516}
3517
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003518/**
3519 * If one of the meta shortcuts is detected, process them here:
3520 * Meta + Backspace -> generate BACK
3521 * Meta + Enter -> generate HOME
3522 * This will potentially overwrite keyCode and metaState.
3523 */
3524void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003525 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003526 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
3527 int32_t newKeyCode = AKEYCODE_UNKNOWN;
3528 if (keyCode == AKEYCODE_DEL) {
3529 newKeyCode = AKEYCODE_BACK;
3530 } else if (keyCode == AKEYCODE_ENTER) {
3531 newKeyCode = AKEYCODE_HOME;
3532 }
3533 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003534 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003535 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003536 mReplacedKeys[replacement] = newKeyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003537 keyCode = newKeyCode;
3538 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3539 }
3540 } else if (action == AKEY_EVENT_ACTION_UP) {
3541 // In order to maintain a consistent stream of up and down events, check to see if the key
3542 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
3543 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003544 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003545 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003546 auto replacementIt = mReplacedKeys.find(replacement);
3547 if (replacementIt != mReplacedKeys.end()) {
3548 keyCode = replacementIt->second;
3549 mReplacedKeys.erase(replacementIt);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003550 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3551 }
3552 }
3553}
3554
Michael Wrightd02c5b62014-02-10 15:10:22 -08003555void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
3556#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003557 ALOGD("notifyKey - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
3558 "policyFlags=0x%x, action=0x%x, "
3559 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
3560 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
3561 args->action, args->flags, args->keyCode, args->scanCode, args->metaState,
3562 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003563#endif
3564 if (!validateKeyEvent(args->action)) {
3565 return;
3566 }
3567
3568 uint32_t policyFlags = args->policyFlags;
3569 int32_t flags = args->flags;
3570 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07003571 // InputDispatcher tracks and generates key repeats on behalf of
3572 // whatever notifies it, so repeatCount should always be set to 0
3573 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003574 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
3575 policyFlags |= POLICY_FLAG_VIRTUAL;
3576 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
3577 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003578 if (policyFlags & POLICY_FLAG_FUNCTION) {
3579 metaState |= AMETA_FUNCTION_ON;
3580 }
3581
3582 policyFlags |= POLICY_FLAG_TRUSTED;
3583
Michael Wright78f24442014-08-06 15:55:28 -07003584 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003585 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07003586
Michael Wrightd02c5b62014-02-10 15:10:22 -08003587 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003588 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08003589 args->action, flags, keyCode, args->scanCode, metaState, repeatCount,
3590 args->downTime, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003591
Michael Wright2b3c3302018-03-02 17:19:13 +00003592 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003593 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003594 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3595 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003596 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003597 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003598
Michael Wrightd02c5b62014-02-10 15:10:22 -08003599 bool needWake;
3600 { // acquire lock
3601 mLock.lock();
3602
3603 if (shouldSendKeyToInputFilterLocked(args)) {
3604 mLock.unlock();
3605
3606 policyFlags |= POLICY_FLAG_FILTERED;
3607 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3608 return; // event was consumed by the filter
3609 }
3610
3611 mLock.lock();
3612 }
3613
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003614 std::unique_ptr<KeyEntry> newEntry =
3615 std::make_unique<KeyEntry>(args->id, args->eventTime, args->deviceId, args->source,
3616 args->displayId, policyFlags, args->action, flags,
3617 keyCode, args->scanCode, metaState, repeatCount,
3618 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003619
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003620 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003621 mLock.unlock();
3622 } // release lock
3623
3624 if (needWake) {
3625 mLooper->wake();
3626 }
3627}
3628
3629bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
3630 return mInputFilterEnabled;
3631}
3632
3633void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
3634#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003635 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
3636 "displayId=%" PRId32 ", policyFlags=0x%x, "
Garfield Tan00f511d2019-06-12 16:55:40 -07003637 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
3638 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
Garfield Tanab0ab9c2019-07-10 18:58:28 -07003639 "yCursorPosition=%f, downTime=%" PRId64,
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003640 args->id, args->eventTime, args->deviceId, args->source, args->displayId,
3641 args->policyFlags, args->action, args->actionButton, args->flags, args->metaState,
3642 args->buttonState, args->edgeFlags, args->xPrecision, args->yPrecision,
3643 args->xCursorPosition, args->yCursorPosition, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003644 for (uint32_t i = 0; i < args->pointerCount; i++) {
3645 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003646 "x=%f, y=%f, pressure=%f, size=%f, "
3647 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
3648 "orientation=%f",
3649 i, args->pointerProperties[i].id, args->pointerProperties[i].toolType,
3650 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
3651 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
3652 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
3653 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
3654 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
3655 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
3656 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
3657 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
3658 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003659 }
3660#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003661 if (!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
3662 args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003663 return;
3664 }
3665
3666 uint32_t policyFlags = args->policyFlags;
3667 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003668
3669 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08003670 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003671 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3672 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003673 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003674 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003675
3676 bool needWake;
3677 { // acquire lock
3678 mLock.lock();
3679
3680 if (shouldSendMotionToInputFilterLocked(args)) {
3681 mLock.unlock();
3682
3683 MotionEvent event;
chaviw9eaa22c2020-07-01 16:21:27 -07003684 ui::Transform transform;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003685 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
3686 args->action, args->actionButton, args->flags, args->edgeFlags,
chaviw9eaa22c2020-07-01 16:21:27 -07003687 args->metaState, args->buttonState, args->classification, transform,
3688 args->xPrecision, args->yPrecision, args->xCursorPosition,
3689 args->yCursorPosition, args->downTime, args->eventTime,
3690 args->pointerCount, args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003691
3692 policyFlags |= POLICY_FLAG_FILTERED;
3693 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3694 return; // event was consumed by the filter
3695 }
3696
3697 mLock.lock();
3698 }
3699
3700 // Just enqueue a new motion event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003701 std::unique_ptr<MotionEntry> newEntry =
3702 std::make_unique<MotionEntry>(args->id, args->eventTime, args->deviceId,
3703 args->source, args->displayId, policyFlags,
3704 args->action, args->actionButton, args->flags,
3705 args->metaState, args->buttonState,
3706 args->classification, args->edgeFlags,
3707 args->xPrecision, args->yPrecision,
3708 args->xCursorPosition, args->yCursorPosition,
3709 args->downTime, args->pointerCount,
3710 args->pointerProperties, args->pointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003711
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003712 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003713 mLock.unlock();
3714 } // release lock
3715
3716 if (needWake) {
3717 mLooper->wake();
3718 }
3719}
3720
Chris Yef59a2f42020-10-16 12:55:26 -07003721void InputDispatcher::notifySensor(const NotifySensorArgs* args) {
3722#if DEBUG_INBOUND_EVENT_DETAILS
3723 ALOGD("notifySensor - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
3724 " sensorType=%s",
3725 args->id, args->eventTime, args->deviceId, args->source,
3726 NamedEnum::string(args->sensorType).c_str());
3727#endif
3728
3729 bool needWake;
3730 { // acquire lock
3731 mLock.lock();
3732
3733 // Just enqueue a new sensor event.
3734 std::unique_ptr<SensorEntry> newEntry =
3735 std::make_unique<SensorEntry>(args->id, args->eventTime, args->deviceId,
3736 args->source, 0 /* policyFlags*/, args->hwTimestamp,
3737 args->sensorType, args->accuracy,
3738 args->accuracyChanged, args->values);
3739
3740 needWake = enqueueInboundEventLocked(std::move(newEntry));
3741 mLock.unlock();
3742 } // release lock
3743
3744 if (needWake) {
3745 mLooper->wake();
3746 }
3747}
3748
Chris Yefb552902021-02-03 17:18:37 -08003749void InputDispatcher::notifyVibratorState(const NotifyVibratorStateArgs* args) {
3750#if DEBUG_INBOUND_EVENT_DETAILS
3751 ALOGD("notifyVibratorState - eventTime=%" PRId64 ", device=%d, isOn=%d", args->eventTime,
3752 args->deviceId, args->isOn);
3753#endif
3754 mPolicy->notifyVibratorState(args->deviceId, args->isOn);
3755}
3756
Michael Wrightd02c5b62014-02-10 15:10:22 -08003757bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08003758 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003759}
3760
3761void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
3762#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003763 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003764 "switchMask=0x%08x",
3765 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003766#endif
3767
3768 uint32_t policyFlags = args->policyFlags;
3769 policyFlags |= POLICY_FLAG_TRUSTED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003770 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003771}
3772
3773void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
3774#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003775 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
3776 args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003777#endif
3778
3779 bool needWake;
3780 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003781 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003782
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003783 std::unique_ptr<DeviceResetEntry> newEntry =
3784 std::make_unique<DeviceResetEntry>(args->id, args->eventTime, args->deviceId);
3785 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003786 } // release lock
3787
3788 if (needWake) {
3789 mLooper->wake();
3790 }
3791}
3792
Prabir Pradhan7e186182020-11-10 13:56:45 -08003793void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs* args) {
3794#if DEBUG_INBOUND_EVENT_DETAILS
3795 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args->eventTime,
3796 args->enabled ? "true" : "false");
3797#endif
3798
Prabir Pradhan99987712020-11-10 18:43:05 -08003799 bool needWake;
3800 { // acquire lock
3801 std::scoped_lock _l(mLock);
3802 auto entry = std::make_unique<PointerCaptureChangedEntry>(args->id, args->eventTime,
3803 args->enabled);
3804 needWake = enqueueInboundEventLocked(std::move(entry));
3805 } // release lock
3806
3807 if (needWake) {
3808 mLooper->wake();
3809 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08003810}
3811
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003812InputEventInjectionResult InputDispatcher::injectInputEvent(
3813 const InputEvent* event, int32_t injectorPid, int32_t injectorUid,
3814 InputEventInjectionSync syncMode, std::chrono::milliseconds timeout, uint32_t policyFlags) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003815#if DEBUG_INBOUND_EVENT_DETAILS
3816 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003817 "syncMode=%d, timeout=%lld, policyFlags=0x%08x",
3818 event->getType(), injectorPid, injectorUid, syncMode, timeout.count(), policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003819#endif
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003820 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003821
3822 policyFlags |= POLICY_FLAG_INJECTED;
3823 if (hasInjectionPermission(injectorPid, injectorUid)) {
3824 policyFlags |= POLICY_FLAG_TRUSTED;
3825 }
3826
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003827 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003828 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003829 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003830 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
3831 int32_t action = incomingKey.getAction();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003832 if (!validateKeyEvent(action)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003833 return InputEventInjectionResult::FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003834 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003835
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003836 int32_t flags = incomingKey.getFlags();
3837 int32_t keyCode = incomingKey.getKeyCode();
3838 int32_t metaState = incomingKey.getMetaState();
3839 accelerateMetaShortcuts(VIRTUAL_KEYBOARD_ID, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003840 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003841 KeyEvent keyEvent;
Garfield Tan4cc839f2020-01-24 11:26:14 -08003842 keyEvent.initialize(incomingKey.getId(), VIRTUAL_KEYBOARD_ID, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003843 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
3844 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
3845 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003846
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003847 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
3848 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00003849 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003850
3851 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
3852 android::base::Timer t;
3853 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
3854 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3855 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
3856 std::to_string(t.duration().count()).c_str());
3857 }
3858 }
3859
3860 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003861 std::unique_ptr<KeyEntry> injectedEntry =
3862 std::make_unique<KeyEntry>(incomingKey.getId(), incomingKey.getEventTime(),
3863 VIRTUAL_KEYBOARD_ID, incomingKey.getSource(),
3864 incomingKey.getDisplayId(), policyFlags, action,
3865 flags, keyCode, incomingKey.getScanCode(), metaState,
3866 incomingKey.getRepeatCount(),
3867 incomingKey.getDownTime());
3868 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003869 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003870 }
3871
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003872 case AINPUT_EVENT_TYPE_MOTION: {
3873 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
3874 int32_t action = motionEvent->getAction();
3875 size_t pointerCount = motionEvent->getPointerCount();
3876 const PointerProperties* pointerProperties = motionEvent->getPointerProperties();
3877 int32_t actionButton = motionEvent->getActionButton();
3878 int32_t displayId = motionEvent->getDisplayId();
3879 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003880 return InputEventInjectionResult::FAILED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003881 }
3882
3883 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
3884 nsecs_t eventTime = motionEvent->getEventTime();
3885 android::base::Timer t;
3886 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
3887 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3888 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
3889 std::to_string(t.duration().count()).c_str());
3890 }
3891 }
3892
3893 mLock.lock();
3894 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
3895 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003896 std::unique_ptr<MotionEntry> injectedEntry =
3897 std::make_unique<MotionEntry>(motionEvent->getId(), *sampleEventTimes,
3898 VIRTUAL_KEYBOARD_ID, motionEvent->getSource(),
3899 motionEvent->getDisplayId(), policyFlags, action,
3900 actionButton, motionEvent->getFlags(),
3901 motionEvent->getMetaState(),
3902 motionEvent->getButtonState(),
3903 motionEvent->getClassification(),
3904 motionEvent->getEdgeFlags(),
3905 motionEvent->getXPrecision(),
3906 motionEvent->getYPrecision(),
3907 motionEvent->getRawXCursorPosition(),
3908 motionEvent->getRawYCursorPosition(),
3909 motionEvent->getDownTime(),
3910 uint32_t(pointerCount), pointerProperties,
3911 samplePointerCoords, motionEvent->getXOffset(),
3912 motionEvent->getYOffset());
3913 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003914 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
3915 sampleEventTimes += 1;
3916 samplePointerCoords += pointerCount;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003917 std::unique_ptr<MotionEntry> nextInjectedEntry =
3918 std::make_unique<MotionEntry>(motionEvent->getId(), *sampleEventTimes,
3919 VIRTUAL_KEYBOARD_ID, motionEvent->getSource(),
3920 motionEvent->getDisplayId(), policyFlags,
3921 action, actionButton, motionEvent->getFlags(),
3922 motionEvent->getMetaState(),
3923 motionEvent->getButtonState(),
3924 motionEvent->getClassification(),
3925 motionEvent->getEdgeFlags(),
3926 motionEvent->getXPrecision(),
3927 motionEvent->getYPrecision(),
3928 motionEvent->getRawXCursorPosition(),
3929 motionEvent->getRawYCursorPosition(),
3930 motionEvent->getDownTime(),
3931 uint32_t(pointerCount), pointerProperties,
3932 samplePointerCoords,
3933 motionEvent->getXOffset(),
3934 motionEvent->getYOffset());
3935 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003936 }
3937 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003938 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003939
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003940 default:
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08003941 ALOGW("Cannot inject %s events", inputEventTypeToString(event->getType()));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003942 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003943 }
3944
3945 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003946 if (syncMode == InputEventInjectionSync::NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003947 injectionState->injectionIsAsync = true;
3948 }
3949
3950 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003951 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003952
3953 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003954 while (!injectedEntries.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003955 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003956 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003957 }
3958
3959 mLock.unlock();
3960
3961 if (needWake) {
3962 mLooper->wake();
3963 }
3964
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003965 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003966 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003967 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003968
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003969 if (syncMode == InputEventInjectionSync::NONE) {
3970 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003971 } else {
3972 for (;;) {
3973 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003974 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003975 break;
3976 }
3977
3978 nsecs_t remainingTimeout = endTime - now();
3979 if (remainingTimeout <= 0) {
3980#if DEBUG_INJECTION
3981 ALOGD("injectInputEvent - Timed out waiting for injection result "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003982 "to become available.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003983#endif
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003984 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003985 break;
3986 }
3987
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003988 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003989 }
3990
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003991 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
3992 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003993 while (injectionState->pendingForegroundDispatches != 0) {
3994#if DEBUG_INJECTION
3995 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003996 injectionState->pendingForegroundDispatches);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003997#endif
3998 nsecs_t remainingTimeout = endTime - now();
3999 if (remainingTimeout <= 0) {
4000#if DEBUG_INJECTION
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004001 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
4002 "dispatches to finish.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004003#endif
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004004 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004005 break;
4006 }
4007
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004008 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004009 }
4010 }
4011 }
4012
4013 injectionState->release();
4014 } // release lock
4015
4016#if DEBUG_INJECTION
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004017 ALOGD("injectInputEvent - Finished with result %d. injectorPid=%d, injectorUid=%d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004018 injectionResult, injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004019#endif
4020
4021 return injectionResult;
4022}
4023
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004024std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05004025 std::array<uint8_t, 32> calculatedHmac;
4026 std::unique_ptr<VerifiedInputEvent> result;
4027 switch (event.getType()) {
4028 case AINPUT_EVENT_TYPE_KEY: {
4029 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
4030 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
4031 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004032 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05004033 break;
4034 }
4035 case AINPUT_EVENT_TYPE_MOTION: {
4036 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
4037 VerifiedMotionEvent verifiedMotionEvent =
4038 verifiedMotionEventFromMotionEvent(motionEvent);
4039 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004040 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05004041 break;
4042 }
4043 default: {
4044 ALOGE("Cannot verify events of type %" PRId32, event.getType());
4045 return nullptr;
4046 }
4047 }
4048 if (calculatedHmac == INVALID_HMAC) {
4049 return nullptr;
4050 }
4051 if (calculatedHmac != event.getHmac()) {
4052 return nullptr;
4053 }
4054 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004055}
4056
Michael Wrightd02c5b62014-02-10 15:10:22 -08004057bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004058 return injectorUid == 0 ||
4059 mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004060}
4061
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004062void InputDispatcher::setInjectionResult(EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004063 InputEventInjectionResult injectionResult) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004064 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004065 if (injectionState) {
4066#if DEBUG_INJECTION
4067 ALOGD("Setting input event injection result to %d. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004068 "injectorPid=%d, injectorUid=%d",
4069 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004070#endif
4071
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004072 if (injectionState->injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004073 // Log the outcome since the injector did not wait for the injection result.
4074 switch (injectionResult) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004075 case InputEventInjectionResult::SUCCEEDED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004076 ALOGV("Asynchronous input event injection succeeded.");
4077 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004078 case InputEventInjectionResult::FAILED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004079 ALOGW("Asynchronous input event injection failed.");
4080 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004081 case InputEventInjectionResult::PERMISSION_DENIED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004082 ALOGW("Asynchronous input event injection permission denied.");
4083 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004084 case InputEventInjectionResult::TIMED_OUT:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004085 ALOGW("Asynchronous input event injection timed out.");
4086 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004087 case InputEventInjectionResult::PENDING:
4088 ALOGE("Setting result to 'PENDING' for asynchronous injection");
4089 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004090 }
4091 }
4092
4093 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004094 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004095 }
4096}
4097
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004098void InputDispatcher::incrementPendingForegroundDispatches(EventEntry& entry) {
4099 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004100 if (injectionState) {
4101 injectionState->pendingForegroundDispatches += 1;
4102 }
4103}
4104
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004105void InputDispatcher::decrementPendingForegroundDispatches(EventEntry& entry) {
4106 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004107 if (injectionState) {
4108 injectionState->pendingForegroundDispatches -= 1;
4109
4110 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004111 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004112 }
4113 }
4114}
4115
Vishnu Nairad321cd2020-08-20 16:40:21 -07004116const std::vector<sp<InputWindowHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004117 int32_t displayId) const {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004118 static const std::vector<sp<InputWindowHandle>> EMPTY_WINDOW_HANDLES;
4119 auto it = mWindowHandlesByDisplay.find(displayId);
4120 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08004121}
4122
Michael Wrightd02c5b62014-02-10 15:10:22 -08004123sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08004124 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08004125 if (windowHandleToken == nullptr) {
4126 return nullptr;
4127 }
4128
Arthur Hungb92218b2018-08-14 12:00:21 +08004129 for (auto& it : mWindowHandlesByDisplay) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004130 const std::vector<sp<InputWindowHandle>>& windowHandles = it.second;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004131 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004132 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004133 return windowHandle;
4134 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004135 }
4136 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004137 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004138}
4139
Vishnu Nairad321cd2020-08-20 16:40:21 -07004140sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(const sp<IBinder>& windowHandleToken,
4141 int displayId) const {
4142 if (windowHandleToken == nullptr) {
4143 return nullptr;
4144 }
4145
4146 for (const sp<InputWindowHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
4147 if (windowHandle->getToken() == windowHandleToken) {
4148 return windowHandle;
4149 }
4150 }
4151 return nullptr;
4152}
4153
4154sp<InputWindowHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
Vishnu Nairc519ff72021-01-21 08:23:08 -08004155 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(displayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07004156 return getWindowHandleLocked(focusedToken, displayId);
4157}
4158
Mady Mellor017bcd12020-06-23 19:12:00 +00004159bool InputDispatcher::hasWindowHandleLocked(const sp<InputWindowHandle>& windowHandle) const {
4160 for (auto& it : mWindowHandlesByDisplay) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004161 const std::vector<sp<InputWindowHandle>>& windowHandles = it.second;
Mady Mellor017bcd12020-06-23 19:12:00 +00004162 for (const sp<InputWindowHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08004163 if (handle->getId() == windowHandle->getId() &&
4164 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004165 if (windowHandle->getInfo()->displayId != it.first) {
4166 ALOGE("Found window %s in display %" PRId32
4167 ", but it should belong to display %" PRId32,
4168 windowHandle->getName().c_str(), it.first,
4169 windowHandle->getInfo()->displayId);
4170 }
4171 return true;
Arthur Hungb92218b2018-08-14 12:00:21 +08004172 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004173 }
4174 }
4175 return false;
4176}
4177
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004178bool InputDispatcher::hasResponsiveConnectionLocked(InputWindowHandle& windowHandle) const {
4179 sp<Connection> connection = getConnectionLocked(windowHandle.getToken());
4180 const bool noInputChannel =
4181 windowHandle.getInfo()->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
4182 if (connection != nullptr && noInputChannel) {
4183 ALOGW("%s has feature NO_INPUT_CHANNEL, but it matched to connection %s",
4184 windowHandle.getName().c_str(), connection->inputChannel->getName().c_str());
4185 return false;
4186 }
4187
4188 if (connection == nullptr) {
4189 if (!noInputChannel) {
4190 ALOGI("Could not find connection for %s", windowHandle.getName().c_str());
4191 }
4192 return false;
4193 }
4194 if (!connection->responsive) {
4195 ALOGW("Window %s is not responsive", windowHandle.getName().c_str());
4196 return false;
4197 }
4198 return true;
4199}
4200
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004201std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
4202 const sp<IBinder>& token) const {
Robert Carr5c8a0262018-10-03 16:30:44 -07004203 size_t count = mInputChannelsByToken.count(token);
4204 if (count == 0) {
4205 return nullptr;
4206 }
4207 return mInputChannelsByToken.at(token);
4208}
4209
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004210void InputDispatcher::updateWindowHandlesForDisplayLocked(
4211 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
4212 if (inputWindowHandles.empty()) {
4213 // Remove all handles on a display if there are no windows left.
4214 mWindowHandlesByDisplay.erase(displayId);
4215 return;
4216 }
4217
4218 // Since we compare the pointer of input window handles across window updates, we need
4219 // to make sure the handle object for the same window stays unchanged across updates.
4220 const std::vector<sp<InputWindowHandle>>& oldHandles = getWindowHandlesLocked(displayId);
chaviwaf87b3e2019-10-01 16:59:28 -07004221 std::unordered_map<int32_t /*id*/, sp<InputWindowHandle>> oldHandlesById;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004222 for (const sp<InputWindowHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07004223 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004224 }
4225
4226 std::vector<sp<InputWindowHandle>> newHandles;
4227 for (const sp<InputWindowHandle>& handle : inputWindowHandles) {
4228 if (!handle->updateInfo()) {
4229 // handle no longer valid
4230 continue;
4231 }
4232
4233 const InputWindowInfo* info = handle->getInfo();
4234 if ((getInputChannelLocked(handle->getToken()) == nullptr &&
4235 info->portalToDisplayId == ADISPLAY_ID_NONE)) {
4236 const bool noInputChannel =
Michael Wright44753b12020-07-08 13:48:11 +01004237 info->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
4238 const bool canReceiveInput = !info->flags.test(InputWindowInfo::Flag::NOT_TOUCHABLE) ||
4239 !info->flags.test(InputWindowInfo::Flag::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004240 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07004241 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004242 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07004243 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004244 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004245 }
4246
4247 if (info->displayId != displayId) {
4248 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
4249 handle->getName().c_str(), displayId, info->displayId);
4250 continue;
4251 }
4252
Robert Carredd13602020-04-13 17:24:34 -07004253 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
4254 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviwaf87b3e2019-10-01 16:59:28 -07004255 const sp<InputWindowHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004256 oldHandle->updateFrom(handle);
4257 newHandles.push_back(oldHandle);
4258 } else {
4259 newHandles.push_back(handle);
4260 }
4261 }
4262
4263 // Insert or replace
4264 mWindowHandlesByDisplay[displayId] = newHandles;
4265}
4266
Arthur Hung72d8dc32020-03-28 00:48:39 +00004267void InputDispatcher::setInputWindows(
4268 const std::unordered_map<int32_t, std::vector<sp<InputWindowHandle>>>& handlesPerDisplay) {
4269 { // acquire lock
4270 std::scoped_lock _l(mLock);
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004271 for (const auto& [displayId, handles] : handlesPerDisplay) {
4272 setInputWindowsLocked(handles, displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004273 }
4274 }
4275 // Wake up poll loop since it may need to make new input dispatching choices.
4276 mLooper->wake();
4277}
4278
Arthur Hungb92218b2018-08-14 12:00:21 +08004279/**
4280 * Called from InputManagerService, update window handle list by displayId that can receive input.
4281 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
4282 * If set an empty list, remove all handles from the specific display.
4283 * For focused handle, check if need to change and send a cancel event to previous one.
4284 * For removed handle, check if need to send a cancel event if already in touch.
4285 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00004286void InputDispatcher::setInputWindowsLocked(
4287 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004288 if (DEBUG_FOCUS) {
4289 std::string windowList;
4290 for (const sp<InputWindowHandle>& iwh : inputWindowHandles) {
4291 windowList += iwh->getName() + " ";
4292 }
4293 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
4294 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004295
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004296 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
4297 for (const sp<InputWindowHandle>& window : inputWindowHandles) {
4298 const bool noInputWindow =
4299 window->getInfo()->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
4300 if (noInputWindow && window->getToken() != nullptr) {
4301 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
4302 window->getName().c_str());
4303 window->releaseChannel();
4304 }
4305 }
4306
Arthur Hung72d8dc32020-03-28 00:48:39 +00004307 // Copy old handles for release if they are no longer present.
4308 const std::vector<sp<InputWindowHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004309
Arthur Hung72d8dc32020-03-28 00:48:39 +00004310 updateWindowHandlesForDisplayLocked(inputWindowHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004311
Vishnu Nair958da932020-08-21 17:12:37 -07004312 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
4313 if (mLastHoverWindowHandle &&
4314 std::find(windowHandles.begin(), windowHandles.end(), mLastHoverWindowHandle) ==
4315 windowHandles.end()) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004316 mLastHoverWindowHandle = nullptr;
4317 }
4318
Vishnu Nairc519ff72021-01-21 08:23:08 -08004319 std::optional<FocusResolver::FocusChanges> changes =
4320 mFocusResolver.setInputWindows(displayId, windowHandles);
4321 if (changes) {
4322 onFocusChangedLocked(*changes);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004323 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004324
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004325 std::unordered_map<int32_t, TouchState>::iterator stateIt =
4326 mTouchStatesByDisplay.find(displayId);
4327 if (stateIt != mTouchStatesByDisplay.end()) {
4328 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00004329 for (size_t i = 0; i < state.windows.size();) {
4330 TouchedWindow& touchedWindow = state.windows[i];
Mady Mellor017bcd12020-06-23 19:12:00 +00004331 if (!hasWindowHandleLocked(touchedWindow.windowHandle)) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004332 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004333 ALOGD("Touched window was removed: %s in display %" PRId32,
4334 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004335 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004336 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00004337 getInputChannelLocked(touchedWindow.windowHandle->getToken());
4338 if (touchedInputChannel != nullptr) {
4339 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4340 "touched window was removed");
4341 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004342 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004343 state.windows.erase(state.windows.begin() + i);
4344 } else {
4345 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004346 }
4347 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004348 }
Arthur Hung25e2af12020-03-26 12:58:37 +00004349
Arthur Hung72d8dc32020-03-28 00:48:39 +00004350 // Release information for windows that are no longer present.
4351 // This ensures that unused input channels are released promptly.
4352 // Otherwise, they might stick around until the window handle is destroyed
4353 // which might not happen until the next GC.
4354 for (const sp<InputWindowHandle>& oldWindowHandle : oldWindowHandles) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004355 if (!hasWindowHandleLocked(oldWindowHandle)) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004356 if (DEBUG_FOCUS) {
4357 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00004358 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004359 oldWindowHandle->releaseChannel();
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004360 // To avoid making too many calls into the compat framework, only
4361 // check for window flags when windows are going away.
4362 // TODO(b/157929241) : delete this. This is only needed temporarily
4363 // in order to gather some data about the flag usage
4364 if (oldWindowHandle->getInfo()->flags.test(InputWindowInfo::Flag::SLIPPERY)) {
4365 ALOGW("%s has FLAG_SLIPPERY. Please report this in b/157929241",
4366 oldWindowHandle->getName().c_str());
4367 if (mCompatService != nullptr) {
4368 mCompatService->reportChangeByUid(IInputConstants::BLOCK_FLAG_SLIPPERY,
4369 oldWindowHandle->getInfo()->ownerUid);
4370 }
4371 }
Arthur Hung25e2af12020-03-26 12:58:37 +00004372 }
chaviw291d88a2019-02-14 10:33:58 -08004373 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004374}
4375
4376void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07004377 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004378 if (DEBUG_FOCUS) {
4379 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
4380 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
4381 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004382 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004383 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004384
Chris Yea209fde2020-07-22 13:54:51 -07004385 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08004386 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004387
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004388 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
4389 return; // This application is already focused. No need to wake up or change anything.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004390 }
4391
Chris Yea209fde2020-07-22 13:54:51 -07004392 // Set the new application handle.
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004393 if (inputApplicationHandle != nullptr) {
4394 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
4395 } else {
4396 mFocusedApplicationHandlesByDisplay.erase(displayId);
4397 }
4398
4399 // No matter what the old focused application was, stop waiting on it because it is
4400 // no longer focused.
4401 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004402 } // release lock
4403
4404 // Wake up poll loop since it may need to make new input dispatching choices.
4405 mLooper->wake();
4406}
4407
Tiger Huang721e26f2018-07-24 22:26:19 +08004408/**
4409 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
4410 * the display not specified.
4411 *
4412 * We track any unreleased events for each window. If a window loses the ability to receive the
4413 * released event, we will send a cancel event to it. So when the focused display is changed, we
4414 * cancel all the unreleased display-unspecified events for the focused window on the old focused
4415 * display. The display-specified events won't be affected.
4416 */
4417void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004418 if (DEBUG_FOCUS) {
4419 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
4420 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004421 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004422 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08004423
4424 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004425 sp<IBinder> oldFocusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08004426 mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07004427 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004428 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07004429 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08004430 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004431 CancelationOptions
4432 options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
4433 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004434 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08004435 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
4436 }
4437 }
4438 mFocusedDisplayId = displayId;
4439
Chris Ye3c2d6f52020-08-09 10:39:48 -07004440 // Find new focused window and validate
Vishnu Nairc519ff72021-01-21 08:23:08 -08004441 sp<IBinder> newFocusedWindowToken = mFocusResolver.getFocusedWindowToken(displayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07004442 notifyFocusChangedLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08004443
Vishnu Nairad321cd2020-08-20 16:40:21 -07004444 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08004445 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairc519ff72021-01-21 08:23:08 -08004446 if (mFocusResolver.hasFocusedWindowTokens()) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004447 ALOGE("But another display has a focused window\n%s",
Vishnu Nairc519ff72021-01-21 08:23:08 -08004448 mFocusResolver.dumpFocusedWindows().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08004449 }
4450 }
4451 }
4452
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004453 if (DEBUG_FOCUS) {
4454 logDispatchStateLocked();
4455 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004456 } // release lock
4457
4458 // Wake up poll loop since it may need to make new input dispatching choices.
4459 mLooper->wake();
4460}
4461
Michael Wrightd02c5b62014-02-10 15:10:22 -08004462void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004463 if (DEBUG_FOCUS) {
4464 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
4465 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004466
4467 bool changed;
4468 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004469 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004470
4471 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
4472 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004473 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004474 }
4475
4476 if (mDispatchEnabled && !enabled) {
4477 resetAndDropEverythingLocked("dispatcher is being disabled");
4478 }
4479
4480 mDispatchEnabled = enabled;
4481 mDispatchFrozen = frozen;
4482 changed = true;
4483 } else {
4484 changed = false;
4485 }
4486
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004487 if (DEBUG_FOCUS) {
4488 logDispatchStateLocked();
4489 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004490 } // release lock
4491
4492 if (changed) {
4493 // Wake up poll loop since it may need to make new input dispatching choices.
4494 mLooper->wake();
4495 }
4496}
4497
4498void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004499 if (DEBUG_FOCUS) {
4500 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
4501 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004502
4503 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004504 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004505
4506 if (mInputFilterEnabled == enabled) {
4507 return;
4508 }
4509
4510 mInputFilterEnabled = enabled;
4511 resetAndDropEverythingLocked("input filter is being enabled or disabled");
4512 } // release lock
4513
4514 // Wake up poll loop since there might be work to do to drop everything.
4515 mLooper->wake();
4516}
4517
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08004518void InputDispatcher::setInTouchMode(bool inTouchMode) {
4519 std::scoped_lock lock(mLock);
4520 mInTouchMode = inTouchMode;
4521}
4522
Bernardo Rufinoea97d182020-08-19 14:43:14 +01004523void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
4524 if (opacity < 0 || opacity > 1) {
4525 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
4526 return;
4527 }
4528
4529 std::scoped_lock lock(mLock);
4530 mMaximumObscuringOpacityForTouch = opacity;
4531}
4532
4533void InputDispatcher::setBlockUntrustedTouchesMode(BlockUntrustedTouchesMode mode) {
4534 std::scoped_lock lock(mLock);
4535 mBlockUntrustedTouchesMode = mode;
4536}
4537
chaviwfbe5d9c2018-12-26 12:23:37 -08004538bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken) {
4539 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004540 if (DEBUG_FOCUS) {
4541 ALOGD("Trivial transfer to same window.");
4542 }
chaviwfbe5d9c2018-12-26 12:23:37 -08004543 return true;
4544 }
4545
Michael Wrightd02c5b62014-02-10 15:10:22 -08004546 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004547 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004548
chaviwfbe5d9c2018-12-26 12:23:37 -08004549 sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromToken);
4550 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toToken);
Yi Kong9b14ac62018-07-17 13:48:38 -07004551 if (fromWindowHandle == nullptr || toWindowHandle == nullptr) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004552 ALOGW("Cannot transfer focus because from or to window not found.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004553 return false;
4554 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004555 if (DEBUG_FOCUS) {
4556 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
4557 fromWindowHandle->getName().c_str(), toWindowHandle->getName().c_str());
4558 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004559 if (fromWindowHandle->getInfo()->displayId != toWindowHandle->getInfo()->displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004560 if (DEBUG_FOCUS) {
4561 ALOGD("Cannot transfer focus because windows are on different displays.");
4562 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004563 return false;
4564 }
4565
4566 bool found = false;
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004567 for (std::pair<const int32_t, TouchState>& pair : mTouchStatesByDisplay) {
4568 TouchState& state = pair.second;
Jeff Brownf086ddb2014-02-11 14:28:48 -08004569 for (size_t i = 0; i < state.windows.size(); i++) {
4570 const TouchedWindow& touchedWindow = state.windows[i];
4571 if (touchedWindow.windowHandle == fromWindowHandle) {
4572 int32_t oldTargetFlags = touchedWindow.targetFlags;
4573 BitSet32 pointerIds = touchedWindow.pointerIds;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004574
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004575 state.windows.erase(state.windows.begin() + i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004576
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004577 int32_t newTargetFlags = oldTargetFlags &
4578 (InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_SPLIT |
4579 InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004580 state.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004581
Jeff Brownf086ddb2014-02-11 14:28:48 -08004582 found = true;
4583 goto Found;
4584 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004585 }
4586 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004587 Found:
Michael Wrightd02c5b62014-02-10 15:10:22 -08004588
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004589 if (!found) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004590 if (DEBUG_FOCUS) {
4591 ALOGD("Focus transfer failed because from window did not have focus.");
4592 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004593 return false;
4594 }
4595
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004596 sp<Connection> fromConnection = getConnectionLocked(fromToken);
4597 sp<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004598 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004599 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004600 CancelationOptions
4601 options(CancelationOptions::CANCEL_POINTER_EVENTS,
4602 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004603 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004604 synthesizePointerDownEventsForConnectionLocked(toConnection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004605 }
4606
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004607 if (DEBUG_FOCUS) {
4608 logDispatchStateLocked();
4609 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004610 } // release lock
4611
4612 // Wake up poll loop since it may need to make new input dispatching choices.
4613 mLooper->wake();
4614 return true;
4615}
4616
4617void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004618 if (DEBUG_FOCUS) {
4619 ALOGD("Resetting and dropping all events (%s).", reason);
4620 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004621
4622 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
4623 synthesizeCancelationEventsForAllConnectionsLocked(options);
4624
4625 resetKeyRepeatLocked();
4626 releasePendingEventLocked();
4627 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004628 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004629
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004630 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08004631 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004632 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07004633 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004634}
4635
4636void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004637 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004638 dumpDispatchStateLocked(dump);
4639
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004640 std::istringstream stream(dump);
4641 std::string line;
4642
4643 while (std::getline(stream, line, '\n')) {
4644 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004645 }
4646}
4647
Prabir Pradhan99987712020-11-10 18:43:05 -08004648std::string InputDispatcher::dumpPointerCaptureStateLocked() {
4649 std::string dump;
4650
4651 dump += StringPrintf(INDENT "FocusedWindowRequestedPointerCapture: %s\n",
4652 toString(mFocusedWindowRequestedPointerCapture));
4653
4654 std::string windowName = "None";
4655 if (mWindowTokenWithPointerCapture) {
4656 const sp<InputWindowHandle> captureWindowHandle =
4657 getWindowHandleLocked(mWindowTokenWithPointerCapture);
4658 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
4659 : "token has capture without window";
4660 }
4661 dump += StringPrintf(INDENT "CurrentWindowWithPointerCapture: %s\n", windowName.c_str());
4662
4663 return dump;
4664}
4665
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004666void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07004667 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
4668 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
4669 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08004670 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004671
Tiger Huang721e26f2018-07-24 22:26:19 +08004672 if (!mFocusedApplicationHandlesByDisplay.empty()) {
4673 dump += StringPrintf(INDENT "FocusedApplications:\n");
4674 for (auto& it : mFocusedApplicationHandlesByDisplay) {
4675 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07004676 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05004677 const std::chrono::duration timeout =
4678 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004679 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004680 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05004681 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08004682 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004683 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08004684 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004685 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004686
Vishnu Nairc519ff72021-01-21 08:23:08 -08004687 dump += mFocusResolver.dump();
Prabir Pradhan99987712020-11-10 18:43:05 -08004688 dump += dumpPointerCaptureStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004689
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004690 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004691 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004692 for (const std::pair<int32_t, TouchState>& pair : mTouchStatesByDisplay) {
4693 const TouchState& state = pair.second;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004694 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004695 state.displayId, toString(state.down), toString(state.split),
4696 state.deviceId, state.source);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004697 if (!state.windows.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004698 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004699 for (size_t i = 0; i < state.windows.size(); i++) {
4700 const TouchedWindow& touchedWindow = state.windows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004701 dump += StringPrintf(INDENT4
4702 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
4703 i, touchedWindow.windowHandle->getName().c_str(),
4704 touchedWindow.pointerIds.value, touchedWindow.targetFlags);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004705 }
4706 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004707 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004708 }
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004709 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004710 dump += INDENT3 "Portal windows:\n";
4711 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004712 const sp<InputWindowHandle> portalWindowHandle = state.portalWindows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004713 dump += StringPrintf(INDENT4 "%zu: name='%s'\n", i,
4714 portalWindowHandle->getName().c_str());
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004715 }
4716 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004717 }
4718 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004719 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004720 }
4721
Arthur Hungb92218b2018-08-14 12:00:21 +08004722 if (!mWindowHandlesByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004723 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004724 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
Arthur Hung3b413f22018-10-26 18:05:34 +08004725 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", it.first);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004726 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004727 dump += INDENT2 "Windows:\n";
4728 for (size_t i = 0; i < windowHandles.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004729 const sp<InputWindowHandle>& windowHandle = windowHandles[i];
Arthur Hungb92218b2018-08-14 12:00:21 +08004730 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004731
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00004732 dump += StringPrintf(INDENT3 "%zu: name='%s', id=%" PRId32 ", displayId=%d, "
Vishnu Nair47074b82020-08-14 11:54:47 -07004733 "portalToDisplayId=%d, paused=%s, focusable=%s, "
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00004734 "hasWallpaper=%s, visible=%s, alpha=%.2f, "
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00004735 "flags=%s, type=%s, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004736 "frame=[%d,%d][%d,%d], globalScale=%f, "
Bernardo Rufino49d99e42021-01-18 15:16:59 +00004737 "applicationInfo.name=%s, "
4738 "applicationInfo.token=%s, "
chaviw1ff3d1e2020-07-01 15:53:47 -07004739 "touchableRegion=",
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00004740 i, windowInfo->name.c_str(), windowInfo->id,
4741 windowInfo->displayId, windowInfo->portalToDisplayId,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004742 toString(windowInfo->paused),
Vishnu Nair47074b82020-08-14 11:54:47 -07004743 toString(windowInfo->focusable),
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004744 toString(windowInfo->hasWallpaper),
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00004745 toString(windowInfo->visible), windowInfo->alpha,
Michael Wright8759d672020-07-21 00:46:45 +01004746 windowInfo->flags.string().c_str(),
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00004747 NamedEnum::string(windowInfo->type).c_str(),
Michael Wright44753b12020-07-08 13:48:11 +01004748 windowInfo->frameLeft, windowInfo->frameTop,
4749 windowInfo->frameRight, windowInfo->frameBottom,
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004750 windowInfo->globalScaleFactor,
Bernardo Rufino49d99e42021-01-18 15:16:59 +00004751 windowInfo->applicationInfo.name.c_str(),
4752 toString(windowInfo->applicationInfo.token).c_str());
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00004753 dump += dumpRegion(windowInfo->touchableRegion);
Michael Wright44753b12020-07-08 13:48:11 +01004754 dump += StringPrintf(", inputFeatures=%s",
4755 windowInfo->inputFeatures.string().c_str());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004756 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%" PRId64
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00004757 "ms, trustedOverlay=%s, hasToken=%s, "
4758 "touchOcclusionMode=%s\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004759 windowInfo->ownerPid, windowInfo->ownerUid,
Bernardo Rufinoc2f1fad2020-11-04 17:30:57 +00004760 millis(windowInfo->dispatchingTimeout),
4761 toString(windowInfo->trustedOverlay),
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00004762 toString(windowInfo->token != nullptr),
4763 toString(windowInfo->touchOcclusionMode).c_str());
chaviw85b44202020-07-24 11:46:21 -07004764 windowInfo->transform.dump(dump, "transform", INDENT4);
Arthur Hungb92218b2018-08-14 12:00:21 +08004765 }
4766 } else {
4767 dump += INDENT2 "Windows: <none>\n";
4768 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004769 }
4770 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08004771 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004772 }
4773
Michael Wright3dd60e22019-03-27 22:06:44 +00004774 if (!mGlobalMonitorsByDisplay.empty() || !mGestureMonitorsByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004775 for (auto& it : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004776 const std::vector<Monitor>& monitors = it.second;
4777 dump += StringPrintf(INDENT "Global monitors in display %" PRId32 ":\n", it.first);
4778 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004779 }
4780 for (auto& it : mGestureMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004781 const std::vector<Monitor>& monitors = it.second;
4782 dump += StringPrintf(INDENT "Gesture monitors in display %" PRId32 ":\n", it.first);
4783 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004784 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004785 } else {
Michael Wright3dd60e22019-03-27 22:06:44 +00004786 dump += INDENT "Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004787 }
4788
4789 nsecs_t currentTime = now();
4790
4791 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004792 if (!mRecentQueue.empty()) {
4793 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004794 for (std::shared_ptr<EventEntry>& entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004795 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05004796 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004797 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004798 }
4799 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004800 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004801 }
4802
4803 // Dump event currently being dispatched.
4804 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004805 dump += INDENT "PendingEvent:\n";
4806 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05004807 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004808 dump += StringPrintf(", age=%" PRId64 "ms\n",
4809 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004810 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004811 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004812 }
4813
4814 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004815 if (!mInboundQueue.empty()) {
4816 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004817 for (std::shared_ptr<EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004818 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05004819 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004820 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004821 }
4822 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004823 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004824 }
4825
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004826 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004827 dump += INDENT "ReplacedKeys:\n";
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004828 for (const std::pair<KeyReplacement, int32_t>& pair : mReplacedKeys) {
4829 const KeyReplacement& replacement = pair.first;
4830 int32_t newKeyCode = pair.second;
4831 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004832 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07004833 }
4834 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004835 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07004836 }
4837
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004838 if (!mConnectionsByFd.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004839 dump += INDENT "Connections:\n";
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004840 for (const auto& pair : mConnectionsByFd) {
4841 const sp<Connection>& connection = pair.second;
4842 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004843 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004844 pair.first, connection->getInputChannelName().c_str(),
4845 connection->getWindowName().c_str(), connection->getStatusLabel(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004846 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004847
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004848 if (!connection->outboundQueue.empty()) {
4849 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
4850 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05004851 dump += dumpQueue(connection->outboundQueue, currentTime);
4852
Michael Wrightd02c5b62014-02-10 15:10:22 -08004853 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004854 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004855 }
4856
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004857 if (!connection->waitQueue.empty()) {
4858 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
4859 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05004860 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004861 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004862 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004863 }
4864 }
4865 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004866 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004867 }
4868
4869 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004870 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
4871 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004872 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004873 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004874 }
4875
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004876 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004877 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
4878 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
4879 ns2ms(mConfig.keyRepeatTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004880}
4881
Michael Wright3dd60e22019-03-27 22:06:44 +00004882void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
4883 const size_t numMonitors = monitors.size();
4884 for (size_t i = 0; i < numMonitors; i++) {
4885 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004886 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00004887 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
4888 dump += "\n";
4889 }
4890}
4891
Garfield Tan15601662020-09-22 15:32:38 -07004892base::Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(
4893 const std::string& name) {
4894#if DEBUG_CHANNEL_CREATION
4895 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004896#endif
4897
Garfield Tan15601662020-09-22 15:32:38 -07004898 std::shared_ptr<InputChannel> serverChannel;
4899 std::unique_ptr<InputChannel> clientChannel;
4900 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
4901
4902 if (result) {
4903 return base::Error(result) << "Failed to open input channel pair with name " << name;
4904 }
4905
Michael Wrightd02c5b62014-02-10 15:10:22 -08004906 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004907 std::scoped_lock _l(mLock);
Garfield Tan15601662020-09-22 15:32:38 -07004908 sp<Connection> connection = new Connection(serverChannel, false /*monitor*/, mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004909
Garfield Tan15601662020-09-22 15:32:38 -07004910 int fd = serverChannel->getFd();
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004911 mConnectionsByFd[fd] = connection;
Garfield Tan15601662020-09-22 15:32:38 -07004912 mInputChannelsByToken[serverChannel->getConnectionToken()] = serverChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004913
Michael Wrightd02c5b62014-02-10 15:10:22 -08004914 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
4915 } // release lock
4916
4917 // Wake the looper because some connections have changed.
4918 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07004919 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004920}
4921
Garfield Tan15601662020-09-22 15:32:38 -07004922base::Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(
Siarhei Vishniakou58cfc602020-12-14 23:21:30 +00004923 int32_t displayId, bool isGestureMonitor, const std::string& name, int32_t pid) {
Garfield Tan15601662020-09-22 15:32:38 -07004924 std::shared_ptr<InputChannel> serverChannel;
4925 std::unique_ptr<InputChannel> clientChannel;
4926 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
4927 if (result) {
4928 return base::Error(result) << "Failed to open input channel pair with name " << name;
4929 }
4930
Michael Wright3dd60e22019-03-27 22:06:44 +00004931 { // acquire lock
4932 std::scoped_lock _l(mLock);
4933
4934 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07004935 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
4936 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00004937 }
4938
Garfield Tan15601662020-09-22 15:32:38 -07004939 sp<Connection> connection = new Connection(serverChannel, true /*monitor*/, mIdGenerator);
Michael Wright3dd60e22019-03-27 22:06:44 +00004940
Garfield Tan15601662020-09-22 15:32:38 -07004941 const int fd = serverChannel->getFd();
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004942 mConnectionsByFd[fd] = connection;
Garfield Tan15601662020-09-22 15:32:38 -07004943 mInputChannelsByToken[serverChannel->getConnectionToken()] = serverChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00004944
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004945 auto& monitorsByDisplay =
4946 isGestureMonitor ? mGestureMonitorsByDisplay : mGlobalMonitorsByDisplay;
Siarhei Vishniakou58cfc602020-12-14 23:21:30 +00004947 monitorsByDisplay[displayId].emplace_back(serverChannel, pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00004948
4949 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
Michael Wright3dd60e22019-03-27 22:06:44 +00004950 }
Garfield Tan15601662020-09-22 15:32:38 -07004951
Michael Wright3dd60e22019-03-27 22:06:44 +00004952 // Wake the looper because some connections have changed.
4953 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07004954 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00004955}
4956
Garfield Tan15601662020-09-22 15:32:38 -07004957status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004958 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004959 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004960
Garfield Tan15601662020-09-22 15:32:38 -07004961 status_t status = removeInputChannelLocked(connectionToken, false /*notify*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004962 if (status) {
4963 return status;
4964 }
4965 } // release lock
4966
4967 // Wake the poll loop because removing the connection may have changed the current
4968 // synchronization state.
4969 mLooper->wake();
4970 return OK;
4971}
4972
Garfield Tan15601662020-09-22 15:32:38 -07004973status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
4974 bool notify) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004975 sp<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004976 if (connection == nullptr) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00004977 // Connection can be removed via socket hang up or an explicit call to 'removeInputChannel'
Michael Wrightd02c5b62014-02-10 15:10:22 -08004978 return BAD_VALUE;
4979 }
4980
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004981 removeConnectionLocked(connection);
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004982 mInputChannelsByToken.erase(connectionToken);
Robert Carr5c8a0262018-10-03 16:30:44 -07004983
Michael Wrightd02c5b62014-02-10 15:10:22 -08004984 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004985 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004986 }
4987
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004988 mLooper->removeFd(connection->inputChannel->getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004989
4990 nsecs_t currentTime = now();
4991 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
4992
4993 connection->status = Connection::STATUS_ZOMBIE;
4994 return OK;
4995}
4996
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004997void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
4998 removeMonitorChannelLocked(connectionToken, mGlobalMonitorsByDisplay);
4999 removeMonitorChannelLocked(connectionToken, mGestureMonitorsByDisplay);
Michael Wright3dd60e22019-03-27 22:06:44 +00005000}
5001
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005002void InputDispatcher::removeMonitorChannelLocked(
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005003 const sp<IBinder>& connectionToken,
Michael Wright3dd60e22019-03-27 22:06:44 +00005004 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005005 for (auto it = monitorsByDisplay.begin(); it != monitorsByDisplay.end();) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005006 std::vector<Monitor>& monitors = it->second;
5007 const size_t numMonitors = monitors.size();
5008 for (size_t i = 0; i < numMonitors; i++) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005009 if (monitors[i].inputChannel->getConnectionToken() == connectionToken) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005010 monitors.erase(monitors.begin() + i);
5011 break;
5012 }
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005013 }
Michael Wright3dd60e22019-03-27 22:06:44 +00005014 if (monitors.empty()) {
5015 it = monitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005016 } else {
5017 ++it;
5018 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005019 }
5020}
5021
Michael Wright3dd60e22019-03-27 22:06:44 +00005022status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
5023 { // acquire lock
5024 std::scoped_lock _l(mLock);
5025 std::optional<int32_t> foundDisplayId = findGestureMonitorDisplayByTokenLocked(token);
5026
5027 if (!foundDisplayId) {
5028 ALOGW("Attempted to pilfer pointers from an un-registered monitor or invalid token");
5029 return BAD_VALUE;
5030 }
5031 int32_t displayId = foundDisplayId.value();
5032
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005033 std::unordered_map<int32_t, TouchState>::iterator stateIt =
5034 mTouchStatesByDisplay.find(displayId);
5035 if (stateIt == mTouchStatesByDisplay.end()) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005036 ALOGW("Failed to pilfer pointers: no pointers on display %" PRId32 ".", displayId);
5037 return BAD_VALUE;
5038 }
5039
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005040 TouchState& state = stateIt->second;
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005041 std::shared_ptr<InputChannel> requestingChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005042 std::optional<int32_t> foundDeviceId;
5043 for (const TouchedMonitor& touchedMonitor : state.gestureMonitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005044 if (touchedMonitor.monitor.inputChannel->getConnectionToken() == token) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005045 requestingChannel = touchedMonitor.monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005046 foundDeviceId = state.deviceId;
5047 }
5048 }
5049 if (!foundDeviceId || !state.down) {
5050 ALOGW("Attempted to pilfer points from a monitor without any on-going pointer streams."
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005051 " Ignoring.");
Michael Wright3dd60e22019-03-27 22:06:44 +00005052 return BAD_VALUE;
5053 }
5054 int32_t deviceId = foundDeviceId.value();
5055
5056 // Send cancel events to all the input channels we're stealing from.
5057 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005058 "gesture monitor stole pointer stream");
Michael Wright3dd60e22019-03-27 22:06:44 +00005059 options.deviceId = deviceId;
5060 options.displayId = displayId;
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005061 std::string canceledWindows = "[";
Michael Wright3dd60e22019-03-27 22:06:44 +00005062 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005063 std::shared_ptr<InputChannel> channel =
5064 getInputChannelLocked(window.windowHandle->getToken());
Michael Wright3a240c42019-12-10 20:53:41 +00005065 if (channel != nullptr) {
5066 synthesizeCancelationEventsForInputChannelLocked(channel, options);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005067 canceledWindows += channel->getName() + ", ";
Michael Wright3a240c42019-12-10 20:53:41 +00005068 }
Michael Wright3dd60e22019-03-27 22:06:44 +00005069 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005070 canceledWindows += "]";
5071 ALOGI("Monitor %s is stealing touch from %s", requestingChannel->getName().c_str(),
5072 canceledWindows.c_str());
5073
Michael Wright3dd60e22019-03-27 22:06:44 +00005074 // Then clear the current touch state so we stop dispatching to them as well.
5075 state.filterNonMonitors();
5076 }
5077 return OK;
5078}
5079
Prabir Pradhan99987712020-11-10 18:43:05 -08005080void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
5081 { // acquire lock
5082 std::scoped_lock _l(mLock);
5083 if (DEBUG_FOCUS) {
5084 const sp<InputWindowHandle> windowHandle = getWindowHandleLocked(windowToken);
5085 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
5086 windowHandle != nullptr ? windowHandle->getName().c_str()
5087 : "token without window");
5088 }
5089
Vishnu Nairc519ff72021-01-21 08:23:08 -08005090 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08005091 if (focusedToken != windowToken) {
5092 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
5093 enabled ? "enable" : "disable");
5094 return;
5095 }
5096
5097 if (enabled == mFocusedWindowRequestedPointerCapture) {
5098 ALOGW("Ignoring request to %s Pointer Capture: "
5099 "window has %s requested pointer capture.",
5100 enabled ? "enable" : "disable", enabled ? "already" : "not");
5101 return;
5102 }
5103
5104 mFocusedWindowRequestedPointerCapture = enabled;
5105 setPointerCaptureLocked(enabled);
5106 } // release lock
5107
5108 // Wake the thread to process command entries.
5109 mLooper->wake();
5110}
5111
Michael Wright3dd60e22019-03-27 22:06:44 +00005112std::optional<int32_t> InputDispatcher::findGestureMonitorDisplayByTokenLocked(
5113 const sp<IBinder>& token) {
5114 for (const auto& it : mGestureMonitorsByDisplay) {
5115 const std::vector<Monitor>& monitors = it.second;
5116 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005117 if (monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005118 return it.first;
5119 }
5120 }
5121 }
5122 return std::nullopt;
5123}
5124
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005125std::optional<int32_t> InputDispatcher::findMonitorPidByTokenLocked(const sp<IBinder>& token) {
5126 std::optional<int32_t> gesturePid = findMonitorPidByToken(mGestureMonitorsByDisplay, token);
5127 if (gesturePid.has_value()) {
5128 return gesturePid;
5129 }
5130 return findMonitorPidByToken(mGlobalMonitorsByDisplay, token);
5131}
5132
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005133sp<Connection> InputDispatcher::getConnectionLocked(const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005134 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005135 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08005136 }
5137
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005138 for (const auto& pair : mConnectionsByFd) {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005139 const sp<Connection>& connection = pair.second;
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005140 if (connection->inputChannel->getConnectionToken() == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005141 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005142 }
5143 }
Robert Carr4e670e52018-08-15 13:26:12 -07005144
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005145 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005146}
5147
Siarhei Vishniakouad991402020-10-28 11:40:09 -05005148std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
5149 sp<Connection> connection = getConnectionLocked(connectionToken);
5150 if (connection == nullptr) {
5151 return "<nullptr>";
5152 }
5153 return connection->getInputChannelName();
5154}
5155
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005156void InputDispatcher::removeConnectionLocked(const sp<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005157 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005158 removeByValue(mConnectionsByFd, connection);
5159}
5160
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005161void InputDispatcher::onDispatchCycleFinishedLocked(nsecs_t currentTime,
5162 const sp<Connection>& connection, uint32_t seq,
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10005163 bool handled, nsecs_t consumeTime) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005164 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5165 &InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005166 commandEntry->connection = connection;
5167 commandEntry->eventTime = currentTime;
5168 commandEntry->seq = seq;
5169 commandEntry->handled = handled;
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10005170 commandEntry->consumeTime = consumeTime;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005171 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005172}
5173
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005174void InputDispatcher::onDispatchCycleBrokenLocked(nsecs_t currentTime,
5175 const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005176 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005177 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005178
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005179 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5180 &InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005181 commandEntry->connection = connection;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005182 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005183}
5184
Vishnu Nairad321cd2020-08-20 16:40:21 -07005185void InputDispatcher::notifyFocusChangedLocked(const sp<IBinder>& oldToken,
5186 const sp<IBinder>& newToken) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005187 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5188 &InputDispatcher::doNotifyFocusChangedLockedInterruptible);
chaviw0c06c6e2019-01-09 13:27:07 -08005189 commandEntry->oldToken = oldToken;
5190 commandEntry->newToken = newToken;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005191 postCommandLocked(std::move(commandEntry));
Robert Carrf759f162018-11-13 12:57:11 -08005192}
5193
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005194void InputDispatcher::onAnrLocked(const sp<Connection>& connection) {
5195 if (connection == nullptr) {
5196 LOG_ALWAYS_FATAL("Caller must check for nullness");
5197 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005198 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
5199 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005200 if (connection->waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005201 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005202 connection->inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005203 return;
5204 }
5205 /**
5206 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
5207 * may not be the one that caused the timeout to occur. One possibility is that window timeout
5208 * has changed. This could cause newer entries to time out before the already dispatched
5209 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
5210 * processes the events linearly. So providing information about the oldest entry seems to be
5211 * most useful.
5212 */
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005213 DispatchEntry* oldestEntry = *connection->waitQueue.begin();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005214 const nsecs_t currentWait = now() - oldestEntry->deliveryTime;
5215 std::string reason =
5216 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005217 connection->inputChannel->getName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005218 ns2ms(currentWait),
5219 oldestEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005220 sp<IBinder> connectionToken = connection->inputChannel->getConnectionToken();
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06005221 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005222
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005223 processConnectionUnresponsiveLocked(*connection, std::move(reason));
5224
5225 // Stop waking up for events on this connection, it is already unresponsive
5226 cancelEventsForAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005227}
5228
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005229void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
5230 std::string reason =
5231 StringPrintf("%s does not have a focused window", application->getName().c_str());
5232 updateLastAnrStateLocked(*application, reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005233
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005234 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5235 &InputDispatcher::doNotifyNoFocusedWindowAnrLockedInterruptible);
5236 commandEntry->inputApplicationHandle = std::move(application);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005237 postCommandLocked(std::move(commandEntry));
5238}
5239
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00005240void InputDispatcher::onUntrustedTouchLocked(const std::string& obscuringPackage) {
5241 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5242 &InputDispatcher::doNotifyUntrustedTouchLockedInterruptible);
5243 commandEntry->obscuringPackage = obscuringPackage;
5244 postCommandLocked(std::move(commandEntry));
5245}
5246
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005247void InputDispatcher::updateLastAnrStateLocked(const sp<InputWindowHandle>& window,
5248 const std::string& reason) {
5249 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
5250 updateLastAnrStateLocked(windowLabel, reason);
5251}
5252
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005253void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
5254 const std::string& reason) {
5255 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005256 updateLastAnrStateLocked(windowLabel, reason);
5257}
5258
5259void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
5260 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005261 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07005262 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005263 struct tm tm;
5264 localtime_r(&t, &tm);
5265 char timestr[64];
5266 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005267 mLastAnrState.clear();
5268 mLastAnrState += INDENT "ANR:\n";
5269 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005270 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
5271 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005272 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005273}
5274
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005275void InputDispatcher::doNotifyConfigurationChangedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005276 mLock.unlock();
5277
5278 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
5279
5280 mLock.lock();
5281}
5282
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005283void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005284 sp<Connection> connection = commandEntry->connection;
5285
5286 if (connection->status != Connection::STATUS_ZOMBIE) {
5287 mLock.unlock();
5288
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005289 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005290
5291 mLock.lock();
5292 }
5293}
5294
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005295void InputDispatcher::doNotifyFocusChangedLockedInterruptible(CommandEntry* commandEntry) {
chaviw0c06c6e2019-01-09 13:27:07 -08005296 sp<IBinder> oldToken = commandEntry->oldToken;
5297 sp<IBinder> newToken = commandEntry->newToken;
Robert Carrf759f162018-11-13 12:57:11 -08005298 mLock.unlock();
chaviw0c06c6e2019-01-09 13:27:07 -08005299 mPolicy->notifyFocusChanged(oldToken, newToken);
Robert Carrf759f162018-11-13 12:57:11 -08005300 mLock.lock();
5301}
5302
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005303void InputDispatcher::doNotifyNoFocusedWindowAnrLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005304 mLock.unlock();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005305
5306 mPolicy->notifyNoFocusedWindowAnr(commandEntry->inputApplicationHandle);
5307
5308 mLock.lock();
5309}
5310
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005311void InputDispatcher::doNotifyWindowUnresponsiveLockedInterruptible(CommandEntry* commandEntry) {
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005312 mLock.unlock();
5313
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005314 mPolicy->notifyWindowUnresponsive(commandEntry->connectionToken, commandEntry->reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005315
5316 mLock.lock();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005317}
5318
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005319void InputDispatcher::doNotifyMonitorUnresponsiveLockedInterruptible(CommandEntry* commandEntry) {
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005320 mLock.unlock();
5321
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005322 mPolicy->notifyMonitorUnresponsive(commandEntry->pid, commandEntry->reason);
5323
5324 mLock.lock();
5325}
5326
5327void InputDispatcher::doNotifyWindowResponsiveLockedInterruptible(CommandEntry* commandEntry) {
5328 mLock.unlock();
5329
5330 mPolicy->notifyWindowResponsive(commandEntry->connectionToken);
5331
5332 mLock.lock();
5333}
5334
5335void InputDispatcher::doNotifyMonitorResponsiveLockedInterruptible(CommandEntry* commandEntry) {
5336 mLock.unlock();
5337
5338 mPolicy->notifyMonitorResponsive(commandEntry->pid);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005339
5340 mLock.lock();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005341}
5342
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00005343void InputDispatcher::doNotifyUntrustedTouchLockedInterruptible(CommandEntry* commandEntry) {
5344 mLock.unlock();
5345
5346 mPolicy->notifyUntrustedTouch(commandEntry->obscuringPackage);
5347
5348 mLock.lock();
5349}
5350
Michael Wrightd02c5b62014-02-10 15:10:22 -08005351void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
5352 CommandEntry* commandEntry) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005353 KeyEntry& entry = *(commandEntry->keyEntry);
5354 KeyEvent event = createKeyEvent(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005355
5356 mLock.unlock();
5357
Michael Wright2b3c3302018-03-02 17:19:13 +00005358 android::base::Timer t;
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06005359 const sp<IBinder>& token = commandEntry->connectionToken;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005360 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(token, &event, entry.policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00005361 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
5362 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005363 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00005364 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005365
5366 mLock.lock();
5367
5368 if (delay < 0) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005369 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005370 } else if (!delay) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005371 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005372 } else {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005373 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
5374 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005375 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005376}
5377
chaviwfd6d3512019-03-25 13:23:49 -07005378void InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible(CommandEntry* commandEntry) {
5379 mLock.unlock();
5380 mPolicy->onPointerDownOutsideFocus(commandEntry->newToken);
5381 mLock.lock();
5382}
5383
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005384/**
5385 * Connection is responsive if it has no events in the waitQueue that are older than the
5386 * current time.
5387 */
5388static bool isConnectionResponsive(const Connection& connection) {
5389 const nsecs_t currentTime = now();
5390 for (const DispatchEntry* entry : connection.waitQueue) {
5391 if (entry->timeoutTime < currentTime) {
5392 return false;
5393 }
5394 }
5395 return true;
5396}
5397
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005398void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005399 sp<Connection> connection = commandEntry->connection;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005400 const nsecs_t finishTime = commandEntry->eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005401 uint32_t seq = commandEntry->seq;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005402 const bool handled = commandEntry->handled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005403
5404 // Handle post-event policy actions.
Garfield Tane84e6f92019-08-29 17:28:41 -07005405 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005406 if (dispatchEntryIt == connection->waitQueue.end()) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005407 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005408 }
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005409 DispatchEntry* dispatchEntry = *dispatchEntryIt;
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07005410 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005411 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005412 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
5413 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005414 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07005415 reportDispatchStatistics(std::chrono::nanoseconds(eventDuration), *connection, handled);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005416
5417 bool restartEvent;
Siarhei Vishniakou49483272019-10-22 13:13:47 -07005418 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005419 KeyEntry& keyEntry = static_cast<KeyEntry&>(*(dispatchEntry->eventEntry));
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005420 restartEvent =
5421 afterKeyEventLockedInterruptible(connection, dispatchEntry, keyEntry, handled);
Siarhei Vishniakou49483272019-10-22 13:13:47 -07005422 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005423 MotionEntry& motionEntry = static_cast<MotionEntry&>(*(dispatchEntry->eventEntry));
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005424 restartEvent = afterMotionEventLockedInterruptible(connection, dispatchEntry, motionEntry,
5425 handled);
5426 } else {
5427 restartEvent = false;
5428 }
5429
5430 // Dequeue the event and start the next cycle.
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07005431 // Because the lock might have been released, it is possible that the
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005432 // contents of the wait queue to have been drained, so we need to double-check
5433 // a few things.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005434 dispatchEntryIt = connection->findWaitQueueEntry(seq);
5435 if (dispatchEntryIt != connection->waitQueue.end()) {
5436 dispatchEntry = *dispatchEntryIt;
5437 connection->waitQueue.erase(dispatchEntryIt);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005438 const sp<IBinder>& connectionToken = connection->inputChannel->getConnectionToken();
5439 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005440 if (!connection->responsive) {
5441 connection->responsive = isConnectionResponsive(*connection);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005442 if (connection->responsive) {
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005443 // The connection was unresponsive, and now it's responsive.
5444 processConnectionResponsiveLocked(*connection);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005445 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005446 }
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005447 traceWaitQueueLength(connection);
5448 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005449 connection->outboundQueue.push_front(dispatchEntry);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005450 traceOutboundQueueLength(connection);
5451 } else {
5452 releaseDispatchEntry(dispatchEntry);
5453 }
5454 }
5455
5456 // Start the next dispatch cycle for this connection.
5457 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005458}
5459
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005460void InputDispatcher::sendMonitorUnresponsiveCommandLocked(int32_t pid, std::string reason) {
5461 std::unique_ptr<CommandEntry> monitorUnresponsiveCommand = std::make_unique<CommandEntry>(
5462 &InputDispatcher::doNotifyMonitorUnresponsiveLockedInterruptible);
5463 monitorUnresponsiveCommand->pid = pid;
5464 monitorUnresponsiveCommand->reason = std::move(reason);
5465 postCommandLocked(std::move(monitorUnresponsiveCommand));
5466}
5467
5468void InputDispatcher::sendWindowUnresponsiveCommandLocked(sp<IBinder> connectionToken,
5469 std::string reason) {
5470 std::unique_ptr<CommandEntry> windowUnresponsiveCommand = std::make_unique<CommandEntry>(
5471 &InputDispatcher::doNotifyWindowUnresponsiveLockedInterruptible);
5472 windowUnresponsiveCommand->connectionToken = std::move(connectionToken);
5473 windowUnresponsiveCommand->reason = std::move(reason);
5474 postCommandLocked(std::move(windowUnresponsiveCommand));
5475}
5476
5477void InputDispatcher::sendMonitorResponsiveCommandLocked(int32_t pid) {
5478 std::unique_ptr<CommandEntry> monitorResponsiveCommand = std::make_unique<CommandEntry>(
5479 &InputDispatcher::doNotifyMonitorResponsiveLockedInterruptible);
5480 monitorResponsiveCommand->pid = pid;
5481 postCommandLocked(std::move(monitorResponsiveCommand));
5482}
5483
5484void InputDispatcher::sendWindowResponsiveCommandLocked(sp<IBinder> connectionToken) {
5485 std::unique_ptr<CommandEntry> windowResponsiveCommand = std::make_unique<CommandEntry>(
5486 &InputDispatcher::doNotifyWindowResponsiveLockedInterruptible);
5487 windowResponsiveCommand->connectionToken = std::move(connectionToken);
5488 postCommandLocked(std::move(windowResponsiveCommand));
5489}
5490
5491/**
5492 * Tell the policy that a connection has become unresponsive so that it can start ANR.
5493 * Check whether the connection of interest is a monitor or a window, and add the corresponding
5494 * command entry to the command queue.
5495 */
5496void InputDispatcher::processConnectionUnresponsiveLocked(const Connection& connection,
5497 std::string reason) {
5498 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
5499 if (connection.monitor) {
5500 ALOGW("Monitor %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
5501 reason.c_str());
5502 std::optional<int32_t> pid = findMonitorPidByTokenLocked(connectionToken);
5503 if (!pid.has_value()) {
5504 ALOGE("Could not find unresponsive monitor for connection %s",
5505 connection.inputChannel->getName().c_str());
5506 return;
5507 }
5508 sendMonitorUnresponsiveCommandLocked(pid.value(), std::move(reason));
5509 return;
5510 }
5511 // If not a monitor, must be a window
5512 ALOGW("Window %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
5513 reason.c_str());
5514 sendWindowUnresponsiveCommandLocked(connectionToken, std::move(reason));
5515}
5516
5517/**
5518 * Tell the policy that a connection has become responsive so that it can stop ANR.
5519 */
5520void InputDispatcher::processConnectionResponsiveLocked(const Connection& connection) {
5521 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
5522 if (connection.monitor) {
5523 std::optional<int32_t> pid = findMonitorPidByTokenLocked(connectionToken);
5524 if (!pid.has_value()) {
5525 ALOGE("Could not find responsive monitor for connection %s",
5526 connection.inputChannel->getName().c_str());
5527 return;
5528 }
5529 sendMonitorResponsiveCommandLocked(pid.value());
5530 return;
5531 }
5532 // If not a monitor, must be a window
5533 sendWindowResponsiveCommandLocked(connectionToken);
5534}
5535
Michael Wrightd02c5b62014-02-10 15:10:22 -08005536bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005537 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005538 KeyEntry& keyEntry, bool handled) {
5539 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005540 if (!handled) {
5541 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005542 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005543 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005544 return false;
5545 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005546
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005547 // Get the fallback key state.
5548 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005549 int32_t originalKeyCode = keyEntry.keyCode;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005550 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005551 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005552 connection->inputState.removeFallbackKey(originalKeyCode);
5553 }
5554
5555 if (handled || !dispatchEntry->hasForegroundTarget()) {
5556 // If the application handles the original key for which we previously
5557 // generated a fallback or if the window is not a foreground window,
5558 // then cancel the associated fallback key, if any.
5559 if (fallbackKeyCode != -1) {
5560 // Dispatch the unhandled key to the policy with the cancel flag.
Michael Wrightd02c5b62014-02-10 15:10:22 -08005561#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005562 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005563 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005564 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005565#endif
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005566 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005567 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005568
5569 mLock.unlock();
5570
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005571 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005572 keyEntry.policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005573
5574 mLock.lock();
5575
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005576 // Cancel the fallback key.
5577 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005578 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005579 "application handled the original non-fallback key "
5580 "or is no longer a foreground target, "
5581 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005582 options.keyCode = fallbackKeyCode;
5583 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005584 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005585 connection->inputState.removeFallbackKey(originalKeyCode);
5586 }
5587 } else {
5588 // If the application did not handle a non-fallback key, first check
5589 // that we are in a good state to perform unhandled key event processing
5590 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005591 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005592 if (fallbackKeyCode == -1 && !initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005593#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005594 ALOGD("Unhandled key event: Skipping unhandled key event processing "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005595 "since this is not an initial down. "
5596 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005597 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005598#endif
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005599 return false;
5600 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005601
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005602 // Dispatch the unhandled key to the policy.
5603#if DEBUG_OUTBOUND_EVENT_DETAILS
5604 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005605 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005606 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005607#endif
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005608 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005609
5610 mLock.unlock();
5611
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005612 bool fallback =
5613 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005614 &event, keyEntry.policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005615
5616 mLock.lock();
5617
5618 if (connection->status != Connection::STATUS_NORMAL) {
5619 connection->inputState.removeFallbackKey(originalKeyCode);
5620 return false;
5621 }
5622
5623 // Latch the fallback keycode for this key on an initial down.
5624 // The fallback keycode cannot change at any other point in the lifecycle.
5625 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005626 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005627 fallbackKeyCode = event.getKeyCode();
5628 } else {
5629 fallbackKeyCode = AKEYCODE_UNKNOWN;
5630 }
5631 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
5632 }
5633
5634 ALOG_ASSERT(fallbackKeyCode != -1);
5635
5636 // Cancel the fallback key if the policy decides not to send it anymore.
5637 // We will continue to dispatch the key to the policy but we will no
5638 // longer dispatch a fallback key to the application.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005639 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
5640 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005641#if DEBUG_OUTBOUND_EVENT_DETAILS
5642 if (fallback) {
5643 ALOGD("Unhandled key event: Policy requested to send key %d"
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005644 "as a fallback for %d, but on the DOWN it had requested "
5645 "to send %d instead. Fallback canceled.",
5646 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005647 } else {
5648 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005649 "but on the DOWN it had requested to send %d. "
5650 "Fallback canceled.",
5651 originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005652 }
5653#endif
5654
5655 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
5656 "canceling fallback, policy no longer desires it");
5657 options.keyCode = fallbackKeyCode;
5658 synthesizeCancelationEventsForConnectionLocked(connection, options);
5659
5660 fallback = false;
5661 fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005662 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005663 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005664 }
5665 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005666
5667#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005668 {
5669 std::string msg;
5670 const KeyedVector<int32_t, int32_t>& fallbackKeys =
5671 connection->inputState.getFallbackKeys();
5672 for (size_t i = 0; i < fallbackKeys.size(); i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005673 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005674 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005675 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005676 fallbackKeys.size(), msg.c_str());
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005677 }
5678#endif
5679
5680 if (fallback) {
5681 // Restart the dispatch cycle using the fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005682 keyEntry.eventTime = event.getEventTime();
5683 keyEntry.deviceId = event.getDeviceId();
5684 keyEntry.source = event.getSource();
5685 keyEntry.displayId = event.getDisplayId();
5686 keyEntry.flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
5687 keyEntry.keyCode = fallbackKeyCode;
5688 keyEntry.scanCode = event.getScanCode();
5689 keyEntry.metaState = event.getMetaState();
5690 keyEntry.repeatCount = event.getRepeatCount();
5691 keyEntry.downTime = event.getDownTime();
5692 keyEntry.syntheticRepeat = false;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005693
5694#if DEBUG_OUTBOUND_EVENT_DETAILS
5695 ALOGD("Unhandled key event: Dispatching fallback key. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005696 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005697 originalKeyCode, fallbackKeyCode, keyEntry.metaState);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005698#endif
5699 return true; // restart the event
5700 } else {
5701#if DEBUG_OUTBOUND_EVENT_DETAILS
5702 ALOGD("Unhandled key event: No fallback key.");
5703#endif
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005704
5705 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005706 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005707 }
5708 }
5709 return false;
5710}
5711
5712bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005713 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005714 MotionEntry& motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005715 return false;
5716}
5717
5718void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
5719 mLock.unlock();
5720
5721 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType);
5722
5723 mLock.lock();
5724}
5725
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07005726void InputDispatcher::reportDispatchStatistics(std::chrono::nanoseconds eventDuration,
5727 const Connection& connection, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005728 // TODO Write some statistics about how long we spend waiting.
5729}
5730
Siarhei Vishniakoude4bf152019-08-16 11:12:52 -05005731/**
5732 * Report the touch event latency to the statsd server.
5733 * Input events are reported for statistics if:
5734 * - This is a touchscreen event
5735 * - InputFilter is not enabled
5736 * - Event is not injected or synthesized
5737 *
5738 * Statistics should be reported before calling addValue, to prevent a fresh new sample
5739 * from getting aggregated with the "old" data.
5740 */
5741void InputDispatcher::reportTouchEventForStatistics(const MotionEntry& motionEntry)
5742 REQUIRES(mLock) {
5743 const bool reportForStatistics = (motionEntry.source == AINPUT_SOURCE_TOUCHSCREEN) &&
5744 !(motionEntry.isSynthesized()) && !mInputFilterEnabled;
5745 if (!reportForStatistics) {
5746 return;
5747 }
5748
5749 if (mTouchStatistics.shouldReport()) {
5750 android::util::stats_write(android::util::TOUCH_EVENT_REPORTED, mTouchStatistics.getMin(),
5751 mTouchStatistics.getMax(), mTouchStatistics.getMean(),
5752 mTouchStatistics.getStDev(), mTouchStatistics.getCount());
5753 mTouchStatistics.reset();
5754 }
5755 const float latencyMicros = nanoseconds_to_microseconds(now() - motionEntry.eventTime);
5756 mTouchStatistics.addValue(latencyMicros);
5757}
5758
Michael Wrightd02c5b62014-02-10 15:10:22 -08005759void InputDispatcher::traceInboundQueueLengthLocked() {
5760 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005761 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005762 }
5763}
5764
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08005765void InputDispatcher::traceOutboundQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005766 if (ATRACE_ENABLED()) {
5767 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08005768 snprintf(counterName, sizeof(counterName), "oq:%s", connection->getWindowName().c_str());
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005769 ATRACE_INT(counterName, connection->outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005770 }
5771}
5772
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08005773void InputDispatcher::traceWaitQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005774 if (ATRACE_ENABLED()) {
5775 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08005776 snprintf(counterName, sizeof(counterName), "wq:%s", connection->getWindowName().c_str());
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005777 ATRACE_INT(counterName, connection->waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005778 }
5779}
5780
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005781void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005782 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005783
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005784 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005785 dumpDispatchStateLocked(dump);
5786
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005787 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005788 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005789 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005790 }
5791}
5792
5793void InputDispatcher::monitor() {
5794 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005795 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005796 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005797 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005798}
5799
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08005800/**
5801 * Wake up the dispatcher and wait until it processes all events and commands.
5802 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
5803 * this method can be safely called from any thread, as long as you've ensured that
5804 * the work you are interested in completing has already been queued.
5805 */
5806bool InputDispatcher::waitForIdle() {
5807 /**
5808 * Timeout should represent the longest possible time that a device might spend processing
5809 * events and commands.
5810 */
5811 constexpr std::chrono::duration TIMEOUT = 100ms;
5812 std::unique_lock lock(mLock);
5813 mLooper->wake();
5814 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
5815 return result == std::cv_status::no_timeout;
5816}
5817
Vishnu Naire798b472020-07-23 13:52:21 -07005818/**
5819 * Sets focus to the window identified by the token. This must be called
5820 * after updating any input window handles.
5821 *
5822 * Params:
5823 * request.token - input channel token used to identify the window that should gain focus.
5824 * request.focusedToken - the token that the caller expects currently to be focused. If the
5825 * specified token does not match the currently focused window, this request will be dropped.
5826 * If the specified focused token matches the currently focused window, the call will succeed.
5827 * Set this to "null" if this call should succeed no matter what the currently focused token is.
5828 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
5829 * when requesting the focus change. This determines which request gets
5830 * precedence if there is a focus change request from another source such as pointer down.
5831 */
Vishnu Nair958da932020-08-21 17:12:37 -07005832void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
5833 { // acquire lock
5834 std::scoped_lock _l(mLock);
Vishnu Nairc519ff72021-01-21 08:23:08 -08005835 std::optional<FocusResolver::FocusChanges> changes =
5836 mFocusResolver.setFocusedWindow(request, getWindowHandlesLocked(request.displayId));
5837 if (changes) {
5838 onFocusChangedLocked(*changes);
Vishnu Nair958da932020-08-21 17:12:37 -07005839 }
5840 } // release lock
5841 // Wake up poll loop since it may need to make new input dispatching choices.
5842 mLooper->wake();
5843}
5844
Vishnu Nairc519ff72021-01-21 08:23:08 -08005845void InputDispatcher::onFocusChangedLocked(const FocusResolver::FocusChanges& changes) {
5846 if (changes.oldFocus) {
5847 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(changes.oldFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005848 if (focusedInputChannel) {
5849 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
5850 "focus left window");
5851 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Vishnu Nairc519ff72021-01-21 08:23:08 -08005852 enqueueFocusEventLocked(changes.oldFocus, false /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005853 }
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005854 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08005855 if (changes.newFocus) {
5856 enqueueFocusEventLocked(changes.newFocus, true /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005857 }
5858
Prabir Pradhan99987712020-11-10 18:43:05 -08005859 // If a window has pointer capture, then it must have focus. We need to ensure that this
5860 // contract is upheld when pointer capture is being disabled due to a loss of window focus.
5861 // If the window loses focus before it loses pointer capture, then the window can be in a state
5862 // where it has pointer capture but not focus, violating the contract. Therefore we must
5863 // dispatch the pointer capture event before the focus event. Since focus events are added to
5864 // the front of the queue (above), we add the pointer capture event to the front of the queue
5865 // after the focus events are added. This ensures the pointer capture event ends up at the
5866 // front.
5867 disablePointerCaptureForcedLocked();
5868
Vishnu Nairc519ff72021-01-21 08:23:08 -08005869 if (mFocusedDisplayId == changes.displayId) {
5870 notifyFocusChangedLocked(changes.oldFocus, changes.newFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005871 }
5872}
Vishnu Nair958da932020-08-21 17:12:37 -07005873
Prabir Pradhan99987712020-11-10 18:43:05 -08005874void InputDispatcher::disablePointerCaptureForcedLocked() {
5875 if (!mFocusedWindowRequestedPointerCapture && !mWindowTokenWithPointerCapture) {
5876 return;
5877 }
5878
5879 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
5880
5881 if (mFocusedWindowRequestedPointerCapture) {
5882 mFocusedWindowRequestedPointerCapture = false;
5883 setPointerCaptureLocked(false);
5884 }
5885
5886 if (!mWindowTokenWithPointerCapture) {
5887 // No need to send capture changes because no window has capture.
5888 return;
5889 }
5890
5891 if (mPendingEvent != nullptr) {
5892 // Move the pending event to the front of the queue. This will give the chance
5893 // for the pending event to be dropped if it is a captured event.
5894 mInboundQueue.push_front(mPendingEvent);
5895 mPendingEvent = nullptr;
5896 }
5897
5898 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
5899 false /* hasCapture */);
5900 mInboundQueue.push_front(std::move(entry));
5901}
5902
Prabir Pradhan99987712020-11-10 18:43:05 -08005903void InputDispatcher::setPointerCaptureLocked(bool enabled) {
5904 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5905 &InputDispatcher::doSetPointerCaptureLockedInterruptible);
5906 commandEntry->enabled = enabled;
5907 postCommandLocked(std::move(commandEntry));
5908}
5909
5910void InputDispatcher::doSetPointerCaptureLockedInterruptible(
5911 android::inputdispatcher::CommandEntry* commandEntry) {
5912 mLock.unlock();
5913
5914 mPolicy->setPointerCapture(commandEntry->enabled);
5915
5916 mLock.lock();
5917}
5918
Garfield Tane84e6f92019-08-29 17:28:41 -07005919} // namespace android::inputdispatcher