blob: 583210956db274335d00dd8e605f9bc542561283 [file] [log] [blame]
Michael Wrightd02c5b62014-02-10 15:10:22 -08001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "InputDispatcher"
18#define ATRACE_TAG ATRACE_TAG_INPUT
19
John Recke0710582019-09-26 13:46:12 -070020#define LOG_NDEBUG 1
Michael Wrightd02c5b62014-02-10 15:10:22 -080021
22// Log detailed debug messages about each inbound event notification to the dispatcher.
23#define DEBUG_INBOUND_EVENT_DETAILS 0
24
25// Log detailed debug messages about each outbound event processed by the dispatcher.
26#define DEBUG_OUTBOUND_EVENT_DETAILS 0
27
28// Log debug messages about the dispatch cycle.
29#define DEBUG_DISPATCH_CYCLE 0
30
Garfield Tan15601662020-09-22 15:32:38 -070031// Log debug messages about channel creation
32#define DEBUG_CHANNEL_CREATION 0
Michael Wrightd02c5b62014-02-10 15:10:22 -080033
34// Log debug messages about input event injection.
35#define DEBUG_INJECTION 0
36
37// Log debug messages about input focus tracking.
Siarhei Vishniakou86587282019-09-09 18:20:15 +010038static constexpr bool DEBUG_FOCUS = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -080039
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +000040// Log debug messages about touch occlusion
41// STOPSHIP(b/169067926): Set to false
42static constexpr bool DEBUG_TOUCH_OCCLUSION = true;
43
Michael Wrightd02c5b62014-02-10 15:10:22 -080044// Log debug messages about the app switch latency optimization.
45#define DEBUG_APP_SWITCH 0
46
47// Log debug messages about hover events.
48#define DEBUG_HOVER 0
49
Michael Wright2b3c3302018-03-02 17:19:13 +000050#include <android-base/chrono_utils.h>
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080051#include <android-base/stringprintf.h>
Siarhei Vishniakou70622952020-07-30 11:17:23 -050052#include <android/os/IInputConstants.h>
Robert Carr4e670e52018-08-15 13:26:12 -070053#include <binder/Binder.h>
Siarhei Vishniakou2508b872020-12-03 16:33:53 -100054#include <binder/IServiceManager.h>
55#include <com/android/internal/compat/IPlatformCompatNative.h>
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -080056#include <input/InputDevice.h>
Michael Wright44753b12020-07-08 13:48:11 +010057#include <input/InputWindow.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070058#include <log/log.h>
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +000059#include <log/log_event_list.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070060#include <powermanager/PowerManager.h>
Michael Wright44753b12020-07-08 13:48:11 +010061#include <statslog.h>
62#include <unistd.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070063#include <utils/Trace.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080064
Michael Wright44753b12020-07-08 13:48:11 +010065#include <cerrno>
66#include <cinttypes>
67#include <climits>
68#include <cstddef>
69#include <ctime>
70#include <queue>
71#include <sstream>
72
73#include "Connection.h"
Chris Yef59a2f42020-10-16 12:55:26 -070074#include "InputDispatcher.h"
Michael Wright44753b12020-07-08 13:48:11 +010075
Michael Wrightd02c5b62014-02-10 15:10:22 -080076#define INDENT " "
77#define INDENT2 " "
78#define INDENT3 " "
79#define INDENT4 " "
80
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080081using android::base::StringPrintf;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -080082using android::os::BlockUntrustedTouchesMode;
Siarhei Vishniakou2508b872020-12-03 16:33:53 -100083using android::os::IInputConstants;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -080084using android::os::InputEventInjectionResult;
85using android::os::InputEventInjectionSync;
Siarhei Vishniakou2508b872020-12-03 16:33:53 -100086using com::android::internal::compat::IPlatformCompatNative;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080087
Garfield Tane84e6f92019-08-29 17:28:41 -070088namespace android::inputdispatcher {
Michael Wrightd02c5b62014-02-10 15:10:22 -080089
90// Default input dispatching timeout if there is no focused application or paused window
91// from which to determine an appropriate dispatching timeout.
Siarhei Vishniakou70622952020-07-30 11:17:23 -050092constexpr std::chrono::duration DEFAULT_INPUT_DISPATCHING_TIMEOUT =
93 std::chrono::milliseconds(android::os::IInputConstants::DEFAULT_DISPATCHING_TIMEOUT_MILLIS);
Michael Wrightd02c5b62014-02-10 15:10:22 -080094
95// Amount of time to allow for all pending events to be processed when an app switch
96// key is on the way. This is used to preempt input dispatch and drop input events
97// when an application takes too long to respond and the user has pressed an app switch key.
Michael Wright2b3c3302018-03-02 17:19:13 +000098constexpr nsecs_t APP_SWITCH_TIMEOUT = 500 * 1000000LL; // 0.5sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080099
100// Amount of time to allow for an event to be dispatched (measured since its eventTime)
101// before considering it stale and dropping it.
Michael Wright2b3c3302018-03-02 17:19:13 +0000102constexpr nsecs_t STALE_EVENT_TIMEOUT = 10000 * 1000000LL; // 10sec
Michael Wrightd02c5b62014-02-10 15:10:22 -0800103
Michael Wrightd02c5b62014-02-10 15:10:22 -0800104// Log a warning when an event takes longer than this to process, even if an ANR does not occur.
Michael Wright2b3c3302018-03-02 17:19:13 +0000105constexpr nsecs_t SLOW_EVENT_PROCESSING_WARNING_TIMEOUT = 2000 * 1000000LL; // 2sec
106
107// Log a warning when an interception call takes longer than this to process.
108constexpr std::chrono::milliseconds SLOW_INTERCEPTION_THRESHOLD = 50ms;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800109
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700110// Additional key latency in case a connection is still processing some motion events.
111// This will help with the case when a user touched a button that opens a new window,
112// and gives us the chance to dispatch the key to this new window.
113constexpr std::chrono::nanoseconds KEY_WAITING_FOR_EVENTS_TIMEOUT = 500ms;
114
Michael Wrightd02c5b62014-02-10 15:10:22 -0800115// Number of recent events to keep for debugging purposes.
Michael Wright2b3c3302018-03-02 17:19:13 +0000116constexpr size_t RECENT_QUEUE_MAX_SIZE = 10;
117
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +0000118// Event log tags. See EventLogTags.logtags for reference
119constexpr int LOGTAG_INPUT_INTERACTION = 62000;
120constexpr int LOGTAG_INPUT_FOCUS = 62001;
121
Michael Wrightd02c5b62014-02-10 15:10:22 -0800122static inline nsecs_t now() {
123 return systemTime(SYSTEM_TIME_MONOTONIC);
124}
125
126static inline const char* toString(bool value) {
127 return value ? "true" : "false";
128}
129
130static inline int32_t getMotionEventActionPointerIndex(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700131 return (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) >>
132 AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800133}
134
135static bool isValidKeyAction(int32_t action) {
136 switch (action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700137 case AKEY_EVENT_ACTION_DOWN:
138 case AKEY_EVENT_ACTION_UP:
139 return true;
140 default:
141 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800142 }
143}
144
145static bool validateKeyEvent(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700146 if (!isValidKeyAction(action)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800147 ALOGE("Key event has invalid action code 0x%x", action);
148 return false;
149 }
150 return true;
151}
152
Michael Wright7b159c92015-05-14 14:48:03 +0100153static bool isValidMotionAction(int32_t action, int32_t actionButton, int32_t pointerCount) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800154 switch (action & AMOTION_EVENT_ACTION_MASK) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700155 case AMOTION_EVENT_ACTION_DOWN:
156 case AMOTION_EVENT_ACTION_UP:
157 case AMOTION_EVENT_ACTION_CANCEL:
158 case AMOTION_EVENT_ACTION_MOVE:
159 case AMOTION_EVENT_ACTION_OUTSIDE:
160 case AMOTION_EVENT_ACTION_HOVER_ENTER:
161 case AMOTION_EVENT_ACTION_HOVER_MOVE:
162 case AMOTION_EVENT_ACTION_HOVER_EXIT:
163 case AMOTION_EVENT_ACTION_SCROLL:
164 return true;
165 case AMOTION_EVENT_ACTION_POINTER_DOWN:
166 case AMOTION_EVENT_ACTION_POINTER_UP: {
167 int32_t index = getMotionEventActionPointerIndex(action);
168 return index >= 0 && index < pointerCount;
169 }
170 case AMOTION_EVENT_ACTION_BUTTON_PRESS:
171 case AMOTION_EVENT_ACTION_BUTTON_RELEASE:
172 return actionButton != 0;
173 default:
174 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800175 }
176}
177
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -0500178static int64_t millis(std::chrono::nanoseconds t) {
179 return std::chrono::duration_cast<std::chrono::milliseconds>(t).count();
180}
181
Michael Wright7b159c92015-05-14 14:48:03 +0100182static bool validateMotionEvent(int32_t action, int32_t actionButton, size_t pointerCount,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700183 const PointerProperties* pointerProperties) {
184 if (!isValidMotionAction(action, actionButton, pointerCount)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800185 ALOGE("Motion event has invalid action code 0x%x", action);
186 return false;
187 }
188 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
Narayan Kamath37764c72014-03-27 14:21:09 +0000189 ALOGE("Motion event has invalid pointer count %zu; value must be between 1 and %d.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700190 pointerCount, MAX_POINTERS);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800191 return false;
192 }
193 BitSet32 pointerIdBits;
194 for (size_t i = 0; i < pointerCount; i++) {
195 int32_t id = pointerProperties[i].id;
196 if (id < 0 || id > MAX_POINTER_ID) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700197 ALOGE("Motion event has invalid pointer id %d; value must be between 0 and %d", id,
198 MAX_POINTER_ID);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800199 return false;
200 }
201 if (pointerIdBits.hasBit(id)) {
202 ALOGE("Motion event has duplicate pointer id %d", id);
203 return false;
204 }
205 pointerIdBits.markBit(id);
206 }
207 return true;
208}
209
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000210static std::string dumpRegion(const Region& region) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800211 if (region.isEmpty()) {
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000212 return "<empty>";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800213 }
214
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000215 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800216 bool first = true;
217 Region::const_iterator cur = region.begin();
218 Region::const_iterator const tail = region.end();
219 while (cur != tail) {
220 if (first) {
221 first = false;
222 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800223 dump += "|";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800224 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800225 dump += StringPrintf("[%d,%d][%d,%d]", cur->left, cur->top, cur->right, cur->bottom);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800226 cur++;
227 }
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000228 return dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800229}
230
Siarhei Vishniakou14411c92020-09-18 21:15:05 -0500231static std::string dumpQueue(const std::deque<DispatchEntry*>& queue, nsecs_t currentTime) {
232 constexpr size_t maxEntries = 50; // max events to print
233 constexpr size_t skipBegin = maxEntries / 2;
234 const size_t skipEnd = queue.size() - maxEntries / 2;
235 // skip from maxEntries / 2 ... size() - maxEntries/2
236 // only print from 0 .. skipBegin and then from skipEnd .. size()
237
238 std::string dump;
239 for (size_t i = 0; i < queue.size(); i++) {
240 const DispatchEntry& entry = *queue[i];
241 if (i >= skipBegin && i < skipEnd) {
242 dump += StringPrintf(INDENT4 "<skipped %zu entries>\n", skipEnd - skipBegin);
243 i = skipEnd - 1; // it will be incremented to "skipEnd" by 'continue'
244 continue;
245 }
246 dump.append(INDENT4);
247 dump += entry.eventEntry->getDescription();
248 dump += StringPrintf(", seq=%" PRIu32
249 ", targetFlags=0x%08x, resolvedAction=%d, age=%" PRId64 "ms",
250 entry.seq, entry.targetFlags, entry.resolvedAction,
251 ns2ms(currentTime - entry.eventEntry->eventTime));
252 if (entry.deliveryTime != 0) {
253 // This entry was delivered, so add information on how long we've been waiting
254 dump += StringPrintf(", wait=%" PRId64 "ms", ns2ms(currentTime - entry.deliveryTime));
255 }
256 dump.append("\n");
257 }
258 return dump;
259}
260
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700261/**
262 * Find the entry in std::unordered_map by key, and return it.
263 * If the entry is not found, return a default constructed entry.
264 *
265 * Useful when the entries are vectors, since an empty vector will be returned
266 * if the entry is not found.
267 * Also useful when the entries are sp<>. If an entry is not found, nullptr is returned.
268 */
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700269template <typename K, typename V>
270static V getValueByKey(const std::unordered_map<K, V>& map, K key) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700271 auto it = map.find(key);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700272 return it != map.end() ? it->second : V{};
Tiger Huang721e26f2018-07-24 22:26:19 +0800273}
274
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700275/**
276 * Find the entry in std::unordered_map by value, and remove it.
277 * If more than one entry has the same value, then all matching
278 * key-value pairs will be removed.
279 *
280 * Return true if at least one value has been removed.
281 */
282template <typename K, typename V>
283static bool removeByValue(std::unordered_map<K, V>& map, const V& value) {
284 bool removed = false;
285 for (auto it = map.begin(); it != map.end();) {
286 if (it->second == value) {
287 it = map.erase(it);
288 removed = true;
289 } else {
290 it++;
291 }
292 }
293 return removed;
294}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800295
Vishnu Nair958da932020-08-21 17:12:37 -0700296/**
297 * Find the entry in std::unordered_map by key and return the value as an optional.
298 */
299template <typename K, typename V>
300static std::optional<V> getOptionalValueByKey(const std::unordered_map<K, V>& map, K key) {
301 auto it = map.find(key);
302 return it != map.end() ? std::optional<V>{it->second} : std::nullopt;
303}
304
chaviwaf87b3e2019-10-01 16:59:28 -0700305static bool haveSameToken(const sp<InputWindowHandle>& first, const sp<InputWindowHandle>& second) {
306 if (first == second) {
307 return true;
308 }
309
310 if (first == nullptr || second == nullptr) {
311 return false;
312 }
313
314 return first->getToken() == second->getToken();
315}
316
Siarhei Vishniakouadfd4fa2019-12-20 11:02:58 -0800317static bool isStaleEvent(nsecs_t currentTime, const EventEntry& entry) {
318 return currentTime - entry.eventTime >= STALE_EVENT_TIMEOUT;
319}
320
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000321static std::unique_ptr<DispatchEntry> createDispatchEntry(const InputTarget& inputTarget,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700322 std::shared_ptr<EventEntry> eventEntry,
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000323 int32_t inputTargetFlags) {
chaviw1ff3d1e2020-07-01 15:53:47 -0700324 if (inputTarget.useDefaultPointerTransform()) {
325 const ui::Transform& transform = inputTarget.getDefaultPointerTransform();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700326 return std::make_unique<DispatchEntry>(eventEntry, inputTargetFlags, transform,
chaviw1ff3d1e2020-07-01 15:53:47 -0700327 inputTarget.globalScaleFactor);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000328 }
329
330 ALOG_ASSERT(eventEntry->type == EventEntry::Type::MOTION);
331 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
332
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700333 std::vector<PointerCoords> pointerCoords;
334 pointerCoords.resize(motionEntry.pointerCount);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000335
336 // Use the first pointer information to normalize all other pointers. This could be any pointer
337 // as long as all other pointers are normalized to the same value and the final DispatchEntry
chaviw1ff3d1e2020-07-01 15:53:47 -0700338 // uses the transform for the normalized pointer.
339 const ui::Transform& firstPointerTransform =
340 inputTarget.pointerTransforms[inputTarget.pointerIds.firstMarkedBit()];
341 ui::Transform inverseFirstTransform = firstPointerTransform.inverse();
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000342
343 // Iterate through all pointers in the event to normalize against the first.
344 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.pointerCount; pointerIndex++) {
345 const PointerProperties& pointerProperties = motionEntry.pointerProperties[pointerIndex];
346 uint32_t pointerId = uint32_t(pointerProperties.id);
chaviw1ff3d1e2020-07-01 15:53:47 -0700347 const ui::Transform& currTransform = inputTarget.pointerTransforms[pointerId];
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000348
349 pointerCoords[pointerIndex].copyFrom(motionEntry.pointerCoords[pointerIndex]);
chaviw1ff3d1e2020-07-01 15:53:47 -0700350 // First, apply the current pointer's transform to update the coordinates into
351 // window space.
352 pointerCoords[pointerIndex].transform(currTransform);
353 // Next, apply the inverse transform of the normalized coordinates so the
354 // current coordinates are transformed into the normalized coordinate space.
355 pointerCoords[pointerIndex].transform(inverseFirstTransform);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000356 }
357
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700358 std::unique_ptr<MotionEntry> combinedMotionEntry =
359 std::make_unique<MotionEntry>(motionEntry.id, motionEntry.eventTime,
360 motionEntry.deviceId, motionEntry.source,
361 motionEntry.displayId, motionEntry.policyFlags,
362 motionEntry.action, motionEntry.actionButton,
363 motionEntry.flags, motionEntry.metaState,
364 motionEntry.buttonState, motionEntry.classification,
365 motionEntry.edgeFlags, motionEntry.xPrecision,
366 motionEntry.yPrecision, motionEntry.xCursorPosition,
367 motionEntry.yCursorPosition, motionEntry.downTime,
368 motionEntry.pointerCount, motionEntry.pointerProperties,
369 pointerCoords.data(), 0 /* xOffset */, 0 /* yOffset */);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000370
371 if (motionEntry.injectionState) {
372 combinedMotionEntry->injectionState = motionEntry.injectionState;
373 combinedMotionEntry->injectionState->refCount += 1;
374 }
375
376 std::unique_ptr<DispatchEntry> dispatchEntry =
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700377 std::make_unique<DispatchEntry>(std::move(combinedMotionEntry), inputTargetFlags,
378 firstPointerTransform, inputTarget.globalScaleFactor);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000379 return dispatchEntry;
380}
381
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -0700382static void addGestureMonitors(const std::vector<Monitor>& monitors,
383 std::vector<TouchedMonitor>& outTouchedMonitors, float xOffset = 0,
384 float yOffset = 0) {
385 if (monitors.empty()) {
386 return;
387 }
388 outTouchedMonitors.reserve(monitors.size() + outTouchedMonitors.size());
389 for (const Monitor& monitor : monitors) {
390 outTouchedMonitors.emplace_back(monitor, xOffset, yOffset);
391 }
392}
393
Garfield Tan15601662020-09-22 15:32:38 -0700394static status_t openInputChannelPair(const std::string& name,
395 std::shared_ptr<InputChannel>& serverChannel,
396 std::unique_ptr<InputChannel>& clientChannel) {
397 std::unique_ptr<InputChannel> uniqueServerChannel;
398 status_t result = InputChannel::openInputChannelPair(name, uniqueServerChannel, clientChannel);
399
400 serverChannel = std::move(uniqueServerChannel);
401 return result;
402}
403
Vishnu Nair958da932020-08-21 17:12:37 -0700404const char* InputDispatcher::typeToString(InputDispatcher::FocusResult result) {
405 switch (result) {
406 case InputDispatcher::FocusResult::OK:
407 return "Ok";
408 case InputDispatcher::FocusResult::NO_WINDOW:
409 return "Window not found";
410 case InputDispatcher::FocusResult::NOT_FOCUSABLE:
411 return "Window not focusable";
412 case InputDispatcher::FocusResult::NOT_VISIBLE:
413 return "Window not visible";
414 }
415}
416
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500417template <typename T>
418static bool sharedPointersEqual(const std::shared_ptr<T>& lhs, const std::shared_ptr<T>& rhs) {
419 if (lhs == nullptr && rhs == nullptr) {
420 return true;
421 }
422 if (lhs == nullptr || rhs == nullptr) {
423 return false;
424 }
425 return *lhs == *rhs;
426}
427
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000428static sp<IPlatformCompatNative> getCompatService() {
429 sp<IBinder> service(defaultServiceManager()->getService(String16("platform_compat_native")));
430 if (service == nullptr) {
431 ALOGE("Failed to link to compat service");
432 return nullptr;
433 }
434 return interface_cast<IPlatformCompatNative>(service);
435}
436
Michael Wrightd02c5b62014-02-10 15:10:22 -0800437// --- InputDispatcher ---
438
Garfield Tan00f511d2019-06-12 16:55:40 -0700439InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy)
440 : mPolicy(policy),
441 mPendingEvent(nullptr),
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700442 mLastDropReason(DropReason::NOT_DROPPED),
Garfield Tanff1f1bb2020-01-28 13:24:04 -0800443 mIdGenerator(IdGenerator::Source::INPUT_DISPATCHER),
Garfield Tan00f511d2019-06-12 16:55:40 -0700444 mAppSwitchSawKeyDown(false),
445 mAppSwitchDueTime(LONG_LONG_MAX),
446 mNextUnblockedEvent(nullptr),
447 mDispatchEnabled(false),
448 mDispatchFrozen(false),
449 mInputFilterEnabled(false),
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -0800450 // mInTouchMode will be initialized by the WindowManager to the default device config.
451 // To avoid leaking stack in case that call never comes, and for tests,
452 // initialize it here anyways.
453 mInTouchMode(true),
Bernardo Rufinoea97d182020-08-19 14:43:14 +0100454 mMaximumObscuringOpacityForTouch(1.0f),
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000455 mFocusedDisplayId(ADISPLAY_ID_DEFAULT),
Prabir Pradhan99987712020-11-10 18:43:05 -0800456 mFocusedWindowRequestedPointerCapture(false),
457 mWindowTokenWithPointerCapture(nullptr),
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000458 mCompatService(getCompatService()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800459 mLooper = new Looper(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800460 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800461
Yi Kong9b14ac62018-07-17 13:48:38 -0700462 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800463
464 policy->getDispatcherConfiguration(&mConfig);
465}
466
467InputDispatcher::~InputDispatcher() {
468 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800469 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800470
471 resetKeyRepeatLocked();
472 releasePendingEventLocked();
473 drainInboundQueueLocked();
474 }
475
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700476 while (!mConnectionsByFd.empty()) {
477 sp<Connection> connection = mConnectionsByFd.begin()->second;
Garfield Tan15601662020-09-22 15:32:38 -0700478 removeInputChannel(connection->inputChannel->getConnectionToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800479 }
480}
481
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700482status_t InputDispatcher::start() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700483 if (mThread) {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700484 return ALREADY_EXISTS;
485 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700486 mThread = std::make_unique<InputThread>(
487 "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
488 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700489}
490
491status_t InputDispatcher::stop() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700492 if (mThread && mThread->isCallingThread()) {
493 ALOGE("InputDispatcher cannot be stopped from its own thread!");
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700494 return INVALID_OPERATION;
495 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700496 mThread.reset();
497 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700498}
499
Michael Wrightd02c5b62014-02-10 15:10:22 -0800500void InputDispatcher::dispatchOnce() {
501 nsecs_t nextWakeupTime = LONG_LONG_MAX;
502 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800503 std::scoped_lock _l(mLock);
504 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800505
506 // Run a dispatch loop if there are no pending commands.
507 // The dispatch loop might enqueue commands to run afterwards.
508 if (!haveCommandsLocked()) {
509 dispatchOnceInnerLocked(&nextWakeupTime);
510 }
511
512 // Run all pending commands if there are any.
513 // If any commands were run then force the next poll to wake up immediately.
514 if (runCommandsLockedInterruptible()) {
515 nextWakeupTime = LONG_LONG_MIN;
516 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800517
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700518 // If we are still waiting for ack on some events,
519 // we might have to wake up earlier to check if an app is anr'ing.
520 const nsecs_t nextAnrCheck = processAnrsLocked();
521 nextWakeupTime = std::min(nextWakeupTime, nextAnrCheck);
522
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800523 // We are about to enter an infinitely long sleep, because we have no commands or
524 // pending or queued events
525 if (nextWakeupTime == LONG_LONG_MAX) {
526 mDispatcherEnteredIdle.notify_all();
527 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800528 } // release lock
529
530 // Wait for callback or timeout or wake. (make sure we round up, not down)
531 nsecs_t currentTime = now();
532 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
533 mLooper->pollOnce(timeoutMillis);
534}
535
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700536/**
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500537 * Raise ANR if there is no focused window.
538 * Before the ANR is raised, do a final state check:
539 * 1. The currently focused application must be the same one we are waiting for.
540 * 2. Ensure we still don't have a focused window.
541 */
542void InputDispatcher::processNoFocusedWindowAnrLocked() {
543 // Check if the application that we are waiting for is still focused.
544 std::shared_ptr<InputApplicationHandle> focusedApplication =
545 getValueByKey(mFocusedApplicationHandlesByDisplay, mAwaitedApplicationDisplayId);
546 if (focusedApplication == nullptr ||
547 focusedApplication->getApplicationToken() !=
548 mAwaitedFocusedApplication->getApplicationToken()) {
549 // Unexpected because we should have reset the ANR timer when focused application changed
550 ALOGE("Waited for a focused window, but focused application has already changed to %s",
551 focusedApplication->getName().c_str());
552 return; // The focused application has changed.
553 }
554
555 const sp<InputWindowHandle>& focusedWindowHandle =
556 getFocusedWindowHandleLocked(mAwaitedApplicationDisplayId);
557 if (focusedWindowHandle != nullptr) {
558 return; // We now have a focused window. No need for ANR.
559 }
560 onAnrLocked(mAwaitedFocusedApplication);
561}
562
563/**
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700564 * Check if any of the connections' wait queues have events that are too old.
565 * If we waited for events to be ack'ed for more than the window timeout, raise an ANR.
566 * Return the time at which we should wake up next.
567 */
568nsecs_t InputDispatcher::processAnrsLocked() {
569 const nsecs_t currentTime = now();
570 nsecs_t nextAnrCheck = LONG_LONG_MAX;
571 // Check if we are waiting for a focused window to appear. Raise ANR if waited too long
572 if (mNoFocusedWindowTimeoutTime.has_value() && mAwaitedFocusedApplication != nullptr) {
573 if (currentTime >= *mNoFocusedWindowTimeoutTime) {
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500574 processNoFocusedWindowAnrLocked();
Chris Yea209fde2020-07-22 13:54:51 -0700575 mAwaitedFocusedApplication.reset();
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500576 mNoFocusedWindowTimeoutTime = std::nullopt;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700577 return LONG_LONG_MIN;
578 } else {
Siarhei Vishniakou38a6d272020-10-20 20:29:33 -0500579 // Keep waiting. We will drop the event when mNoFocusedWindowTimeoutTime comes.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700580 nextAnrCheck = *mNoFocusedWindowTimeoutTime;
581 }
582 }
583
584 // Check if any connection ANRs are due
585 nextAnrCheck = std::min(nextAnrCheck, mAnrTracker.firstTimeout());
586 if (currentTime < nextAnrCheck) { // most likely scenario
587 return nextAnrCheck; // everything is normal. Let's check again at nextAnrCheck
588 }
589
590 // If we reached here, we have an unresponsive connection.
591 sp<Connection> connection = getConnectionLocked(mAnrTracker.firstToken());
592 if (connection == nullptr) {
593 ALOGE("Could not find connection for entry %" PRId64, mAnrTracker.firstTimeout());
594 return nextAnrCheck;
595 }
596 connection->responsive = false;
597 // Stop waking up for this unresponsive connection
598 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -0500599 onAnrLocked(*connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700600 return LONG_LONG_MIN;
601}
602
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500603std::chrono::nanoseconds InputDispatcher::getDispatchingTimeoutLocked(const sp<IBinder>& token) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700604 sp<InputWindowHandle> window = getWindowHandleLocked(token);
605 if (window != nullptr) {
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500606 return window->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700607 }
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500608 return DEFAULT_INPUT_DISPATCHING_TIMEOUT;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700609}
610
Michael Wrightd02c5b62014-02-10 15:10:22 -0800611void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
612 nsecs_t currentTime = now();
613
Jeff Browndc5992e2014-04-11 01:27:26 -0700614 // Reset the key repeat timer whenever normal dispatch is suspended while the
615 // device is in a non-interactive state. This is to ensure that we abort a key
616 // repeat if the device is just coming out of sleep.
617 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800618 resetKeyRepeatLocked();
619 }
620
621 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
622 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +0100623 if (DEBUG_FOCUS) {
624 ALOGD("Dispatch frozen. Waiting some more.");
625 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800626 return;
627 }
628
629 // Optimize latency of app switches.
630 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
631 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
632 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
633 if (mAppSwitchDueTime < *nextWakeupTime) {
634 *nextWakeupTime = mAppSwitchDueTime;
635 }
636
637 // Ready to start a new event.
638 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700639 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700640 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800641 if (isAppSwitchDue) {
642 // The inbound queue is empty so the app switch key we were waiting
643 // for will never arrive. Stop waiting for it.
644 resetPendingAppSwitchLocked(false);
645 isAppSwitchDue = false;
646 }
647
648 // Synthesize a key repeat if appropriate.
649 if (mKeyRepeatState.lastKeyEntry) {
650 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
651 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
652 } else {
653 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
654 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
655 }
656 }
657 }
658
659 // Nothing to do if there is no pending event.
660 if (!mPendingEvent) {
661 return;
662 }
663 } else {
664 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700665 mPendingEvent = mInboundQueue.front();
666 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800667 traceInboundQueueLengthLocked();
668 }
669
670 // Poke user activity for this event.
671 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700672 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800673 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800674 }
675
676 // Now we have an event to dispatch.
677 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700678 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800679 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700680 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800681 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700682 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800683 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700684 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800685 }
686
687 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700688 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800689 }
690
691 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700692 case EventEntry::Type::CONFIGURATION_CHANGED: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700693 const ConfigurationChangedEntry& typedEntry =
694 static_cast<const ConfigurationChangedEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700695 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700696 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700697 break;
698 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800699
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700700 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700701 const DeviceResetEntry& typedEntry =
702 static_cast<const DeviceResetEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700703 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700704 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700705 break;
706 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800707
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100708 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700709 std::shared_ptr<FocusEntry> typedEntry =
710 std::static_pointer_cast<FocusEntry>(mPendingEvent);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100711 dispatchFocusLocked(currentTime, typedEntry);
712 done = true;
713 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
714 break;
715 }
716
Prabir Pradhan99987712020-11-10 18:43:05 -0800717 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
718 const auto typedEntry =
719 std::static_pointer_cast<PointerCaptureChangedEntry>(mPendingEvent);
720 dispatchPointerCaptureChangedLocked(currentTime, typedEntry, dropReason);
721 done = true;
722 break;
723 }
724
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700725 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700726 std::shared_ptr<KeyEntry> keyEntry = std::static_pointer_cast<KeyEntry>(mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700727 if (isAppSwitchDue) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700728 if (isAppSwitchKeyEvent(*keyEntry)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700729 resetPendingAppSwitchLocked(true);
730 isAppSwitchDue = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700731 } else if (dropReason == DropReason::NOT_DROPPED) {
732 dropReason = DropReason::APP_SWITCH;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700733 }
734 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700735 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *keyEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700736 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700737 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700738 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
739 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700740 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700741 done = dispatchKeyLocked(currentTime, keyEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700742 break;
743 }
744
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700745 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700746 std::shared_ptr<MotionEntry> motionEntry =
747 std::static_pointer_cast<MotionEntry>(mPendingEvent);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700748 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
749 dropReason = DropReason::APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800750 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700751 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *motionEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700752 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700753 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700754 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
755 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700756 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700757 done = dispatchMotionLocked(currentTime, motionEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700758 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800759 }
Chris Yef59a2f42020-10-16 12:55:26 -0700760
761 case EventEntry::Type::SENSOR: {
762 std::shared_ptr<SensorEntry> sensorEntry =
763 std::static_pointer_cast<SensorEntry>(mPendingEvent);
764 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
765 dropReason = DropReason::APP_SWITCH;
766 }
767 // Sensor timestamps use SYSTEM_TIME_BOOTTIME time base, so we can't use
768 // 'currentTime' here, get SYSTEM_TIME_BOOTTIME instead.
769 nsecs_t bootTime = systemTime(SYSTEM_TIME_BOOTTIME);
770 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(bootTime, *sensorEntry)) {
771 dropReason = DropReason::STALE;
772 }
773 dispatchSensorLocked(currentTime, sensorEntry, &dropReason, nextWakeupTime);
774 done = true;
775 break;
776 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800777 }
778
779 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700780 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700781 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800782 }
Michael Wright3a981722015-06-10 15:26:13 +0100783 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800784
785 releasePendingEventLocked();
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700786 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -0800787 }
788}
789
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700790/**
791 * Return true if the events preceding this incoming motion event should be dropped
792 * Return false otherwise (the default behaviour)
793 */
794bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700795 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700796 (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700797
798 // Optimize case where the current application is unresponsive and the user
799 // decides to touch a window in a different application.
800 // If the application takes too long to catch up then we drop all events preceding
801 // the touch into the other window.
802 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700803 int32_t displayId = motionEntry.displayId;
804 int32_t x = static_cast<int32_t>(
805 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
806 int32_t y = static_cast<int32_t>(
807 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
808 sp<InputWindowHandle> touchedWindowHandle =
809 findTouchedWindowAtLocked(displayId, x, y, nullptr);
810 if (touchedWindowHandle != nullptr &&
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700811 touchedWindowHandle->getApplicationToken() !=
812 mAwaitedFocusedApplication->getApplicationToken()) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700813 // User touched a different application than the one we are waiting on.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700814 ALOGI("Pruning input queue because user touched a different application while waiting "
815 "for %s",
816 mAwaitedFocusedApplication->getName().c_str());
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700817 return true;
818 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700819
820 // Alternatively, maybe there's a gesture monitor that could handle this event
821 std::vector<TouchedMonitor> gestureMonitors =
822 findTouchedGestureMonitorsLocked(displayId, {});
823 for (TouchedMonitor& gestureMonitor : gestureMonitors) {
824 sp<Connection> connection =
825 getConnectionLocked(gestureMonitor.monitor.inputChannel->getConnectionToken());
Siarhei Vishniakou34ed4d42020-06-18 00:43:02 +0000826 if (connection != nullptr && connection->responsive) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700827 // This monitor could take more input. Drop all events preceding this
828 // event, so that gesture monitor could get a chance to receive the stream
829 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
830 "responsive gesture monitor that may handle the event",
831 mAwaitedFocusedApplication->getName().c_str());
832 return true;
833 }
834 }
835 }
836
837 // Prevent getting stuck: if we have a pending key event, and some motion events that have not
838 // yet been processed by some connections, the dispatcher will wait for these motion
839 // events to be processed before dispatching the key event. This is because these motion events
840 // may cause a new window to be launched, which the user might expect to receive focus.
841 // To prevent waiting forever for such events, just send the key to the currently focused window
842 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
843 ALOGD("Received a new pointer down event, stop waiting for events to process and "
844 "just send the pending key event to the focused window.");
845 mKeyIsWaitingForEventsTimeout = now();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700846 }
847 return false;
848}
849
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700850bool InputDispatcher::enqueueInboundEventLocked(std::unique_ptr<EventEntry> newEntry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700851 bool needWake = mInboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700852 mInboundQueue.push_back(std::move(newEntry));
853 EventEntry& entry = *(mInboundQueue.back());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800854 traceInboundQueueLengthLocked();
855
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700856 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700857 case EventEntry::Type::KEY: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700858 // Optimize app switch latency.
859 // If the application takes too long to catch up then we drop all events preceding
860 // the app switch key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700861 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700862 if (isAppSwitchKeyEvent(keyEntry)) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700863 if (keyEntry.action == AKEY_EVENT_ACTION_DOWN) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700864 mAppSwitchSawKeyDown = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700865 } else if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700866 if (mAppSwitchSawKeyDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800867#if DEBUG_APP_SWITCH
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700868 ALOGD("App switch is pending!");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800869#endif
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700870 mAppSwitchDueTime = keyEntry.eventTime + APP_SWITCH_TIMEOUT;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700871 mAppSwitchSawKeyDown = false;
872 needWake = true;
873 }
874 }
875 }
876 break;
877 }
878
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700879 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700880 if (shouldPruneInboundQueueLocked(static_cast<MotionEntry&>(entry))) {
881 mNextUnblockedEvent = mInboundQueue.back();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700882 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800883 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700884 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800885 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100886 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700887 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
888 break;
889 }
890 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -0800891 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -0700892 case EventEntry::Type::SENSOR:
Prabir Pradhan99987712020-11-10 18:43:05 -0800893 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700894 // nothing to do
895 break;
896 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800897 }
898
899 return needWake;
900}
901
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700902void InputDispatcher::addRecentEventLocked(std::shared_ptr<EventEntry> entry) {
Chris Yef59a2f42020-10-16 12:55:26 -0700903 // Do not store sensor event in recent queue to avoid flooding the queue.
904 if (entry->type != EventEntry::Type::SENSOR) {
905 mRecentQueue.push_back(entry);
906 }
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700907 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700908 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800909 }
910}
911
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700912sp<InputWindowHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, int32_t x,
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700913 int32_t y, TouchState* touchState,
914 bool addOutsideTargets,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700915 bool addPortalWindows) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700916 if ((addPortalWindows || addOutsideTargets) && touchState == nullptr) {
917 LOG_ALWAYS_FATAL(
918 "Must provide a valid touch state if adding portal windows or outside targets");
919 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800920 // Traverse windows from front to back to find touched window.
Vishnu Nairad321cd2020-08-20 16:40:21 -0700921 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800922 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800923 const InputWindowInfo* windowInfo = windowHandle->getInfo();
924 if (windowInfo->displayId == displayId) {
Michael Wright44753b12020-07-08 13:48:11 +0100925 auto flags = windowInfo->flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800926
927 if (windowInfo->visible) {
Michael Wright44753b12020-07-08 13:48:11 +0100928 if (!flags.test(InputWindowInfo::Flag::NOT_TOUCHABLE)) {
929 bool isTouchModal = !flags.test(InputWindowInfo::Flag::NOT_FOCUSABLE) &&
930 !flags.test(InputWindowInfo::Flag::NOT_TOUCH_MODAL);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800931 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800932 int32_t portalToDisplayId = windowInfo->portalToDisplayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700933 if (portalToDisplayId != ADISPLAY_ID_NONE &&
934 portalToDisplayId != displayId) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800935 if (addPortalWindows) {
936 // For the monitoring channels of the display.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700937 touchState->addPortalWindow(windowHandle);
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800938 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700939 return findTouchedWindowAtLocked(portalToDisplayId, x, y, touchState,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700940 addOutsideTargets, addPortalWindows);
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800941 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800942 // Found window.
943 return windowHandle;
944 }
945 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800946
Michael Wright44753b12020-07-08 13:48:11 +0100947 if (addOutsideTargets && flags.test(InputWindowInfo::Flag::WATCH_OUTSIDE_TOUCH)) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700948 touchState->addOrUpdateWindow(windowHandle,
949 InputTarget::FLAG_DISPATCH_AS_OUTSIDE,
950 BitSet32(0));
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800951 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800952 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800953 }
954 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700955 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800956}
957
Garfield Tane84e6f92019-08-29 17:28:41 -0700958std::vector<TouchedMonitor> InputDispatcher::findTouchedGestureMonitorsLocked(
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -0700959 int32_t displayId, const std::vector<sp<InputWindowHandle>>& portalWindows) const {
Michael Wright3dd60e22019-03-27 22:06:44 +0000960 std::vector<TouchedMonitor> touchedMonitors;
961
962 std::vector<Monitor> monitors = getValueByKey(mGestureMonitorsByDisplay, displayId);
963 addGestureMonitors(monitors, touchedMonitors);
964 for (const sp<InputWindowHandle>& portalWindow : portalWindows) {
965 const InputWindowInfo* windowInfo = portalWindow->getInfo();
966 monitors = getValueByKey(mGestureMonitorsByDisplay, windowInfo->portalToDisplayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700967 addGestureMonitors(monitors, touchedMonitors, -windowInfo->frameLeft,
968 -windowInfo->frameTop);
Michael Wright3dd60e22019-03-27 22:06:44 +0000969 }
970 return touchedMonitors;
971}
972
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700973void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800974 const char* reason;
975 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700976 case DropReason::POLICY:
Michael Wrightd02c5b62014-02-10 15:10:22 -0800977#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700978 ALOGD("Dropped event because policy consumed it.");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800979#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700980 reason = "inbound event was dropped because the policy consumed it";
981 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700982 case DropReason::DISABLED:
983 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700984 ALOGI("Dropped event because input dispatch is disabled.");
985 }
986 reason = "inbound event was dropped because input dispatch is disabled";
987 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700988 case DropReason::APP_SWITCH:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700989 ALOGI("Dropped event because of pending overdue app switch.");
990 reason = "inbound event was dropped because of pending overdue app switch";
991 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700992 case DropReason::BLOCKED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700993 ALOGI("Dropped event because the current application is not responding and the user "
994 "has started interacting with a different application.");
995 reason = "inbound event was dropped because the current application is not responding "
996 "and the user has started interacting with a different application";
997 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700998 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700999 ALOGI("Dropped event because it is stale.");
1000 reason = "inbound event was dropped because it is stale";
1001 break;
Prabir Pradhan99987712020-11-10 18:43:05 -08001002 case DropReason::NO_POINTER_CAPTURE:
1003 ALOGI("Dropped event because there is no window with Pointer Capture.");
1004 reason = "inbound event was dropped because there is no window with Pointer Capture";
1005 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001006 case DropReason::NOT_DROPPED: {
1007 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001008 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001009 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001010 }
1011
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001012 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001013 case EventEntry::Type::KEY: {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001014 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
1015 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001016 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001017 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001018 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001019 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1020 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001021 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
1022 synthesizeCancelationEventsForAllConnectionsLocked(options);
1023 } else {
1024 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
1025 synthesizeCancelationEventsForAllConnectionsLocked(options);
1026 }
1027 break;
1028 }
Chris Yef59a2f42020-10-16 12:55:26 -07001029 case EventEntry::Type::SENSOR: {
1030 break;
1031 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001032 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
1033 break;
1034 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001035 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001036 case EventEntry::Type::CONFIGURATION_CHANGED:
1037 case EventEntry::Type::DEVICE_RESET: {
Chris Yef59a2f42020-10-16 12:55:26 -07001038 LOG_ALWAYS_FATAL("Should not drop %s events", NamedEnum::string(entry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001039 break;
1040 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001041 }
1042}
1043
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001044static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001045 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
1046 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001047}
1048
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001049bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
1050 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
1051 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
1052 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001053}
1054
1055bool InputDispatcher::isAppSwitchPendingLocked() {
1056 return mAppSwitchDueTime != LONG_LONG_MAX;
1057}
1058
1059void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
1060 mAppSwitchDueTime = LONG_LONG_MAX;
1061
1062#if DEBUG_APP_SWITCH
1063 if (handled) {
1064 ALOGD("App switch has arrived.");
1065 } else {
1066 ALOGD("App switch was abandoned.");
1067 }
1068#endif
1069}
1070
Michael Wrightd02c5b62014-02-10 15:10:22 -08001071bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001072 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001073}
1074
1075bool InputDispatcher::runCommandsLockedInterruptible() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001076 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001077 return false;
1078 }
1079
1080 do {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001081 std::unique_ptr<CommandEntry> commandEntry = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001082 mCommandQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001083 Command command = commandEntry->command;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001084 command(*this, commandEntry.get()); // commands are implicitly 'LockedInterruptible'
Michael Wrightd02c5b62014-02-10 15:10:22 -08001085
1086 commandEntry->connection.clear();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001087 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001088 return true;
1089}
1090
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001091void InputDispatcher::postCommandLocked(std::unique_ptr<CommandEntry> commandEntry) {
1092 mCommandQueue.push_back(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001093}
1094
1095void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001096 while (!mInboundQueue.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001097 std::shared_ptr<EventEntry> entry = mInboundQueue.front();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001098 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001099 releaseInboundEventLocked(entry);
1100 }
1101 traceInboundQueueLengthLocked();
1102}
1103
1104void InputDispatcher::releasePendingEventLocked() {
1105 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001106 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -07001107 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001108 }
1109}
1110
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001111void InputDispatcher::releaseInboundEventLocked(std::shared_ptr<EventEntry> entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001112 InjectionState* injectionState = entry->injectionState;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001113 if (injectionState && injectionState->injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001114#if DEBUG_DISPATCH_CYCLE
1115 ALOGD("Injected inbound event was dropped.");
1116#endif
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001117 setInjectionResult(*entry, InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001118 }
1119 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001120 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001121 }
1122 addRecentEventLocked(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001123}
1124
1125void InputDispatcher::resetKeyRepeatLocked() {
1126 if (mKeyRepeatState.lastKeyEntry) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001127 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001128 }
1129}
1130
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001131std::shared_ptr<KeyEntry> InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
1132 std::shared_ptr<KeyEntry> entry = mKeyRepeatState.lastKeyEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001133
Michael Wright2e732952014-09-24 13:26:59 -07001134 uint32_t policyFlags = entry->policyFlags &
1135 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001136
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001137 std::shared_ptr<KeyEntry> newEntry =
1138 std::make_unique<KeyEntry>(mIdGenerator.nextId(), currentTime, entry->deviceId,
1139 entry->source, entry->displayId, policyFlags, entry->action,
1140 entry->flags, entry->keyCode, entry->scanCode,
1141 entry->metaState, entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001142
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001143 newEntry->syntheticRepeat = true;
1144 mKeyRepeatState.lastKeyEntry = newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001145 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001146 return newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001147}
1148
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001149bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001150 const ConfigurationChangedEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001151#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001152 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry.eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001153#endif
1154
1155 // Reset key repeating in case a keyboard device was added or removed or something.
1156 resetKeyRepeatLocked();
1157
1158 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001159 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
1160 &InputDispatcher::doNotifyConfigurationChangedLockedInterruptible);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001161 commandEntry->eventTime = entry.eventTime;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001162 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001163 return true;
1164}
1165
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001166bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime,
1167 const DeviceResetEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001168#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001169 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry.eventTime,
1170 entry.deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001171#endif
1172
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001173 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, "device was reset");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001174 options.deviceId = entry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001175 synthesizeCancelationEventsForAllConnectionsLocked(options);
1176 return true;
1177}
1178
Vishnu Nairad321cd2020-08-20 16:40:21 -07001179void InputDispatcher::enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus,
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001180 std::string_view reason) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001181 if (mPendingEvent != nullptr) {
1182 // Move the pending event to the front of the queue. This will give the chance
1183 // for the pending event to get dispatched to the newly focused window
1184 mInboundQueue.push_front(mPendingEvent);
1185 mPendingEvent = nullptr;
1186 }
1187
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001188 std::unique_ptr<FocusEntry> focusEntry =
1189 std::make_unique<FocusEntry>(mIdGenerator.nextId(), now(), windowToken, hasFocus,
1190 reason);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001191
1192 // This event should go to the front of the queue, but behind all other focus events
1193 // Find the last focus event, and insert right after it
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001194 std::deque<std::shared_ptr<EventEntry>>::reverse_iterator it =
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001195 std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001196 [](const std::shared_ptr<EventEntry>& event) {
1197 return event->type == EventEntry::Type::FOCUS;
1198 });
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001199
1200 // Maintain the order of focus events. Insert the entry after all other focus events.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001201 mInboundQueue.insert(it.base(), std::move(focusEntry));
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001202}
1203
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001204void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime, std::shared_ptr<FocusEntry> entry) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05001205 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001206 if (channel == nullptr) {
1207 return; // Window has gone away
1208 }
1209 InputTarget target;
1210 target.inputChannel = channel;
1211 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1212 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001213 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
1214 channel->getName();
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001215 std::string reason = std::string("reason=").append(entry->reason);
1216 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001217 dispatchEventLocked(currentTime, entry, {target});
1218}
1219
Prabir Pradhan99987712020-11-10 18:43:05 -08001220void InputDispatcher::dispatchPointerCaptureChangedLocked(
1221 nsecs_t currentTime, const std::shared_ptr<PointerCaptureChangedEntry>& entry,
1222 DropReason& dropReason) {
1223 const bool haveWindowWithPointerCapture = mWindowTokenWithPointerCapture != nullptr;
1224 if (entry->pointerCaptureEnabled == haveWindowWithPointerCapture) {
1225 LOG_ALWAYS_FATAL_IF(mFocusedWindowRequestedPointerCapture,
1226 "The Pointer Capture state has already been dispatched to the window.");
1227 // Pointer capture was already forcefully disabled because of focus change.
1228 dropReason = DropReason::NOT_DROPPED;
1229 return;
1230 }
1231
1232 // Set drop reason for early returns
1233 dropReason = DropReason::NO_POINTER_CAPTURE;
1234
1235 sp<IBinder> token;
1236 if (entry->pointerCaptureEnabled) {
1237 // Enable Pointer Capture
1238 if (!mFocusedWindowRequestedPointerCapture) {
1239 // This can happen if a window requests capture and immediately releases capture.
1240 ALOGW("No window requested Pointer Capture.");
1241 return;
1242 }
1243 token = getValueByKey(mFocusedWindowTokenByDisplay, mFocusedDisplayId);
1244 LOG_ALWAYS_FATAL_IF(!token, "Cannot find focused window for Pointer Capture.");
1245 mWindowTokenWithPointerCapture = token;
1246 } else {
1247 // Disable Pointer Capture
1248 token = mWindowTokenWithPointerCapture;
1249 mWindowTokenWithPointerCapture = nullptr;
1250 mFocusedWindowRequestedPointerCapture = false;
1251 }
1252
1253 auto channel = getInputChannelLocked(token);
1254 if (channel == nullptr) {
1255 // Window has gone away, clean up Pointer Capture state.
1256 mWindowTokenWithPointerCapture = nullptr;
1257 mFocusedWindowRequestedPointerCapture = false;
1258 return;
1259 }
1260 InputTarget target;
1261 target.inputChannel = channel;
1262 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1263 entry->dispatchInProgress = true;
1264 dispatchEventLocked(currentTime, entry, {target});
1265
1266 dropReason = DropReason::NOT_DROPPED;
1267}
1268
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001269bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, std::shared_ptr<KeyEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001270 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001271 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001272 if (!entry->dispatchInProgress) {
1273 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1274 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1275 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1276 if (mKeyRepeatState.lastKeyEntry &&
Chris Ye2ad95392020-09-01 13:44:44 -07001277 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode &&
Michael Wrightd02c5b62014-02-10 15:10:22 -08001278 // We have seen two identical key downs in a row which indicates that the device
1279 // driver is automatically generating key repeats itself. We take note of the
1280 // repeat here, but we disable our own next key repeat timer since it is clear that
1281 // we will not need to synthesize key repeats ourselves.
Chris Ye2ad95392020-09-01 13:44:44 -07001282 mKeyRepeatState.lastKeyEntry->deviceId == entry->deviceId) {
1283 // Make sure we don't get key down from a different device. If a different
1284 // device Id has same key pressed down, the new device Id will replace the
1285 // current one to hold the key repeat with repeat count reset.
1286 // In the future when got a KEY_UP on the device id, drop it and do not
1287 // stop the key repeat on current device.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001288 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1289 resetKeyRepeatLocked();
1290 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
1291 } else {
1292 // Not a repeat. Save key down state in case we do see a repeat later.
1293 resetKeyRepeatLocked();
1294 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1295 }
1296 mKeyRepeatState.lastKeyEntry = entry;
Chris Ye2ad95392020-09-01 13:44:44 -07001297 } else if (entry->action == AKEY_EVENT_ACTION_UP && mKeyRepeatState.lastKeyEntry &&
1298 mKeyRepeatState.lastKeyEntry->deviceId != entry->deviceId) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001299 // The key on device 'deviceId' is still down, do not stop key repeat
Chris Ye2ad95392020-09-01 13:44:44 -07001300#if DEBUG_INBOUND_EVENT_DETAILS
1301 ALOGD("deviceId=%d got KEY_UP as stale", entry->deviceId);
1302#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001303 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001304 resetKeyRepeatLocked();
1305 }
1306
1307 if (entry->repeatCount == 1) {
1308 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1309 } else {
1310 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1311 }
1312
1313 entry->dispatchInProgress = true;
1314
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001315 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001316 }
1317
1318 // Handle case where the policy asked us to try again later last time.
1319 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
1320 if (currentTime < entry->interceptKeyWakeupTime) {
1321 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1322 *nextWakeupTime = entry->interceptKeyWakeupTime;
1323 }
1324 return false; // wait until next wakeup
1325 }
1326 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
1327 entry->interceptKeyWakeupTime = 0;
1328 }
1329
1330 // Give the policy a chance to intercept the key.
1331 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
1332 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001333 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
Siarhei Vishniakou49a350a2019-07-26 18:44:23 -07001334 &InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible);
Vishnu Nairad321cd2020-08-20 16:40:21 -07001335 sp<IBinder> focusedWindowToken =
1336 getValueByKey(mFocusedWindowTokenByDisplay, getTargetDisplayId(*entry));
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06001337 commandEntry->connectionToken = focusedWindowToken;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001338 commandEntry->keyEntry = entry;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001339 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001340 return false; // wait for the command to run
1341 } else {
1342 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
1343 }
1344 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001345 if (*dropReason == DropReason::NOT_DROPPED) {
1346 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001347 }
1348 }
1349
1350 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001351 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001352 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001353 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1354 : InputEventInjectionResult::FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001355 mReporter->reportDroppedKey(entry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001356 return true;
1357 }
1358
1359 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001360 std::vector<InputTarget> inputTargets;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001361 InputEventInjectionResult injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001362 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001363 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001364 return false;
1365 }
1366
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001367 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001368 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001369 return true;
1370 }
1371
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001372 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001373 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001374
1375 // Dispatch the key.
1376 dispatchEventLocked(currentTime, entry, inputTargets);
1377 return true;
1378}
1379
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001380void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001381#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01001382 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001383 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1384 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001385 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1386 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
1387 entry.repeatCount, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001388#endif
1389}
1390
Chris Yef59a2f42020-10-16 12:55:26 -07001391void InputDispatcher::doNotifySensorLockedInterruptible(CommandEntry* commandEntry) {
1392 mLock.unlock();
1393
1394 const std::shared_ptr<SensorEntry>& entry = commandEntry->sensorEntry;
1395 if (entry->accuracyChanged) {
1396 mPolicy->notifySensorAccuracy(entry->deviceId, entry->sensorType, entry->accuracy);
1397 }
1398 mPolicy->notifySensorEvent(entry->deviceId, entry->sensorType, entry->accuracy,
1399 entry->hwTimestamp, entry->values);
1400 mLock.lock();
1401}
1402
1403void InputDispatcher::dispatchSensorLocked(nsecs_t currentTime, std::shared_ptr<SensorEntry> entry,
1404 DropReason* dropReason, nsecs_t* nextWakeupTime) {
1405#if DEBUG_OUTBOUND_EVENT_DETAILS
1406 ALOGD("notifySensorEvent eventTime=%" PRId64 ", hwTimestamp=%" PRId64 ", deviceId=%d, "
1407 "source=0x%x, sensorType=%s",
1408 entry->eventTime, entry->hwTimestamp, entry->deviceId, entry->source,
1409 NamedEnum::string(sensorType).c_str());
1410#endif
1411 std::unique_ptr<CommandEntry> commandEntry =
1412 std::make_unique<CommandEntry>(&InputDispatcher::doNotifySensorLockedInterruptible);
1413 commandEntry->sensorEntry = entry;
1414 postCommandLocked(std::move(commandEntry));
1415}
1416
1417bool InputDispatcher::flushSensor(int deviceId, InputDeviceSensorType sensorType) {
1418#if DEBUG_OUTBOUND_EVENT_DETAILS
1419 ALOGD("flushSensor deviceId=%d, sensorType=%s", deviceId,
1420 NamedEnum::string(sensorType).c_str());
1421#endif
1422 { // acquire lock
1423 std::scoped_lock _l(mLock);
1424
1425 for (auto it = mInboundQueue.begin(); it != mInboundQueue.end(); it++) {
1426 std::shared_ptr<EventEntry> entry = *it;
1427 if (entry->type == EventEntry::Type::SENSOR) {
1428 it = mInboundQueue.erase(it);
1429 releaseInboundEventLocked(entry);
1430 }
1431 }
1432 }
1433 return true;
1434}
1435
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001436bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, std::shared_ptr<MotionEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001437 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001438 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001439 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001440 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001441 entry->dispatchInProgress = true;
1442
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001443 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001444 }
1445
1446 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001447 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001448 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001449 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1450 : InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001451 return true;
1452 }
1453
1454 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
1455
1456 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001457 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001458
1459 bool conflictingPointerActions = false;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001460 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001461 if (isPointerEvent) {
1462 // Pointer event. (eg. touchscreen)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001463 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001464 findTouchedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001465 &conflictingPointerActions);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001466 } else {
1467 // Non touch event. (eg. trackball)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001468 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001469 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001470 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001471 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001472 return false;
1473 }
1474
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001475 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001476 if (injectionResult == InputEventInjectionResult::PERMISSION_DENIED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001477 ALOGW("Permission denied, dropping the motion (isPointer=%s)", toString(isPointerEvent));
1478 return true;
1479 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001480 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001481 CancelationOptions::Mode mode(isPointerEvent
1482 ? CancelationOptions::CANCEL_POINTER_EVENTS
1483 : CancelationOptions::CANCEL_NON_POINTER_EVENTS);
1484 CancelationOptions options(mode, "input event injection failed");
1485 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001486 return true;
1487 }
1488
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001489 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001490 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001491
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001492 if (isPointerEvent) {
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07001493 std::unordered_map<int32_t, TouchState>::iterator it =
1494 mTouchStatesByDisplay.find(entry->displayId);
1495 if (it != mTouchStatesByDisplay.end()) {
1496 const TouchState& state = it->second;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001497 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001498 // The event has gone through these portal windows, so we add monitoring targets of
1499 // the corresponding displays as well.
1500 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001501 const InputWindowInfo* windowInfo = state.portalWindows[i]->getInfo();
Michael Wright3dd60e22019-03-27 22:06:44 +00001502 addGlobalMonitoringTargetsLocked(inputTargets, windowInfo->portalToDisplayId,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001503 -windowInfo->frameLeft, -windowInfo->frameTop);
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001504 }
1505 }
1506 }
1507 }
1508
Michael Wrightd02c5b62014-02-10 15:10:22 -08001509 // Dispatch the motion.
1510 if (conflictingPointerActions) {
1511 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001512 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001513 synthesizeCancelationEventsForAllConnectionsLocked(options);
1514 }
1515 dispatchEventLocked(currentTime, entry, inputTargets);
1516 return true;
1517}
1518
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001519void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001520#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08001521 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001522 ", policyFlags=0x%x, "
1523 "action=0x%x, actionButton=0x%x, flags=0x%x, "
1524 "metaState=0x%x, buttonState=0x%x,"
1525 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001526 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1527 entry.action, entry.actionButton, entry.flags, entry.metaState, entry.buttonState,
1528 entry.edgeFlags, entry.xPrecision, entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001529
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001530 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001531 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001532 "x=%f, y=%f, pressure=%f, size=%f, "
1533 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1534 "orientation=%f",
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001535 i, entry.pointerProperties[i].id, entry.pointerProperties[i].toolType,
1536 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1537 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1538 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1539 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1540 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1541 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1542 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1543 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1544 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001545 }
1546#endif
1547}
1548
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001549void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
1550 std::shared_ptr<EventEntry> eventEntry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001551 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001552 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001553#if DEBUG_DISPATCH_CYCLE
1554 ALOGD("dispatchEventToCurrentInputTargets");
1555#endif
1556
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001557 updateInteractionTokensLocked(*eventEntry, inputTargets);
1558
Michael Wrightd02c5b62014-02-10 15:10:22 -08001559 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1560
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001561 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001562
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001563 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001564 sp<Connection> connection =
1565 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001566 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08001567 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001568 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001569 if (DEBUG_FOCUS) {
1570 ALOGD("Dropping event delivery to target with channel '%s' because it "
1571 "is no longer registered with the input dispatcher.",
1572 inputTarget.inputChannel->getName().c_str());
1573 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001574 }
1575 }
1576}
1577
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001578void InputDispatcher::cancelEventsForAnrLocked(const sp<Connection>& connection) {
1579 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
1580 // If the policy decides to close the app, we will get a channel removal event via
1581 // unregisterInputChannel, and will clean up the connection that way. We are already not
1582 // sending new pointers to the connection when it blocked, but focused events will continue to
1583 // pile up.
1584 ALOGW("Canceling events for %s because it is unresponsive",
1585 connection->inputChannel->getName().c_str());
1586 if (connection->status == Connection::STATUS_NORMAL) {
1587 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1588 "application not responding");
1589 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001590 }
1591}
1592
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001593void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001594 if (DEBUG_FOCUS) {
1595 ALOGD("Resetting ANR timeouts.");
1596 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001597
1598 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001599 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07001600 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001601}
1602
Tiger Huang721e26f2018-07-24 22:26:19 +08001603/**
1604 * Get the display id that the given event should go to. If this event specifies a valid display id,
1605 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1606 * Focused display is the display that the user most recently interacted with.
1607 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001608int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001609 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001610 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001611 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001612 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1613 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001614 break;
1615 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001616 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001617 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1618 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001619 break;
1620 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001621 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001622 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001623 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07001624 case EventEntry::Type::DEVICE_RESET:
1625 case EventEntry::Type::SENSOR: {
1626 ALOGE("%s events do not have a target display", NamedEnum::string(entry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001627 return ADISPLAY_ID_NONE;
1628 }
Tiger Huang721e26f2018-07-24 22:26:19 +08001629 }
1630 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1631}
1632
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001633bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
1634 const char* focusedWindowName) {
1635 if (mAnrTracker.empty()) {
1636 // already processed all events that we waited for
1637 mKeyIsWaitingForEventsTimeout = std::nullopt;
1638 return false;
1639 }
1640
1641 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
1642 // Start the timer
1643 ALOGD("Waiting to send key to %s because there are unprocessed events that may cause "
1644 "focus to change",
1645 focusedWindowName);
Siarhei Vishniakou70622952020-07-30 11:17:23 -05001646 mKeyIsWaitingForEventsTimeout = currentTime +
1647 std::chrono::duration_cast<std::chrono::nanoseconds>(KEY_WAITING_FOR_EVENTS_TIMEOUT)
1648 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001649 return true;
1650 }
1651
1652 // We still have pending events, and already started the timer
1653 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
1654 return true; // Still waiting
1655 }
1656
1657 // Waited too long, and some connection still hasn't processed all motions
1658 // Just send the key to the focused window
1659 ALOGW("Dispatching key to %s even though there are other unprocessed events",
1660 focusedWindowName);
1661 mKeyIsWaitingForEventsTimeout = std::nullopt;
1662 return false;
1663}
1664
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001665InputEventInjectionResult InputDispatcher::findFocusedWindowTargetsLocked(
1666 nsecs_t currentTime, const EventEntry& entry, std::vector<InputTarget>& inputTargets,
1667 nsecs_t* nextWakeupTime) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001668 std::string reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001669
Tiger Huang721e26f2018-07-24 22:26:19 +08001670 int32_t displayId = getTargetDisplayId(entry);
Vishnu Nairad321cd2020-08-20 16:40:21 -07001671 sp<InputWindowHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07001672 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08001673 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1674
Michael Wrightd02c5b62014-02-10 15:10:22 -08001675 // If there is no currently focused window and no focused application
1676 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001677 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
1678 ALOGI("Dropping %s event because there is no focused window or focused application in "
1679 "display %" PRId32 ".",
Chris Yef59a2f42020-10-16 12:55:26 -07001680 NamedEnum::string(entry.type).c_str(), displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001681 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001682 }
1683
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001684 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
1685 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
1686 // start interacting with another application via touch (app switch). This code can be removed
1687 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
1688 // an app is expected to have a focused window.
1689 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
1690 if (!mNoFocusedWindowTimeoutTime.has_value()) {
1691 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001692 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
1693 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
1694 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001695 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05001696 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001697 ALOGW("Waiting because no window has focus but %s may eventually add a "
1698 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001699 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001700 *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001701 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001702 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
1703 // Already raised ANR. Drop the event
1704 ALOGE("Dropping %s event because there is no focused window",
Chris Yef59a2f42020-10-16 12:55:26 -07001705 NamedEnum::string(entry.type).c_str());
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001706 return InputEventInjectionResult::FAILED;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001707 } else {
1708 // Still waiting for the focused window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001709 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001710 }
1711 }
1712
1713 // we have a valid, non-null focused window
1714 resetNoFocusedWindowTimeoutLocked();
1715
Michael Wrightd02c5b62014-02-10 15:10:22 -08001716 // Check permissions.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001717 if (!checkInjectionPermission(focusedWindowHandle, entry.injectionState)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001718 return InputEventInjectionResult::PERMISSION_DENIED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001719 }
1720
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001721 if (focusedWindowHandle->getInfo()->paused) {
1722 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001723 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001724 }
1725
1726 // If the event is a key event, then we must wait for all previous events to
1727 // complete before delivering it because previous events may have the
1728 // side-effect of transferring focus to a different window and we want to
1729 // ensure that the following keys are sent to the new window.
1730 //
1731 // Suppose the user touches a button in a window then immediately presses "A".
1732 // If the button causes a pop-up window to appear then we want to ensure that
1733 // the "A" key is delivered to the new pop-up window. This is because users
1734 // often anticipate pending UI changes when typing on a keyboard.
1735 // To obtain this behavior, we must serialize key events with respect to all
1736 // prior input events.
1737 if (entry.type == EventEntry::Type::KEY) {
1738 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
1739 *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001740 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001741 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001742 }
1743
1744 // Success! Output targets.
Tiger Huang721e26f2018-07-24 22:26:19 +08001745 addWindowTargetLocked(focusedWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001746 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS,
1747 BitSet32(0), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001748
1749 // Done.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001750 return InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001751}
1752
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001753/**
1754 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
1755 * that are currently unresponsive.
1756 */
1757std::vector<TouchedMonitor> InputDispatcher::selectResponsiveMonitorsLocked(
1758 const std::vector<TouchedMonitor>& monitors) const {
1759 std::vector<TouchedMonitor> responsiveMonitors;
1760 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
1761 [this](const TouchedMonitor& monitor) REQUIRES(mLock) {
1762 sp<Connection> connection = getConnectionLocked(
1763 monitor.monitor.inputChannel->getConnectionToken());
1764 if (connection == nullptr) {
1765 ALOGE("Could not find connection for monitor %s",
1766 monitor.monitor.inputChannel->getName().c_str());
1767 return false;
1768 }
1769 if (!connection->responsive) {
1770 ALOGW("Unresponsive monitor %s will not get the new gesture",
1771 connection->inputChannel->getName().c_str());
1772 return false;
1773 }
1774 return true;
1775 });
1776 return responsiveMonitors;
1777}
1778
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001779InputEventInjectionResult InputDispatcher::findTouchedWindowTargetsLocked(
1780 nsecs_t currentTime, const MotionEntry& entry, std::vector<InputTarget>& inputTargets,
1781 nsecs_t* nextWakeupTime, bool* outConflictingPointerActions) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001782 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001783 enum InjectionPermission {
1784 INJECTION_PERMISSION_UNKNOWN,
1785 INJECTION_PERMISSION_GRANTED,
1786 INJECTION_PERMISSION_DENIED
1787 };
1788
Michael Wrightd02c5b62014-02-10 15:10:22 -08001789 // For security reasons, we defer updating the touch state until we are sure that
1790 // event injection will be allowed.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001791 int32_t displayId = entry.displayId;
1792 int32_t action = entry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001793 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
1794
1795 // Update the touch state as needed based on the properties of the touch event.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001796 InputEventInjectionResult injectionResult = InputEventInjectionResult::PENDING;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001797 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
Garfield Tandf26e862020-07-01 20:18:19 -07001798 sp<InputWindowHandle> newHoverWindowHandle(mLastHoverWindowHandle);
1799 sp<InputWindowHandle> newTouchedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001800
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001801 // Copy current touch state into tempTouchState.
1802 // This state will be used to update mTouchStatesByDisplay at the end of this function.
1803 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07001804 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001805 TouchState tempTouchState;
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07001806 std::unordered_map<int32_t, TouchState>::iterator oldStateIt =
1807 mTouchStatesByDisplay.find(displayId);
1808 if (oldStateIt != mTouchStatesByDisplay.end()) {
1809 oldState = &(oldStateIt->second);
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001810 tempTouchState.copyFrom(*oldState);
Jeff Brownf086ddb2014-02-11 14:28:48 -08001811 }
1812
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001813 bool isSplit = tempTouchState.split;
1814 bool switchedDevice = tempTouchState.deviceId >= 0 && tempTouchState.displayId >= 0 &&
1815 (tempTouchState.deviceId != entry.deviceId || tempTouchState.source != entry.source ||
1816 tempTouchState.displayId != displayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001817 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
1818 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
1819 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
1820 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN ||
1821 maskedAction == AMOTION_EVENT_ACTION_SCROLL || isHoverAction);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001822 const bool isFromMouse = entry.source == AINPUT_SOURCE_MOUSE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001823 bool wrongDevice = false;
1824 if (newGesture) {
1825 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001826 if (switchedDevice && tempTouchState.down && !down && !isHoverAction) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001827 ALOGI("Dropping event because a pointer for a different device is already down "
1828 "in display %" PRId32,
1829 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001830 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001831 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001832 switchedDevice = false;
1833 wrongDevice = true;
1834 goto Failed;
1835 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001836 tempTouchState.reset();
1837 tempTouchState.down = down;
1838 tempTouchState.deviceId = entry.deviceId;
1839 tempTouchState.source = entry.source;
1840 tempTouchState.displayId = displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001841 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001842 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001843 ALOGI("Dropping move event because a pointer for a different device is already active "
1844 "in display %" PRId32,
1845 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001846 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001847 injectionResult = InputEventInjectionResult::PERMISSION_DENIED;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001848 switchedDevice = false;
1849 wrongDevice = true;
1850 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001851 }
1852
1853 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
1854 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
1855
Garfield Tan00f511d2019-06-12 16:55:40 -07001856 int32_t x;
1857 int32_t y;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001858 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Garfield Tan00f511d2019-06-12 16:55:40 -07001859 // Always dispatch mouse events to cursor position.
1860 if (isFromMouse) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001861 x = int32_t(entry.xCursorPosition);
1862 y = int32_t(entry.yCursorPosition);
Garfield Tan00f511d2019-06-12 16:55:40 -07001863 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001864 x = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X));
1865 y = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y));
Garfield Tan00f511d2019-06-12 16:55:40 -07001866 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001867 bool isDown = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Garfield Tandf26e862020-07-01 20:18:19 -07001868 newTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001869 findTouchedWindowAtLocked(displayId, x, y, &tempTouchState,
1870 isDown /*addOutsideTargets*/, true /*addPortalWindows*/);
Michael Wright3dd60e22019-03-27 22:06:44 +00001871
1872 std::vector<TouchedMonitor> newGestureMonitors = isDown
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001873 ? findTouchedGestureMonitorsLocked(displayId, tempTouchState.portalWindows)
Michael Wright3dd60e22019-03-27 22:06:44 +00001874 : std::vector<TouchedMonitor>{};
Michael Wrightd02c5b62014-02-10 15:10:22 -08001875
Michael Wrightd02c5b62014-02-10 15:10:22 -08001876 // Figure out whether splitting will be allowed for this window.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001877 if (newTouchedWindowHandle != nullptr &&
1878 newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Garfield Tanaddb02b2019-06-25 16:36:13 -07001879 // New window supports splitting, but we should never split mouse events.
1880 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001881 } else if (isSplit) {
1882 // New window does not support splitting but we have already split events.
1883 // Ignore the new window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001884 newTouchedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001885 }
1886
1887 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001888 if (newTouchedWindowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001889 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001890 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001891 }
1892
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001893 if (newTouchedWindowHandle != nullptr && newTouchedWindowHandle->getInfo()->paused) {
1894 ALOGI("Not sending touch event to %s because it is paused",
1895 newTouchedWindowHandle->getName().c_str());
1896 newTouchedWindowHandle = nullptr;
1897 }
1898
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001899 // Ensure the window has a connection and the connection is responsive
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001900 if (newTouchedWindowHandle != nullptr) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001901 const bool isResponsive = hasResponsiveConnectionLocked(*newTouchedWindowHandle);
1902 if (!isResponsive) {
1903 ALOGW("%s will not receive the new gesture at %" PRIu64,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001904 newTouchedWindowHandle->getName().c_str(), entry.eventTime);
1905 newTouchedWindowHandle = nullptr;
1906 }
1907 }
1908
Bernardo Rufinoea97d182020-08-19 14:43:14 +01001909 // Drop events that can't be trusted due to occlusion
1910 if (newTouchedWindowHandle != nullptr &&
1911 mBlockUntrustedTouchesMode != BlockUntrustedTouchesMode::DISABLED) {
1912 TouchOcclusionInfo occlusionInfo =
1913 computeTouchOcclusionInfoLocked(newTouchedWindowHandle, x, y);
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00001914 if (!isTouchTrustedLocked(occlusionInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00001915 if (DEBUG_TOUCH_OCCLUSION) {
1916 ALOGD("Stack of obscuring windows during untrusted touch (%d, %d):", x, y);
1917 for (const auto& log : occlusionInfo.debugInfo) {
1918 ALOGD("%s", log.c_str());
1919 }
1920 }
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00001921 onUntrustedTouchLocked(occlusionInfo.obscuringPackage);
1922 if (mBlockUntrustedTouchesMode == BlockUntrustedTouchesMode::BLOCK) {
1923 ALOGW("Dropping untrusted touch event due to %s/%d",
1924 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid);
1925 newTouchedWindowHandle = nullptr;
1926 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01001927 }
1928 }
1929
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001930 // Also don't send the new touch event to unresponsive gesture monitors
1931 newGestureMonitors = selectResponsiveMonitorsLocked(newGestureMonitors);
1932
Michael Wright3dd60e22019-03-27 22:06:44 +00001933 if (newTouchedWindowHandle == nullptr && newGestureMonitors.empty()) {
1934 ALOGI("Dropping event because there is no touchable window or gesture monitor at "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001935 "(%d, %d) in display %" PRId32 ".",
1936 x, y, displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001937 injectionResult = InputEventInjectionResult::FAILED;
Michael Wright3dd60e22019-03-27 22:06:44 +00001938 goto Failed;
1939 }
1940
1941 if (newTouchedWindowHandle != nullptr) {
1942 // Set target flags.
1943 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
1944 if (isSplit) {
1945 targetFlags |= InputTarget::FLAG_SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001946 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001947 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1948 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1949 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
1950 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1951 }
1952
1953 // Update hover state.
Garfield Tandf26e862020-07-01 20:18:19 -07001954 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
1955 newHoverWindowHandle = nullptr;
1956 } else if (isHoverAction) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001957 newHoverWindowHandle = newTouchedWindowHandle;
Michael Wright3dd60e22019-03-27 22:06:44 +00001958 }
1959
1960 // Update the temporary touch state.
1961 BitSet32 pointerIds;
1962 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001963 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wright3dd60e22019-03-27 22:06:44 +00001964 pointerIds.markBit(pointerId);
1965 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001966 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001967 }
1968
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001969 tempTouchState.addGestureMonitors(newGestureMonitors);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001970 } else {
1971 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
1972
1973 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001974 if (!tempTouchState.down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001975 if (DEBUG_FOCUS) {
1976 ALOGD("Dropping event because the pointer is not down or we previously "
1977 "dropped the pointer down event in display %" PRId32,
1978 displayId);
1979 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001980 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001981 goto Failed;
1982 }
1983
1984 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001985 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001986 tempTouchState.isSlippery()) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001987 int32_t x = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
1988 int32_t y = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001989
1990 sp<InputWindowHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001991 tempTouchState.getFirstForegroundWindowHandle();
Garfield Tandf26e862020-07-01 20:18:19 -07001992 newTouchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y, &tempTouchState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001993 if (oldTouchedWindowHandle != newTouchedWindowHandle &&
1994 oldTouchedWindowHandle != nullptr && newTouchedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001995 if (DEBUG_FOCUS) {
1996 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
1997 oldTouchedWindowHandle->getName().c_str(),
1998 newTouchedWindowHandle->getName().c_str(), displayId);
1999 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002000 // Make a slippery exit from the old window.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002001 tempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
2002 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT,
2003 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002004
2005 // Make a slippery entrance into the new window.
2006 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
2007 isSplit = true;
2008 }
2009
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002010 int32_t targetFlags =
2011 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002012 if (isSplit) {
2013 targetFlags |= InputTarget::FLAG_SPLIT;
2014 }
2015 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
2016 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002017 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
2018 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002019 }
2020
2021 BitSet32 pointerIds;
2022 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002023 pointerIds.markBit(entry.pointerProperties[0].id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002024 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002025 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002026 }
2027 }
2028 }
2029
2030 if (newHoverWindowHandle != mLastHoverWindowHandle) {
Garfield Tandf26e862020-07-01 20:18:19 -07002031 // Let the previous window know that the hover sequence is over, unless we already did it
2032 // when dispatching it as is to newTouchedWindowHandle.
2033 if (mLastHoverWindowHandle != nullptr &&
2034 (maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT ||
2035 mLastHoverWindowHandle != newTouchedWindowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002036#if DEBUG_HOVER
2037 ALOGD("Sending hover exit event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002038 mLastHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002039#endif
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002040 tempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
2041 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002042 }
2043
Garfield Tandf26e862020-07-01 20:18:19 -07002044 // Let the new window know that the hover sequence is starting, unless we already did it
2045 // when dispatching it as is to newTouchedWindowHandle.
2046 if (newHoverWindowHandle != nullptr &&
2047 (maskedAction != AMOTION_EVENT_ACTION_HOVER_ENTER ||
2048 newHoverWindowHandle != newTouchedWindowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002049#if DEBUG_HOVER
2050 ALOGD("Sending hover enter event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002051 newHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002052#endif
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002053 tempTouchState.addOrUpdateWindow(newHoverWindowHandle,
2054 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER,
2055 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002056 }
2057 }
2058
2059 // Check permission to inject into all touched foreground windows and ensure there
2060 // is at least one touched foreground window.
2061 {
2062 bool haveForegroundWindow = false;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002063 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002064 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
2065 haveForegroundWindow = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002066 if (!checkInjectionPermission(touchedWindow.windowHandle, entry.injectionState)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002067 injectionResult = InputEventInjectionResult::PERMISSION_DENIED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002068 injectionPermission = INJECTION_PERMISSION_DENIED;
2069 goto Failed;
2070 }
2071 }
2072 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002073 bool hasGestureMonitor = !tempTouchState.gestureMonitors.empty();
Michael Wright3dd60e22019-03-27 22:06:44 +00002074 if (!haveForegroundWindow && !hasGestureMonitor) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002075 ALOGI("Dropping event because there is no touched foreground window in display "
2076 "%" PRId32 " or gesture monitor to receive it.",
2077 displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002078 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002079 goto Failed;
2080 }
2081
2082 // Permission granted to injection into all touched foreground windows.
2083 injectionPermission = INJECTION_PERMISSION_GRANTED;
2084 }
2085
2086 // Check whether windows listening for outside touches are owned by the same UID. If it is
2087 // set the policy flag that we will not reveal coordinate information to this window.
2088 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2089 sp<InputWindowHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002090 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002091 if (foregroundWindowHandle) {
2092 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002093 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002094 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2095 sp<InputWindowHandle> inputWindowHandle = touchedWindow.windowHandle;
2096 if (inputWindowHandle->getInfo()->ownerUid != foregroundWindowUid) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002097 tempTouchState.addOrUpdateWindow(inputWindowHandle,
2098 InputTarget::FLAG_ZERO_COORDS,
2099 BitSet32(0));
Michael Wright3dd60e22019-03-27 22:06:44 +00002100 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002101 }
2102 }
2103 }
2104 }
2105
Michael Wrightd02c5b62014-02-10 15:10:22 -08002106 // If this is the first pointer going down and the touched window has a wallpaper
2107 // then also add the touched wallpaper windows so they are locked in for the duration
2108 // of the touch gesture.
2109 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
2110 // engine only supports touch events. We would need to add a mechanism similar
2111 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
2112 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2113 sp<InputWindowHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002114 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002115 if (foregroundWindowHandle && foregroundWindowHandle->getInfo()->hasWallpaper) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07002116 const std::vector<sp<InputWindowHandle>>& windowHandles =
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002117 getWindowHandlesLocked(displayId);
2118 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002119 const InputWindowInfo* info = windowHandle->getInfo();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002120 if (info->displayId == displayId &&
Michael Wright44753b12020-07-08 13:48:11 +01002121 windowHandle->getInfo()->type == InputWindowInfo::Type::WALLPAPER) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002122 tempTouchState
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002123 .addOrUpdateWindow(windowHandle,
2124 InputTarget::FLAG_WINDOW_IS_OBSCURED |
2125 InputTarget::
2126 FLAG_WINDOW_IS_PARTIALLY_OBSCURED |
2127 InputTarget::FLAG_DISPATCH_AS_IS,
2128 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002129 }
2130 }
2131 }
2132 }
2133
2134 // Success! Output targets.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002135 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002136
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002137 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002138 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002139 touchedWindow.pointerIds, inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002140 }
2141
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002142 for (const TouchedMonitor& touchedMonitor : tempTouchState.gestureMonitors) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002143 addMonitoringTargetLocked(touchedMonitor.monitor, touchedMonitor.xOffset,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002144 touchedMonitor.yOffset, inputTargets);
Michael Wright3dd60e22019-03-27 22:06:44 +00002145 }
2146
Michael Wrightd02c5b62014-02-10 15:10:22 -08002147 // Drop the outside or hover touch windows since we will not care about them
2148 // in the next iteration.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002149 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002150
2151Failed:
2152 // Check injection permission once and for all.
2153 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002154 if (checkInjectionPermission(nullptr, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002155 injectionPermission = INJECTION_PERMISSION_GRANTED;
2156 } else {
2157 injectionPermission = INJECTION_PERMISSION_DENIED;
2158 }
2159 }
2160
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002161 if (injectionPermission != INJECTION_PERMISSION_GRANTED) {
2162 return injectionResult;
2163 }
2164
Michael Wrightd02c5b62014-02-10 15:10:22 -08002165 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002166 if (!wrongDevice) {
2167 if (switchedDevice) {
2168 if (DEBUG_FOCUS) {
2169 ALOGD("Conflicting pointer actions: Switched to a different device.");
2170 }
2171 *outConflictingPointerActions = true;
2172 }
2173
2174 if (isHoverAction) {
2175 // Started hovering, therefore no longer down.
2176 if (oldState && oldState->down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002177 if (DEBUG_FOCUS) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002178 ALOGD("Conflicting pointer actions: Hover received while pointer was "
2179 "down.");
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002180 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002181 *outConflictingPointerActions = true;
2182 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002183 tempTouchState.reset();
2184 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2185 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
2186 tempTouchState.deviceId = entry.deviceId;
2187 tempTouchState.source = entry.source;
2188 tempTouchState.displayId = displayId;
2189 }
2190 } else if (maskedAction == AMOTION_EVENT_ACTION_UP ||
2191 maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
2192 // All pointers up or canceled.
2193 tempTouchState.reset();
2194 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2195 // First pointer went down.
2196 if (oldState && oldState->down) {
2197 if (DEBUG_FOCUS) {
2198 ALOGD("Conflicting pointer actions: Down received while already down.");
2199 }
2200 *outConflictingPointerActions = true;
2201 }
2202 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2203 // One pointer went up.
2204 if (isSplit) {
2205 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2206 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002207
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002208 for (size_t i = 0; i < tempTouchState.windows.size();) {
2209 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2210 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
2211 touchedWindow.pointerIds.clearBit(pointerId);
2212 if (touchedWindow.pointerIds.isEmpty()) {
2213 tempTouchState.windows.erase(tempTouchState.windows.begin() + i);
2214 continue;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002215 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002216 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002217 i += 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002218 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002219 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002220 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002221
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002222 // Save changes unless the action was scroll in which case the temporary touch
2223 // state was only valid for this one action.
2224 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
2225 if (tempTouchState.displayId >= 0) {
2226 mTouchStatesByDisplay[displayId] = tempTouchState;
2227 } else {
2228 mTouchStatesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002229 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002230 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002231
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002232 // Update hover state.
2233 mLastHoverWindowHandle = newHoverWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002234 }
2235
Michael Wrightd02c5b62014-02-10 15:10:22 -08002236 return injectionResult;
2237}
2238
2239void InputDispatcher::addWindowTargetLocked(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002240 int32_t targetFlags, BitSet32 pointerIds,
2241 std::vector<InputTarget>& inputTargets) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002242 std::vector<InputTarget>::iterator it =
2243 std::find_if(inputTargets.begin(), inputTargets.end(),
2244 [&windowHandle](const InputTarget& inputTarget) {
2245 return inputTarget.inputChannel->getConnectionToken() ==
2246 windowHandle->getToken();
2247 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002248
Chavi Weingarten114b77f2020-01-15 22:35:10 +00002249 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002250
2251 if (it == inputTargets.end()) {
2252 InputTarget inputTarget;
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05002253 std::shared_ptr<InputChannel> inputChannel =
2254 getInputChannelLocked(windowHandle->getToken());
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002255 if (inputChannel == nullptr) {
2256 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
2257 return;
2258 }
2259 inputTarget.inputChannel = inputChannel;
2260 inputTarget.flags = targetFlags;
2261 inputTarget.globalScaleFactor = windowInfo->globalScaleFactor;
2262 inputTargets.push_back(inputTarget);
2263 it = inputTargets.end() - 1;
2264 }
2265
2266 ALOG_ASSERT(it->flags == targetFlags);
2267 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
2268
chaviw1ff3d1e2020-07-01 15:53:47 -07002269 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002270}
2271
Michael Wright3dd60e22019-03-27 22:06:44 +00002272void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002273 int32_t displayId, float xOffset,
2274 float yOffset) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002275 std::unordered_map<int32_t, std::vector<Monitor>>::const_iterator it =
2276 mGlobalMonitorsByDisplay.find(displayId);
2277
2278 if (it != mGlobalMonitorsByDisplay.end()) {
2279 const std::vector<Monitor>& monitors = it->second;
2280 for (const Monitor& monitor : monitors) {
2281 addMonitoringTargetLocked(monitor, xOffset, yOffset, inputTargets);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002282 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002283 }
2284}
2285
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002286void InputDispatcher::addMonitoringTargetLocked(const Monitor& monitor, float xOffset,
2287 float yOffset,
2288 std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002289 InputTarget target;
2290 target.inputChannel = monitor.inputChannel;
2291 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
chaviw1ff3d1e2020-07-01 15:53:47 -07002292 ui::Transform t;
2293 t.set(xOffset, yOffset);
2294 target.setDefaultPointerTransform(t);
Michael Wright3dd60e22019-03-27 22:06:44 +00002295 inputTargets.push_back(target);
2296}
2297
Michael Wrightd02c5b62014-02-10 15:10:22 -08002298bool InputDispatcher::checkInjectionPermission(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002299 const InjectionState* injectionState) {
2300 if (injectionState &&
2301 (windowHandle == nullptr ||
2302 windowHandle->getInfo()->ownerUid != injectionState->injectorUid) &&
2303 !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002304 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002305 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002306 "owned by uid %d",
2307 injectionState->injectorPid, injectionState->injectorUid,
2308 windowHandle->getName().c_str(), windowHandle->getInfo()->ownerUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002309 } else {
2310 ALOGW("Permission denied: injecting event from pid %d uid %d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002311 injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002312 }
2313 return false;
2314 }
2315 return true;
2316}
2317
Robert Carrc9bf1d32020-04-13 17:21:08 -07002318/**
2319 * Indicate whether one window handle should be considered as obscuring
2320 * another window handle. We only check a few preconditions. Actually
2321 * checking the bounds is left to the caller.
2322 */
2323static bool canBeObscuredBy(const sp<InputWindowHandle>& windowHandle,
2324 const sp<InputWindowHandle>& otherHandle) {
2325 // Compare by token so cloned layers aren't counted
2326 if (haveSameToken(windowHandle, otherHandle)) {
2327 return false;
2328 }
2329 auto info = windowHandle->getInfo();
2330 auto otherInfo = otherHandle->getInfo();
2331 if (!otherInfo->visible) {
2332 return false;
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002333 } else if (otherInfo->alpha == 0 &&
2334 otherInfo->flags.test(InputWindowInfo::Flag::NOT_TOUCHABLE)) {
2335 // Those act as if they were invisible, so we don't need to flag them.
2336 // We do want to potentially flag touchable windows even if they have 0
2337 // opacity, since they can consume touches and alter the effects of the
2338 // user interaction (eg. apps that rely on
2339 // FLAG_WINDOW_IS_PARTIALLY_OBSCURED should still be told about those
2340 // windows), hence we also check for FLAG_NOT_TOUCHABLE.
2341 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00002342 } else if (info->ownerUid == otherInfo->ownerUid) {
2343 // If ownerUid is the same we don't generate occlusion events as there
2344 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002345 return false;
Chris Yefcdff3e2020-05-10 15:16:04 -07002346 } else if (otherInfo->trustedOverlay) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002347 return false;
2348 } else if (otherInfo->displayId != info->displayId) {
2349 return false;
2350 }
2351 return true;
2352}
2353
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002354/**
2355 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
2356 * untrusted, one should check:
2357 *
2358 * 1. If result.hasBlockingOcclusion is true.
2359 * If it's, it means the touch should be blocked due to a window with occlusion mode of
2360 * BLOCK_UNTRUSTED.
2361 *
2362 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
2363 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
2364 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
2365 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
2366 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
2367 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
2368 *
2369 * If neither of those is true, then it means the touch can be allowed.
2370 */
2371InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
2372 const sp<InputWindowHandle>& windowHandle, int32_t x, int32_t y) const {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002373 const InputWindowInfo* windowInfo = windowHandle->getInfo();
2374 int32_t displayId = windowInfo->displayId;
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002375 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2376 TouchOcclusionInfo info;
2377 info.hasBlockingOcclusion = false;
2378 info.obscuringOpacity = 0;
2379 info.obscuringUid = -1;
2380 std::map<int32_t, float> opacityByUid;
2381 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
2382 if (windowHandle == otherHandle) {
2383 break; // All future windows are below us. Exit early.
2384 }
2385 const InputWindowInfo* otherInfo = otherHandle->getInfo();
2386 if (canBeObscuredBy(windowHandle, otherHandle) &&
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002387 windowInfo->ownerUid != otherInfo->ownerUid && otherInfo->frameContainsPoint(x, y)) {
2388 if (DEBUG_TOUCH_OCCLUSION) {
2389 info.debugInfo.push_back(
2390 dumpWindowForTouchOcclusion(otherInfo, /* isTouchedWindow */ false));
2391 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002392 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
2393 // we perform the checks below to see if the touch can be propagated or not based on the
2394 // window's touch occlusion mode
2395 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
2396 info.hasBlockingOcclusion = true;
2397 info.obscuringUid = otherInfo->ownerUid;
2398 info.obscuringPackage = otherInfo->packageName;
2399 break;
2400 }
2401 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
2402 uint32_t uid = otherInfo->ownerUid;
2403 float opacity =
2404 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
2405 // Given windows A and B:
2406 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
2407 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
2408 opacityByUid[uid] = opacity;
2409 if (opacity > info.obscuringOpacity) {
2410 info.obscuringOpacity = opacity;
2411 info.obscuringUid = uid;
2412 info.obscuringPackage = otherInfo->packageName;
2413 }
2414 }
2415 }
2416 }
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002417 if (DEBUG_TOUCH_OCCLUSION) {
2418 info.debugInfo.push_back(
2419 dumpWindowForTouchOcclusion(windowInfo, /* isTouchedWindow */ true));
2420 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002421 return info;
2422}
2423
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002424std::string InputDispatcher::dumpWindowForTouchOcclusion(const InputWindowInfo* info,
2425 bool isTouchedWindow) const {
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00002426 return StringPrintf(INDENT2 "* %stype=%s, package=%s/%" PRId32 ", id=%" PRId32
2427 ", mode=%s, alpha=%.2f, "
Bernardo Rufinoc2f1fad2020-11-04 17:30:57 +00002428 "frame=[%" PRId32 ",%" PRId32 "][%" PRId32 ",%" PRId32
2429 "], touchableRegion=%s, window={%s}, applicationInfo=%s, "
2430 "flags={%s}, inputFeatures={%s}, hasToken=%s\n",
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002431 (isTouchedWindow) ? "[TOUCHED] " : "",
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00002432 NamedEnum::string(info->type, "%" PRId32).c_str(),
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00002433 info->packageName.c_str(), info->ownerUid, info->id,
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00002434 toString(info->touchOcclusionMode).c_str(), info->alpha, info->frameLeft,
2435 info->frameTop, info->frameRight, info->frameBottom,
2436 dumpRegion(info->touchableRegion).c_str(), info->name.c_str(),
Bernardo Rufinoc2f1fad2020-11-04 17:30:57 +00002437 info->applicationInfo.name.c_str(), info->flags.string().c_str(),
2438 info->inputFeatures.string().c_str(), toString(info->token != nullptr));
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002439}
2440
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002441bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
2442 if (occlusionInfo.hasBlockingOcclusion) {
2443 ALOGW("Untrusted touch due to occlusion by %s/%d", occlusionInfo.obscuringPackage.c_str(),
2444 occlusionInfo.obscuringUid);
2445 return false;
2446 }
2447 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
2448 ALOGW("Untrusted touch due to occlusion by %s/%d (obscuring opacity = "
2449 "%.2f, maximum allowed = %.2f)",
2450 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid,
2451 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
2452 return false;
2453 }
2454 return true;
2455}
2456
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002457bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<InputWindowHandle>& windowHandle,
2458 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002459 int32_t displayId = windowHandle->getInfo()->displayId;
Vishnu Nairad321cd2020-08-20 16:40:21 -07002460 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002461 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002462 if (windowHandle == otherHandle) {
2463 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002464 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002465 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002466 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002467 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002468 return true;
2469 }
2470 }
2471 return false;
2472}
2473
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002474bool InputDispatcher::isWindowObscuredLocked(const sp<InputWindowHandle>& windowHandle) const {
2475 int32_t displayId = windowHandle->getInfo()->displayId;
Vishnu Nairad321cd2020-08-20 16:40:21 -07002476 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002477 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002478 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002479 if (windowHandle == otherHandle) {
2480 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002481 }
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002482 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002483 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002484 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002485 return true;
2486 }
2487 }
2488 return false;
2489}
2490
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002491std::string InputDispatcher::getApplicationWindowLabel(
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05002492 const InputApplicationHandle* applicationHandle,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002493 const sp<InputWindowHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002494 if (applicationHandle != nullptr) {
2495 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002496 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002497 } else {
2498 return applicationHandle->getName();
2499 }
Yi Kong9b14ac62018-07-17 13:48:38 -07002500 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002501 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002502 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002503 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002504 }
2505}
2506
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002507void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Prabir Pradhan99987712020-11-10 18:43:05 -08002508 if (eventEntry.type == EventEntry::Type::FOCUS ||
2509 eventEntry.type == EventEntry::Type::POINTER_CAPTURE_CHANGED) {
2510 // Focus or pointer capture changed events are passed to apps, but do not represent user
2511 // activity.
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002512 return;
2513 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002514 int32_t displayId = getTargetDisplayId(eventEntry);
Vishnu Nairad321cd2020-08-20 16:40:21 -07002515 sp<InputWindowHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Tiger Huang721e26f2018-07-24 22:26:19 +08002516 if (focusedWindowHandle != nullptr) {
2517 const InputWindowInfo* info = focusedWindowHandle->getInfo();
Michael Wright44753b12020-07-08 13:48:11 +01002518 if (info->inputFeatures.test(InputWindowInfo::Feature::DISABLE_USER_ACTIVITY)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002519#if DEBUG_DISPATCH_CYCLE
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002520 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002521#endif
2522 return;
2523 }
2524 }
2525
2526 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002527 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002528 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002529 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
2530 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002531 return;
2532 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002533
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002534 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002535 eventType = USER_ACTIVITY_EVENT_TOUCH;
2536 }
2537 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002538 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002539 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002540 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
2541 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002542 return;
2543 }
2544 eventType = USER_ACTIVITY_EVENT_BUTTON;
2545 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002546 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002547 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002548 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08002549 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07002550 case EventEntry::Type::SENSOR:
Prabir Pradhan99987712020-11-10 18:43:05 -08002551 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002552 LOG_ALWAYS_FATAL("%s events are not user activity",
Chris Yef59a2f42020-10-16 12:55:26 -07002553 NamedEnum::string(eventEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002554 break;
2555 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002556 }
2557
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002558 std::unique_ptr<CommandEntry> commandEntry =
2559 std::make_unique<CommandEntry>(&InputDispatcher::doPokeUserActivityLockedInterruptible);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002560 commandEntry->eventTime = eventEntry.eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002561 commandEntry->userActivityEventType = eventType;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002562 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002563}
2564
2565void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002566 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002567 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002568 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002569 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002570 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002571 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002572 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002573 ATRACE_NAME(message.c_str());
2574 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002575#if DEBUG_DISPATCH_CYCLE
2576 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002577 "globalScaleFactor=%f, pointerIds=0x%x %s",
2578 connection->getInputChannelName().c_str(), inputTarget.flags,
2579 inputTarget.globalScaleFactor, inputTarget.pointerIds.value,
2580 inputTarget.getPointerInfoString().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002581#endif
2582
2583 // Skip this event if the connection status is not normal.
2584 // We don't want to enqueue additional outbound events if the connection is broken.
2585 if (connection->status != Connection::STATUS_NORMAL) {
2586#if DEBUG_DISPATCH_CYCLE
2587 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002588 connection->getInputChannelName().c_str(), connection->getStatusLabel());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002589#endif
2590 return;
2591 }
2592
2593 // Split a motion event if needed.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002594 if (inputTarget.flags & InputTarget::FLAG_SPLIT) {
2595 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
2596 "Entry type %s should not have FLAG_SPLIT",
Chris Yef59a2f42020-10-16 12:55:26 -07002597 NamedEnum::string(eventEntry->type).c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002598
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002599 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002600 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002601 std::unique_ptr<MotionEntry> splitMotionEntry =
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002602 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002603 if (!splitMotionEntry) {
2604 return; // split event was dropped
2605 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002606 if (DEBUG_FOCUS) {
2607 ALOGD("channel '%s' ~ Split motion event.",
2608 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002609 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002610 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002611 enqueueDispatchEntriesLocked(currentTime, connection, std::move(splitMotionEntry),
2612 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002613 return;
2614 }
2615 }
2616
2617 // Not splitting. Enqueue dispatch entries for the event as is.
2618 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
2619}
2620
2621void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002622 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002623 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002624 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002625 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002626 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002627 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002628 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002629 ATRACE_NAME(message.c_str());
2630 }
2631
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002632 bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002633
2634 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07002635 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002636 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002637 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002638 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07002639 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002640 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07002641 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002642 InputTarget::FLAG_DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07002643 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002644 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002645 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002646 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002647
2648 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002649 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002650 startDispatchCycleLocked(currentTime, connection);
2651 }
2652}
2653
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002654void InputDispatcher::enqueueDispatchEntryLocked(const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002655 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002656 const InputTarget& inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002657 int32_t dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002658 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002659 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
2660 connection->getInputChannelName().c_str(),
2661 dispatchModeToString(dispatchMode).c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002662 ATRACE_NAME(message.c_str());
2663 }
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002664 int32_t inputTargetFlags = inputTarget.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002665 if (!(inputTargetFlags & dispatchMode)) {
2666 return;
2667 }
2668 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
2669
2670 // This is a new event.
2671 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002672 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002673 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002674
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002675 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
2676 // different EventEntry than what was passed in.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002677 EventEntry& newEntry = *(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002678 // Apply target flags and update the connection's input state.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002679 switch (newEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002680 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002681 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002682 dispatchEntry->resolvedEventId = keyEntry.id;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002683 dispatchEntry->resolvedAction = keyEntry.action;
2684 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002685
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002686 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
2687 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002688#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002689 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key event",
2690 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002691#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002692 return; // skip the inconsistent event
2693 }
2694 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002695 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002696
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002697 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002698 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002699 // Assign a default value to dispatchEntry that will never be generated by InputReader,
2700 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
2701 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
2702 static_cast<int32_t>(IdGenerator::Source::OTHER);
2703 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002704 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2705 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
2706 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
2707 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
2708 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
2709 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2710 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
2711 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
2712 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
2713 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
2714 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002715 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002716 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002717 }
2718 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002719 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
2720 motionEntry.displayId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002721#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002722 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover enter "
2723 "event",
2724 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002725#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002726 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2727 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002728
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002729 dispatchEntry->resolvedFlags = motionEntry.flags;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002730 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
2731 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
2732 }
2733 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
2734 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2735 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002736
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002737 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
2738 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002739#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002740 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
2741 "event",
2742 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002743#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002744 return; // skip the inconsistent event
2745 }
2746
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002747 dispatchEntry->resolvedEventId =
2748 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
2749 ? mIdGenerator.nextId()
2750 : motionEntry.id;
2751 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
2752 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
2753 ") to MotionEvent(id=0x%" PRIx32 ").",
2754 motionEntry.id, dispatchEntry->resolvedEventId);
2755 ATRACE_NAME(message.c_str());
2756 }
2757
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002758 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002759 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002760
2761 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002762 }
Prabir Pradhan99987712020-11-10 18:43:05 -08002763 case EventEntry::Type::FOCUS:
2764 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002765 break;
2766 }
Chris Yef59a2f42020-10-16 12:55:26 -07002767 case EventEntry::Type::SENSOR: {
2768 LOG_ALWAYS_FATAL("SENSOR events should not go to apps via input channel");
2769 break;
2770 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002771 case EventEntry::Type::CONFIGURATION_CHANGED:
2772 case EventEntry::Type::DEVICE_RESET: {
2773 LOG_ALWAYS_FATAL("%s events should not go to apps",
Chris Yef59a2f42020-10-16 12:55:26 -07002774 NamedEnum::string(newEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002775 break;
2776 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002777 }
2778
2779 // Remember that we are waiting for this dispatch to complete.
2780 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002781 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002782 }
2783
2784 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002785 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002786 traceOutboundQueueLength(connection);
chaviw8c9cf542019-03-25 13:02:48 -07002787}
2788
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00002789/**
2790 * This function is purely for debugging. It helps us understand where the user interaction
2791 * was taking place. For example, if user is touching launcher, we will see a log that user
2792 * started interacting with launcher. In that example, the event would go to the wallpaper as well.
2793 * We will see both launcher and wallpaper in that list.
2794 * Once the interaction with a particular set of connections starts, no new logs will be printed
2795 * until the set of interacted connections changes.
2796 *
2797 * The following items are skipped, to reduce the logspam:
2798 * ACTION_OUTSIDE: any windows that are receiving ACTION_OUTSIDE are not logged
2799 * ACTION_UP: any windows that receive ACTION_UP are not logged (for both keys and motions).
2800 * This includes situations like the soft BACK button key. When the user releases (lifts up the
2801 * finger) the back button, then navigation bar will inject KEYCODE_BACK with ACTION_UP.
2802 * Both of those ACTION_UP events would not be logged
2803 * Monitors (both gesture and global): any gesture monitors or global monitors receiving events
2804 * will not be logged. This is omitted to reduce the amount of data printed.
2805 * If you see <none>, it's likely that one of the gesture monitors pilfered the event, and therefore
2806 * gesture monitor is the only connection receiving the remainder of the gesture.
2807 */
2808void InputDispatcher::updateInteractionTokensLocked(const EventEntry& entry,
2809 const std::vector<InputTarget>& targets) {
2810 // Skip ACTION_UP events, and all events other than keys and motions
2811 if (entry.type == EventEntry::Type::KEY) {
2812 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
2813 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
2814 return;
2815 }
2816 } else if (entry.type == EventEntry::Type::MOTION) {
2817 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
2818 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
2819 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
2820 return;
2821 }
2822 } else {
2823 return; // Not a key or a motion
2824 }
2825
2826 std::unordered_set<sp<IBinder>, IBinderHash> newConnectionTokens;
2827 std::vector<sp<Connection>> newConnections;
2828 for (const InputTarget& target : targets) {
2829 if ((target.flags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) ==
2830 InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2831 continue; // Skip windows that receive ACTION_OUTSIDE
2832 }
2833
2834 sp<IBinder> token = target.inputChannel->getConnectionToken();
2835 sp<Connection> connection = getConnectionLocked(token);
2836 if (connection == nullptr || connection->monitor) {
2837 continue; // We only need to keep track of the non-monitor connections.
2838 }
2839 newConnectionTokens.insert(std::move(token));
2840 newConnections.emplace_back(connection);
2841 }
2842 if (newConnectionTokens == mInteractionConnectionTokens) {
2843 return; // no change
2844 }
2845 mInteractionConnectionTokens = newConnectionTokens;
2846
2847 std::string windowList;
2848 for (const sp<Connection>& connection : newConnections) {
2849 windowList += connection->getWindowName() + ", ";
2850 }
2851 std::string message = "Interaction with windows: " + windowList;
2852 if (windowList.empty()) {
2853 message += "<none>";
2854 }
2855 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
2856}
2857
chaviwfd6d3512019-03-25 13:23:49 -07002858void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07002859 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07002860 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07002861 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
2862 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07002863 return;
2864 }
2865
Vishnu Nairad321cd2020-08-20 16:40:21 -07002866 sp<IBinder> focusedToken = getValueByKey(mFocusedWindowTokenByDisplay, mFocusedDisplayId);
2867 if (focusedToken == token) {
2868 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07002869 return;
2870 }
2871
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002872 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
2873 &InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible);
Vishnu Nairad321cd2020-08-20 16:40:21 -07002874 commandEntry->newToken = token;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002875 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002876}
2877
2878void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002879 const sp<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002880 if (ATRACE_ENABLED()) {
2881 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002882 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002883 ATRACE_NAME(message.c_str());
2884 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002885#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002886 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002887#endif
2888
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002889 while (connection->status == Connection::STATUS_NORMAL && !connection->outboundQueue.empty()) {
2890 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002891 dispatchEntry->deliveryTime = currentTime;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05002892 const std::chrono::nanoseconds timeout =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002893 getDispatchingTimeoutLocked(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou70622952020-07-30 11:17:23 -05002894 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002895
2896 // Publish the event.
2897 status_t status;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002898 const EventEntry& eventEntry = *(dispatchEntry->eventEntry);
2899 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002900 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002901 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
2902 std::array<uint8_t, 32> hmac = getSignature(keyEntry, *dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002903
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002904 // Publish the key event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002905 status = connection->inputPublisher
2906 .publishKeyEvent(dispatchEntry->seq,
2907 dispatchEntry->resolvedEventId, keyEntry.deviceId,
2908 keyEntry.source, keyEntry.displayId,
2909 std::move(hmac), dispatchEntry->resolvedAction,
2910 dispatchEntry->resolvedFlags, keyEntry.keyCode,
2911 keyEntry.scanCode, keyEntry.metaState,
2912 keyEntry.repeatCount, keyEntry.downTime,
2913 keyEntry.eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002914 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002915 }
2916
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002917 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002918 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002919
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002920 PointerCoords scaledCoords[MAX_POINTERS];
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002921 const PointerCoords* usingCoords = motionEntry.pointerCoords;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002922
chaviw82357092020-01-28 13:13:06 -08002923 // Set the X and Y offset and X and Y scale depending on the input source.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002924 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) &&
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002925 !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
2926 float globalScaleFactor = dispatchEntry->globalScaleFactor;
chaviw82357092020-01-28 13:13:06 -08002927 if (globalScaleFactor != 1.0f) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002928 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
2929 scaledCoords[i] = motionEntry.pointerCoords[i];
chaviw82357092020-01-28 13:13:06 -08002930 // Don't apply window scale here since we don't want scale to affect raw
2931 // coordinates. The scale will be sent back to the client and applied
2932 // later when requesting relative coordinates.
2933 scaledCoords[i].scale(globalScaleFactor, 1 /* windowXScale */,
2934 1 /* windowYScale */);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002935 }
2936 usingCoords = scaledCoords;
2937 }
2938 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002939 // We don't want the dispatch target to know.
2940 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002941 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002942 scaledCoords[i].clear();
2943 }
2944 usingCoords = scaledCoords;
2945 }
2946 }
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07002947
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002948 std::array<uint8_t, 32> hmac = getSignature(motionEntry, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002949
2950 // Publish the motion event.
2951 status = connection->inputPublisher
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002952 .publishMotionEvent(dispatchEntry->seq,
2953 dispatchEntry->resolvedEventId,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002954 motionEntry.deviceId, motionEntry.source,
2955 motionEntry.displayId, std::move(hmac),
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002956 dispatchEntry->resolvedAction,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002957 motionEntry.actionButton,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002958 dispatchEntry->resolvedFlags,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002959 motionEntry.edgeFlags, motionEntry.metaState,
2960 motionEntry.buttonState,
2961 motionEntry.classification,
chaviw9eaa22c2020-07-01 16:21:27 -07002962 dispatchEntry->transform,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002963 motionEntry.xPrecision, motionEntry.yPrecision,
2964 motionEntry.xCursorPosition,
2965 motionEntry.yCursorPosition,
2966 motionEntry.downTime, motionEntry.eventTime,
2967 motionEntry.pointerCount,
2968 motionEntry.pointerProperties, usingCoords);
2969 reportTouchEventForStatistics(motionEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002970 break;
2971 }
Prabir Pradhan99987712020-11-10 18:43:05 -08002972
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002973 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002974 const FocusEntry& focusEntry = static_cast<const FocusEntry&>(eventEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002975 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002976 focusEntry.id,
2977 focusEntry.hasFocus,
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002978 mInTouchMode);
2979 break;
2980 }
2981
Prabir Pradhan99987712020-11-10 18:43:05 -08002982 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
2983 const auto& captureEntry =
2984 static_cast<const PointerCaptureChangedEntry&>(eventEntry);
2985 status = connection->inputPublisher
2986 .publishCaptureEvent(dispatchEntry->seq, captureEntry.id,
2987 captureEntry.pointerCaptureEnabled);
2988 break;
2989 }
2990
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08002991 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07002992 case EventEntry::Type::DEVICE_RESET:
2993 case EventEntry::Type::SENSOR: {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08002994 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
Chris Yef59a2f42020-10-16 12:55:26 -07002995 NamedEnum::string(eventEntry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002996 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08002997 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002998 }
2999
3000 // Check the result.
3001 if (status) {
3002 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003003 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003004 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003005 "This is unexpected because the wait queue is empty, so the pipe "
3006 "should be empty and we shouldn't have any problems writing an "
3007 "event to it, status=%d",
3008 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003009 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3010 } else {
3011 // Pipe is full and we are waiting for the app to finish process some events
3012 // before sending more events to it.
3013#if DEBUG_DISPATCH_CYCLE
3014 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003015 "waiting for the application to catch up",
3016 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003017#endif
Michael Wrightd02c5b62014-02-10 15:10:22 -08003018 }
3019 } else {
3020 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003021 "status=%d",
3022 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003023 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3024 }
3025 return;
3026 }
3027
3028 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003029 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
3030 connection->outboundQueue.end(),
3031 dispatchEntry));
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003032 traceOutboundQueueLength(connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003033 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003034 if (connection->responsive) {
3035 mAnrTracker.insert(dispatchEntry->timeoutTime,
3036 connection->inputChannel->getConnectionToken());
3037 }
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003038 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003039 }
3040}
3041
chaviw09c8d2d2020-08-24 15:48:26 -07003042std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
3043 size_t size;
3044 switch (event.type) {
3045 case VerifiedInputEvent::Type::KEY: {
3046 size = sizeof(VerifiedKeyEvent);
3047 break;
3048 }
3049 case VerifiedInputEvent::Type::MOTION: {
3050 size = sizeof(VerifiedMotionEvent);
3051 break;
3052 }
3053 }
3054 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
3055 return mHmacKeyManager.sign(start, size);
3056}
3057
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003058const std::array<uint8_t, 32> InputDispatcher::getSignature(
3059 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
3060 int32_t actionMasked = dispatchEntry.resolvedAction & AMOTION_EVENT_ACTION_MASK;
3061 if ((actionMasked == AMOTION_EVENT_ACTION_UP) || (actionMasked == AMOTION_EVENT_ACTION_DOWN)) {
3062 // Only sign events up and down events as the purely move events
3063 // are tied to their up/down counterparts so signing would be redundant.
3064 VerifiedMotionEvent verifiedEvent = verifiedMotionEventFromMotionEntry(motionEntry);
3065 verifiedEvent.actionMasked = actionMasked;
3066 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
chaviw09c8d2d2020-08-24 15:48:26 -07003067 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003068 }
3069 return INVALID_HMAC;
3070}
3071
3072const std::array<uint8_t, 32> InputDispatcher::getSignature(
3073 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
3074 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
3075 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
3076 verifiedEvent.action = dispatchEntry.resolvedAction;
chaviw09c8d2d2020-08-24 15:48:26 -07003077 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003078}
3079
Michael Wrightd02c5b62014-02-10 15:10:22 -08003080void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003081 const sp<Connection>& connection, uint32_t seq,
3082 bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003083#if DEBUG_DISPATCH_CYCLE
3084 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003085 connection->getInputChannelName().c_str(), seq, toString(handled));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003086#endif
3087
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003088 if (connection->status == Connection::STATUS_BROKEN ||
3089 connection->status == Connection::STATUS_ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003090 return;
3091 }
3092
3093 // Notify other system components and prepare to start the next dispatch cycle.
3094 onDispatchCycleFinishedLocked(currentTime, connection, seq, handled);
3095}
3096
3097void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003098 const sp<Connection>& connection,
3099 bool notify) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003100#if DEBUG_DISPATCH_CYCLE
3101 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003102 connection->getInputChannelName().c_str(), toString(notify));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003103#endif
3104
3105 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003106 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003107 traceOutboundQueueLength(connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003108 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003109 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003110
3111 // The connection appears to be unrecoverably broken.
3112 // Ignore already broken or zombie connections.
3113 if (connection->status == Connection::STATUS_NORMAL) {
3114 connection->status = Connection::STATUS_BROKEN;
3115
3116 if (notify) {
3117 // Notify other system components.
3118 onDispatchCycleBrokenLocked(currentTime, connection);
3119 }
3120 }
3121}
3122
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003123void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
3124 while (!queue.empty()) {
3125 DispatchEntry* dispatchEntry = queue.front();
3126 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003127 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003128 }
3129}
3130
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003131void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003132 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003133 decrementPendingForegroundDispatches(*(dispatchEntry->eventEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003134 }
3135 delete dispatchEntry;
3136}
3137
3138int InputDispatcher::handleReceiveCallback(int fd, int events, void* data) {
3139 InputDispatcher* d = static_cast<InputDispatcher*>(data);
3140
3141 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003142 std::scoped_lock _l(d->mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003143
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003144 if (d->mConnectionsByFd.find(fd) == d->mConnectionsByFd.end()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003145 ALOGE("Received spurious receive callback for unknown input channel. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003146 "fd=%d, events=0x%x",
3147 fd, events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003148 return 0; // remove the callback
3149 }
3150
3151 bool notify;
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003152 sp<Connection> connection = d->mConnectionsByFd[fd];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003153 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
3154 if (!(events & ALOOPER_EVENT_INPUT)) {
3155 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003156 "events=0x%x",
3157 connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003158 return 1;
3159 }
3160
3161 nsecs_t currentTime = now();
3162 bool gotOne = false;
3163 status_t status;
3164 for (;;) {
3165 uint32_t seq;
3166 bool handled;
3167 status = connection->inputPublisher.receiveFinishedSignal(&seq, &handled);
3168 if (status) {
3169 break;
3170 }
3171 d->finishDispatchCycleLocked(currentTime, connection, seq, handled);
3172 gotOne = true;
3173 }
3174 if (gotOne) {
3175 d->runCommandsLockedInterruptible();
3176 if (status == WOULD_BLOCK) {
3177 return 1;
3178 }
3179 }
3180
3181 notify = status != DEAD_OBJECT || !connection->monitor;
3182 if (notify) {
3183 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003184 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003185 }
3186 } else {
3187 // Monitor channels are never explicitly unregistered.
3188 // We do it automatically when the remote endpoint is closed so don't warn
3189 // about them.
arthurhungd352cb32020-04-28 17:09:28 +08003190 const bool stillHaveWindowHandle =
3191 d->getWindowHandleLocked(connection->inputChannel->getConnectionToken()) !=
3192 nullptr;
3193 notify = !connection->monitor && stillHaveWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003194 if (notify) {
3195 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003196 "events=0x%x",
3197 connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003198 }
3199 }
3200
Garfield Tan15601662020-09-22 15:32:38 -07003201 // Remove the channel.
3202 d->removeInputChannelLocked(connection->inputChannel->getConnectionToken(), notify);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003203 return 0; // remove the callback
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003204 } // release lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08003205}
3206
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003207void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08003208 const CancelationOptions& options) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003209 for (const auto& pair : mConnectionsByFd) {
3210 synthesizeCancelationEventsForConnectionLocked(pair.second, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003211 }
3212}
3213
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003214void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003215 const CancelationOptions& options) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003216 synthesizeCancelationEventsForMonitorsLocked(options, mGlobalMonitorsByDisplay);
3217 synthesizeCancelationEventsForMonitorsLocked(options, mGestureMonitorsByDisplay);
3218}
3219
3220void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
3221 const CancelationOptions& options,
3222 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
3223 for (const auto& it : monitorsByDisplay) {
3224 const std::vector<Monitor>& monitors = it.second;
3225 for (const Monitor& monitor : monitors) {
3226 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003227 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003228 }
3229}
3230
Michael Wrightd02c5b62014-02-10 15:10:22 -08003231void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003232 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07003233 sp<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003234 if (connection == nullptr) {
3235 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003236 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003237
3238 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003239}
3240
3241void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
3242 const sp<Connection>& connection, const CancelationOptions& options) {
3243 if (connection->status == Connection::STATUS_BROKEN) {
3244 return;
3245 }
3246
3247 nsecs_t currentTime = now();
3248
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003249 std::vector<std::unique_ptr<EventEntry>> cancelationEvents =
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07003250 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003251
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003252 if (cancelationEvents.empty()) {
3253 return;
3254 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003255#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003256 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
3257 "with reality: %s, mode=%d.",
3258 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
3259 options.mode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003260#endif
Svet Ganov5d3bc372020-01-26 23:11:07 -08003261
3262 InputTarget target;
3263 sp<InputWindowHandle> windowHandle =
3264 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3265 if (windowHandle != nullptr) {
3266 const InputWindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003267 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003268 target.globalScaleFactor = windowInfo->globalScaleFactor;
3269 }
3270 target.inputChannel = connection->inputChannel;
3271 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3272
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003273 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003274 std::unique_ptr<EventEntry> cancelationEventEntry = std::move(cancelationEvents[i]);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003275 switch (cancelationEventEntry->type) {
3276 case EventEntry::Type::KEY: {
3277 logOutboundKeyDetails("cancel - ",
3278 static_cast<const KeyEntry&>(*cancelationEventEntry));
3279 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003280 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003281 case EventEntry::Type::MOTION: {
3282 logOutboundMotionDetails("cancel - ",
3283 static_cast<const MotionEntry&>(*cancelationEventEntry));
3284 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003285 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003286 case EventEntry::Type::FOCUS:
3287 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3288 LOG_ALWAYS_FATAL("Canceling %s events is not supported",
Chris Yef59a2f42020-10-16 12:55:26 -07003289 NamedEnum::string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003290 break;
3291 }
3292 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003293 case EventEntry::Type::DEVICE_RESET:
3294 case EventEntry::Type::SENSOR: {
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003295 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Chris Yef59a2f42020-10-16 12:55:26 -07003296 NamedEnum::string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003297 break;
3298 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003299 }
3300
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003301 enqueueDispatchEntryLocked(connection, std::move(cancelationEventEntry), target,
3302 InputTarget::FLAG_DISPATCH_AS_IS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003303 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003304
3305 startDispatchCycleLocked(currentTime, connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003306}
3307
Svet Ganov5d3bc372020-01-26 23:11:07 -08003308void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
3309 const sp<Connection>& connection) {
3310 if (connection->status == Connection::STATUS_BROKEN) {
3311 return;
3312 }
3313
3314 nsecs_t currentTime = now();
3315
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003316 std::vector<std::unique_ptr<EventEntry>> downEvents =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003317 connection->inputState.synthesizePointerDownEvents(currentTime);
3318
3319 if (downEvents.empty()) {
3320 return;
3321 }
3322
3323#if DEBUG_OUTBOUND_EVENT_DETAILS
3324 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
3325 connection->getInputChannelName().c_str(), downEvents.size());
3326#endif
3327
3328 InputTarget target;
3329 sp<InputWindowHandle> windowHandle =
3330 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3331 if (windowHandle != nullptr) {
3332 const InputWindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003333 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003334 target.globalScaleFactor = windowInfo->globalScaleFactor;
3335 }
3336 target.inputChannel = connection->inputChannel;
3337 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3338
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003339 for (std::unique_ptr<EventEntry>& downEventEntry : downEvents) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003340 switch (downEventEntry->type) {
3341 case EventEntry::Type::MOTION: {
3342 logOutboundMotionDetails("down - ",
3343 static_cast<const MotionEntry&>(*downEventEntry));
3344 break;
3345 }
3346
3347 case EventEntry::Type::KEY:
3348 case EventEntry::Type::FOCUS:
3349 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08003350 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07003351 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3352 case EventEntry::Type::SENSOR: {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003353 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Chris Yef59a2f42020-10-16 12:55:26 -07003354 NamedEnum::string(downEventEntry->type).c_str());
Svet Ganov5d3bc372020-01-26 23:11:07 -08003355 break;
3356 }
3357 }
3358
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003359 enqueueDispatchEntryLocked(connection, std::move(downEventEntry), target,
3360 InputTarget::FLAG_DISPATCH_AS_IS);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003361 }
3362
3363 startDispatchCycleLocked(currentTime, connection);
3364}
3365
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003366std::unique_ptr<MotionEntry> InputDispatcher::splitMotionEvent(
3367 const MotionEntry& originalMotionEntry, BitSet32 pointerIds) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003368 ALOG_ASSERT(pointerIds.value != 0);
3369
3370 uint32_t splitPointerIndexMap[MAX_POINTERS];
3371 PointerProperties splitPointerProperties[MAX_POINTERS];
3372 PointerCoords splitPointerCoords[MAX_POINTERS];
3373
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003374 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003375 uint32_t splitPointerCount = 0;
3376
3377 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003378 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003379 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003380 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003381 uint32_t pointerId = uint32_t(pointerProperties.id);
3382 if (pointerIds.hasBit(pointerId)) {
3383 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
3384 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
3385 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003386 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003387 splitPointerCount += 1;
3388 }
3389 }
3390
3391 if (splitPointerCount != pointerIds.count()) {
3392 // This is bad. We are missing some of the pointers that we expected to deliver.
3393 // Most likely this indicates that we received an ACTION_MOVE events that has
3394 // different pointer ids than we expected based on the previous ACTION_DOWN
3395 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
3396 // in this way.
3397 ALOGW("Dropping split motion event because the pointer count is %d but "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003398 "we expected there to be %d pointers. This probably means we received "
3399 "a broken sequence of pointer ids from the input device.",
3400 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07003401 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003402 }
3403
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003404 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003405 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003406 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
3407 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003408 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
3409 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003410 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003411 uint32_t pointerId = uint32_t(pointerProperties.id);
3412 if (pointerIds.hasBit(pointerId)) {
3413 if (pointerIds.count() == 1) {
3414 // The first/last pointer went down/up.
3415 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003416 ? AMOTION_EVENT_ACTION_DOWN
3417 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003418 } else {
3419 // A secondary pointer went down/up.
3420 uint32_t splitPointerIndex = 0;
3421 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
3422 splitPointerIndex += 1;
3423 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003424 action = maskedAction |
3425 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003426 }
3427 } else {
3428 // An unrelated pointer changed.
3429 action = AMOTION_EVENT_ACTION_MOVE;
3430 }
3431 }
3432
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003433 int32_t newId = mIdGenerator.nextId();
3434 if (ATRACE_ENABLED()) {
3435 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
3436 ") to MotionEvent(id=0x%" PRIx32 ").",
3437 originalMotionEntry.id, newId);
3438 ATRACE_NAME(message.c_str());
3439 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003440 std::unique_ptr<MotionEntry> splitMotionEntry =
3441 std::make_unique<MotionEntry>(newId, originalMotionEntry.eventTime,
3442 originalMotionEntry.deviceId, originalMotionEntry.source,
3443 originalMotionEntry.displayId,
3444 originalMotionEntry.policyFlags, action,
3445 originalMotionEntry.actionButton,
3446 originalMotionEntry.flags, originalMotionEntry.metaState,
3447 originalMotionEntry.buttonState,
3448 originalMotionEntry.classification,
3449 originalMotionEntry.edgeFlags,
3450 originalMotionEntry.xPrecision,
3451 originalMotionEntry.yPrecision,
3452 originalMotionEntry.xCursorPosition,
3453 originalMotionEntry.yCursorPosition,
3454 originalMotionEntry.downTime, splitPointerCount,
3455 splitPointerProperties, splitPointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003456
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003457 if (originalMotionEntry.injectionState) {
3458 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003459 splitMotionEntry->injectionState->refCount += 1;
3460 }
3461
3462 return splitMotionEntry;
3463}
3464
3465void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
3466#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003467 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003468#endif
3469
3470 bool needWake;
3471 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003472 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003473
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003474 std::unique_ptr<ConfigurationChangedEntry> newEntry =
3475 std::make_unique<ConfigurationChangedEntry>(args->id, args->eventTime);
3476 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003477 } // release lock
3478
3479 if (needWake) {
3480 mLooper->wake();
3481 }
3482}
3483
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003484/**
3485 * If one of the meta shortcuts is detected, process them here:
3486 * Meta + Backspace -> generate BACK
3487 * Meta + Enter -> generate HOME
3488 * This will potentially overwrite keyCode and metaState.
3489 */
3490void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003491 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003492 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
3493 int32_t newKeyCode = AKEYCODE_UNKNOWN;
3494 if (keyCode == AKEYCODE_DEL) {
3495 newKeyCode = AKEYCODE_BACK;
3496 } else if (keyCode == AKEYCODE_ENTER) {
3497 newKeyCode = AKEYCODE_HOME;
3498 }
3499 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003500 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003501 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003502 mReplacedKeys[replacement] = newKeyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003503 keyCode = newKeyCode;
3504 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3505 }
3506 } else if (action == AKEY_EVENT_ACTION_UP) {
3507 // In order to maintain a consistent stream of up and down events, check to see if the key
3508 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
3509 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003510 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003511 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003512 auto replacementIt = mReplacedKeys.find(replacement);
3513 if (replacementIt != mReplacedKeys.end()) {
3514 keyCode = replacementIt->second;
3515 mReplacedKeys.erase(replacementIt);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003516 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3517 }
3518 }
3519}
3520
Michael Wrightd02c5b62014-02-10 15:10:22 -08003521void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
3522#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003523 ALOGD("notifyKey - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
3524 "policyFlags=0x%x, action=0x%x, "
3525 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
3526 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
3527 args->action, args->flags, args->keyCode, args->scanCode, args->metaState,
3528 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003529#endif
3530 if (!validateKeyEvent(args->action)) {
3531 return;
3532 }
3533
3534 uint32_t policyFlags = args->policyFlags;
3535 int32_t flags = args->flags;
3536 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07003537 // InputDispatcher tracks and generates key repeats on behalf of
3538 // whatever notifies it, so repeatCount should always be set to 0
3539 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003540 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
3541 policyFlags |= POLICY_FLAG_VIRTUAL;
3542 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
3543 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003544 if (policyFlags & POLICY_FLAG_FUNCTION) {
3545 metaState |= AMETA_FUNCTION_ON;
3546 }
3547
3548 policyFlags |= POLICY_FLAG_TRUSTED;
3549
Michael Wright78f24442014-08-06 15:55:28 -07003550 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003551 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07003552
Michael Wrightd02c5b62014-02-10 15:10:22 -08003553 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003554 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08003555 args->action, flags, keyCode, args->scanCode, metaState, repeatCount,
3556 args->downTime, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003557
Michael Wright2b3c3302018-03-02 17:19:13 +00003558 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003559 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003560 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3561 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003562 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003563 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003564
Michael Wrightd02c5b62014-02-10 15:10:22 -08003565 bool needWake;
3566 { // acquire lock
3567 mLock.lock();
3568
3569 if (shouldSendKeyToInputFilterLocked(args)) {
3570 mLock.unlock();
3571
3572 policyFlags |= POLICY_FLAG_FILTERED;
3573 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3574 return; // event was consumed by the filter
3575 }
3576
3577 mLock.lock();
3578 }
3579
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003580 std::unique_ptr<KeyEntry> newEntry =
3581 std::make_unique<KeyEntry>(args->id, args->eventTime, args->deviceId, args->source,
3582 args->displayId, policyFlags, args->action, flags,
3583 keyCode, args->scanCode, metaState, repeatCount,
3584 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003585
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003586 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003587 mLock.unlock();
3588 } // release lock
3589
3590 if (needWake) {
3591 mLooper->wake();
3592 }
3593}
3594
3595bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
3596 return mInputFilterEnabled;
3597}
3598
3599void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
3600#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003601 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
3602 "displayId=%" PRId32 ", policyFlags=0x%x, "
Garfield Tan00f511d2019-06-12 16:55:40 -07003603 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
3604 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
Garfield Tanab0ab9c2019-07-10 18:58:28 -07003605 "yCursorPosition=%f, downTime=%" PRId64,
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003606 args->id, args->eventTime, args->deviceId, args->source, args->displayId,
3607 args->policyFlags, args->action, args->actionButton, args->flags, args->metaState,
3608 args->buttonState, args->edgeFlags, args->xPrecision, args->yPrecision,
3609 args->xCursorPosition, args->yCursorPosition, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003610 for (uint32_t i = 0; i < args->pointerCount; i++) {
3611 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003612 "x=%f, y=%f, pressure=%f, size=%f, "
3613 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
3614 "orientation=%f",
3615 i, args->pointerProperties[i].id, args->pointerProperties[i].toolType,
3616 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
3617 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
3618 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
3619 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
3620 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
3621 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
3622 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
3623 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
3624 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003625 }
3626#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003627 if (!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
3628 args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003629 return;
3630 }
3631
3632 uint32_t policyFlags = args->policyFlags;
3633 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003634
3635 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08003636 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003637 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3638 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003639 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003640 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003641
3642 bool needWake;
3643 { // acquire lock
3644 mLock.lock();
3645
3646 if (shouldSendMotionToInputFilterLocked(args)) {
3647 mLock.unlock();
3648
3649 MotionEvent event;
chaviw9eaa22c2020-07-01 16:21:27 -07003650 ui::Transform transform;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003651 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
3652 args->action, args->actionButton, args->flags, args->edgeFlags,
chaviw9eaa22c2020-07-01 16:21:27 -07003653 args->metaState, args->buttonState, args->classification, transform,
3654 args->xPrecision, args->yPrecision, args->xCursorPosition,
3655 args->yCursorPosition, args->downTime, args->eventTime,
3656 args->pointerCount, args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003657
3658 policyFlags |= POLICY_FLAG_FILTERED;
3659 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3660 return; // event was consumed by the filter
3661 }
3662
3663 mLock.lock();
3664 }
3665
3666 // Just enqueue a new motion event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003667 std::unique_ptr<MotionEntry> newEntry =
3668 std::make_unique<MotionEntry>(args->id, args->eventTime, args->deviceId,
3669 args->source, args->displayId, policyFlags,
3670 args->action, args->actionButton, args->flags,
3671 args->metaState, args->buttonState,
3672 args->classification, args->edgeFlags,
3673 args->xPrecision, args->yPrecision,
3674 args->xCursorPosition, args->yCursorPosition,
3675 args->downTime, args->pointerCount,
3676 args->pointerProperties, args->pointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003677
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003678 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003679 mLock.unlock();
3680 } // release lock
3681
3682 if (needWake) {
3683 mLooper->wake();
3684 }
3685}
3686
Chris Yef59a2f42020-10-16 12:55:26 -07003687void InputDispatcher::notifySensor(const NotifySensorArgs* args) {
3688#if DEBUG_INBOUND_EVENT_DETAILS
3689 ALOGD("notifySensor - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
3690 " sensorType=%s",
3691 args->id, args->eventTime, args->deviceId, args->source,
3692 NamedEnum::string(args->sensorType).c_str());
3693#endif
3694
3695 bool needWake;
3696 { // acquire lock
3697 mLock.lock();
3698
3699 // Just enqueue a new sensor event.
3700 std::unique_ptr<SensorEntry> newEntry =
3701 std::make_unique<SensorEntry>(args->id, args->eventTime, args->deviceId,
3702 args->source, 0 /* policyFlags*/, args->hwTimestamp,
3703 args->sensorType, args->accuracy,
3704 args->accuracyChanged, args->values);
3705
3706 needWake = enqueueInboundEventLocked(std::move(newEntry));
3707 mLock.unlock();
3708 } // release lock
3709
3710 if (needWake) {
3711 mLooper->wake();
3712 }
3713}
3714
Michael Wrightd02c5b62014-02-10 15:10:22 -08003715bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08003716 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003717}
3718
3719void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
3720#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003721 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003722 "switchMask=0x%08x",
3723 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003724#endif
3725
3726 uint32_t policyFlags = args->policyFlags;
3727 policyFlags |= POLICY_FLAG_TRUSTED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003728 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003729}
3730
3731void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
3732#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003733 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
3734 args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003735#endif
3736
3737 bool needWake;
3738 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003739 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003740
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003741 std::unique_ptr<DeviceResetEntry> newEntry =
3742 std::make_unique<DeviceResetEntry>(args->id, args->eventTime, args->deviceId);
3743 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003744 } // release lock
3745
3746 if (needWake) {
3747 mLooper->wake();
3748 }
3749}
3750
Prabir Pradhan7e186182020-11-10 13:56:45 -08003751void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs* args) {
3752#if DEBUG_INBOUND_EVENT_DETAILS
3753 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args->eventTime,
3754 args->enabled ? "true" : "false");
3755#endif
3756
Prabir Pradhan99987712020-11-10 18:43:05 -08003757 bool needWake;
3758 { // acquire lock
3759 std::scoped_lock _l(mLock);
3760 auto entry = std::make_unique<PointerCaptureChangedEntry>(args->id, args->eventTime,
3761 args->enabled);
3762 needWake = enqueueInboundEventLocked(std::move(entry));
3763 } // release lock
3764
3765 if (needWake) {
3766 mLooper->wake();
3767 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08003768}
3769
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003770InputEventInjectionResult InputDispatcher::injectInputEvent(
3771 const InputEvent* event, int32_t injectorPid, int32_t injectorUid,
3772 InputEventInjectionSync syncMode, std::chrono::milliseconds timeout, uint32_t policyFlags) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003773#if DEBUG_INBOUND_EVENT_DETAILS
3774 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003775 "syncMode=%d, timeout=%lld, policyFlags=0x%08x",
3776 event->getType(), injectorPid, injectorUid, syncMode, timeout.count(), policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003777#endif
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003778 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003779
3780 policyFlags |= POLICY_FLAG_INJECTED;
3781 if (hasInjectionPermission(injectorPid, injectorUid)) {
3782 policyFlags |= POLICY_FLAG_TRUSTED;
3783 }
3784
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003785 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003786 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003787 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003788 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
3789 int32_t action = incomingKey.getAction();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003790 if (!validateKeyEvent(action)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003791 return InputEventInjectionResult::FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003792 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003793
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003794 int32_t flags = incomingKey.getFlags();
3795 int32_t keyCode = incomingKey.getKeyCode();
3796 int32_t metaState = incomingKey.getMetaState();
3797 accelerateMetaShortcuts(VIRTUAL_KEYBOARD_ID, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003798 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003799 KeyEvent keyEvent;
Garfield Tan4cc839f2020-01-24 11:26:14 -08003800 keyEvent.initialize(incomingKey.getId(), VIRTUAL_KEYBOARD_ID, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003801 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
3802 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
3803 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003804
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003805 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
3806 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00003807 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003808
3809 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
3810 android::base::Timer t;
3811 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
3812 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3813 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
3814 std::to_string(t.duration().count()).c_str());
3815 }
3816 }
3817
3818 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003819 std::unique_ptr<KeyEntry> injectedEntry =
3820 std::make_unique<KeyEntry>(incomingKey.getId(), incomingKey.getEventTime(),
3821 VIRTUAL_KEYBOARD_ID, incomingKey.getSource(),
3822 incomingKey.getDisplayId(), policyFlags, action,
3823 flags, keyCode, incomingKey.getScanCode(), metaState,
3824 incomingKey.getRepeatCount(),
3825 incomingKey.getDownTime());
3826 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003827 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003828 }
3829
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003830 case AINPUT_EVENT_TYPE_MOTION: {
3831 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
3832 int32_t action = motionEvent->getAction();
3833 size_t pointerCount = motionEvent->getPointerCount();
3834 const PointerProperties* pointerProperties = motionEvent->getPointerProperties();
3835 int32_t actionButton = motionEvent->getActionButton();
3836 int32_t displayId = motionEvent->getDisplayId();
3837 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003838 return InputEventInjectionResult::FAILED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003839 }
3840
3841 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
3842 nsecs_t eventTime = motionEvent->getEventTime();
3843 android::base::Timer t;
3844 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
3845 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3846 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
3847 std::to_string(t.duration().count()).c_str());
3848 }
3849 }
3850
3851 mLock.lock();
3852 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
3853 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003854 std::unique_ptr<MotionEntry> injectedEntry =
3855 std::make_unique<MotionEntry>(motionEvent->getId(), *sampleEventTimes,
3856 VIRTUAL_KEYBOARD_ID, motionEvent->getSource(),
3857 motionEvent->getDisplayId(), policyFlags, action,
3858 actionButton, motionEvent->getFlags(),
3859 motionEvent->getMetaState(),
3860 motionEvent->getButtonState(),
3861 motionEvent->getClassification(),
3862 motionEvent->getEdgeFlags(),
3863 motionEvent->getXPrecision(),
3864 motionEvent->getYPrecision(),
3865 motionEvent->getRawXCursorPosition(),
3866 motionEvent->getRawYCursorPosition(),
3867 motionEvent->getDownTime(),
3868 uint32_t(pointerCount), pointerProperties,
3869 samplePointerCoords, motionEvent->getXOffset(),
3870 motionEvent->getYOffset());
3871 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003872 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
3873 sampleEventTimes += 1;
3874 samplePointerCoords += pointerCount;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003875 std::unique_ptr<MotionEntry> nextInjectedEntry =
3876 std::make_unique<MotionEntry>(motionEvent->getId(), *sampleEventTimes,
3877 VIRTUAL_KEYBOARD_ID, motionEvent->getSource(),
3878 motionEvent->getDisplayId(), policyFlags,
3879 action, actionButton, motionEvent->getFlags(),
3880 motionEvent->getMetaState(),
3881 motionEvent->getButtonState(),
3882 motionEvent->getClassification(),
3883 motionEvent->getEdgeFlags(),
3884 motionEvent->getXPrecision(),
3885 motionEvent->getYPrecision(),
3886 motionEvent->getRawXCursorPosition(),
3887 motionEvent->getRawYCursorPosition(),
3888 motionEvent->getDownTime(),
3889 uint32_t(pointerCount), pointerProperties,
3890 samplePointerCoords,
3891 motionEvent->getXOffset(),
3892 motionEvent->getYOffset());
3893 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003894 }
3895 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003896 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003897
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003898 default:
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08003899 ALOGW("Cannot inject %s events", inputEventTypeToString(event->getType()));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003900 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003901 }
3902
3903 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003904 if (syncMode == InputEventInjectionSync::NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003905 injectionState->injectionIsAsync = true;
3906 }
3907
3908 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003909 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003910
3911 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003912 while (!injectedEntries.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003913 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003914 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003915 }
3916
3917 mLock.unlock();
3918
3919 if (needWake) {
3920 mLooper->wake();
3921 }
3922
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003923 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003924 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003925 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003926
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003927 if (syncMode == InputEventInjectionSync::NONE) {
3928 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003929 } else {
3930 for (;;) {
3931 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003932 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003933 break;
3934 }
3935
3936 nsecs_t remainingTimeout = endTime - now();
3937 if (remainingTimeout <= 0) {
3938#if DEBUG_INJECTION
3939 ALOGD("injectInputEvent - Timed out waiting for injection result "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003940 "to become available.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003941#endif
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003942 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003943 break;
3944 }
3945
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003946 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003947 }
3948
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003949 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
3950 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003951 while (injectionState->pendingForegroundDispatches != 0) {
3952#if DEBUG_INJECTION
3953 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003954 injectionState->pendingForegroundDispatches);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003955#endif
3956 nsecs_t remainingTimeout = endTime - now();
3957 if (remainingTimeout <= 0) {
3958#if DEBUG_INJECTION
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003959 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
3960 "dispatches to finish.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003961#endif
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003962 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003963 break;
3964 }
3965
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003966 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003967 }
3968 }
3969 }
3970
3971 injectionState->release();
3972 } // release lock
3973
3974#if DEBUG_INJECTION
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003975 ALOGD("injectInputEvent - Finished with result %d. injectorPid=%d, injectorUid=%d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003976 injectionResult, injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003977#endif
3978
3979 return injectionResult;
3980}
3981
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08003982std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05003983 std::array<uint8_t, 32> calculatedHmac;
3984 std::unique_ptr<VerifiedInputEvent> result;
3985 switch (event.getType()) {
3986 case AINPUT_EVENT_TYPE_KEY: {
3987 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
3988 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
3989 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07003990 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05003991 break;
3992 }
3993 case AINPUT_EVENT_TYPE_MOTION: {
3994 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
3995 VerifiedMotionEvent verifiedMotionEvent =
3996 verifiedMotionEventFromMotionEvent(motionEvent);
3997 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07003998 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05003999 break;
4000 }
4001 default: {
4002 ALOGE("Cannot verify events of type %" PRId32, event.getType());
4003 return nullptr;
4004 }
4005 }
4006 if (calculatedHmac == INVALID_HMAC) {
4007 return nullptr;
4008 }
4009 if (calculatedHmac != event.getHmac()) {
4010 return nullptr;
4011 }
4012 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004013}
4014
Michael Wrightd02c5b62014-02-10 15:10:22 -08004015bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004016 return injectorUid == 0 ||
4017 mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004018}
4019
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004020void InputDispatcher::setInjectionResult(EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004021 InputEventInjectionResult injectionResult) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004022 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004023 if (injectionState) {
4024#if DEBUG_INJECTION
4025 ALOGD("Setting input event injection result to %d. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004026 "injectorPid=%d, injectorUid=%d",
4027 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004028#endif
4029
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004030 if (injectionState->injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004031 // Log the outcome since the injector did not wait for the injection result.
4032 switch (injectionResult) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004033 case InputEventInjectionResult::SUCCEEDED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004034 ALOGV("Asynchronous input event injection succeeded.");
4035 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004036 case InputEventInjectionResult::FAILED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004037 ALOGW("Asynchronous input event injection failed.");
4038 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004039 case InputEventInjectionResult::PERMISSION_DENIED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004040 ALOGW("Asynchronous input event injection permission denied.");
4041 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004042 case InputEventInjectionResult::TIMED_OUT:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004043 ALOGW("Asynchronous input event injection timed out.");
4044 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004045 case InputEventInjectionResult::PENDING:
4046 ALOGE("Setting result to 'PENDING' for asynchronous injection");
4047 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004048 }
4049 }
4050
4051 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004052 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004053 }
4054}
4055
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004056void InputDispatcher::incrementPendingForegroundDispatches(EventEntry& entry) {
4057 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004058 if (injectionState) {
4059 injectionState->pendingForegroundDispatches += 1;
4060 }
4061}
4062
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004063void InputDispatcher::decrementPendingForegroundDispatches(EventEntry& entry) {
4064 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004065 if (injectionState) {
4066 injectionState->pendingForegroundDispatches -= 1;
4067
4068 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004069 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004070 }
4071 }
4072}
4073
Vishnu Nairad321cd2020-08-20 16:40:21 -07004074const std::vector<sp<InputWindowHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004075 int32_t displayId) const {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004076 static const std::vector<sp<InputWindowHandle>> EMPTY_WINDOW_HANDLES;
4077 auto it = mWindowHandlesByDisplay.find(displayId);
4078 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08004079}
4080
Michael Wrightd02c5b62014-02-10 15:10:22 -08004081sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08004082 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08004083 if (windowHandleToken == nullptr) {
4084 return nullptr;
4085 }
4086
Arthur Hungb92218b2018-08-14 12:00:21 +08004087 for (auto& it : mWindowHandlesByDisplay) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004088 const std::vector<sp<InputWindowHandle>>& windowHandles = it.second;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004089 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004090 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004091 return windowHandle;
4092 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004093 }
4094 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004095 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004096}
4097
Vishnu Nairad321cd2020-08-20 16:40:21 -07004098sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(const sp<IBinder>& windowHandleToken,
4099 int displayId) const {
4100 if (windowHandleToken == nullptr) {
4101 return nullptr;
4102 }
4103
4104 for (const sp<InputWindowHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
4105 if (windowHandle->getToken() == windowHandleToken) {
4106 return windowHandle;
4107 }
4108 }
4109 return nullptr;
4110}
4111
4112sp<InputWindowHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
4113 sp<IBinder> focusedToken = getValueByKey(mFocusedWindowTokenByDisplay, displayId);
4114 return getWindowHandleLocked(focusedToken, displayId);
4115}
4116
Mady Mellor017bcd12020-06-23 19:12:00 +00004117bool InputDispatcher::hasWindowHandleLocked(const sp<InputWindowHandle>& windowHandle) const {
4118 for (auto& it : mWindowHandlesByDisplay) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004119 const std::vector<sp<InputWindowHandle>>& windowHandles = it.second;
Mady Mellor017bcd12020-06-23 19:12:00 +00004120 for (const sp<InputWindowHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08004121 if (handle->getId() == windowHandle->getId() &&
4122 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004123 if (windowHandle->getInfo()->displayId != it.first) {
4124 ALOGE("Found window %s in display %" PRId32
4125 ", but it should belong to display %" PRId32,
4126 windowHandle->getName().c_str(), it.first,
4127 windowHandle->getInfo()->displayId);
4128 }
4129 return true;
Arthur Hungb92218b2018-08-14 12:00:21 +08004130 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004131 }
4132 }
4133 return false;
4134}
4135
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004136bool InputDispatcher::hasResponsiveConnectionLocked(InputWindowHandle& windowHandle) const {
4137 sp<Connection> connection = getConnectionLocked(windowHandle.getToken());
4138 const bool noInputChannel =
4139 windowHandle.getInfo()->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
4140 if (connection != nullptr && noInputChannel) {
4141 ALOGW("%s has feature NO_INPUT_CHANNEL, but it matched to connection %s",
4142 windowHandle.getName().c_str(), connection->inputChannel->getName().c_str());
4143 return false;
4144 }
4145
4146 if (connection == nullptr) {
4147 if (!noInputChannel) {
4148 ALOGI("Could not find connection for %s", windowHandle.getName().c_str());
4149 }
4150 return false;
4151 }
4152 if (!connection->responsive) {
4153 ALOGW("Window %s is not responsive", windowHandle.getName().c_str());
4154 return false;
4155 }
4156 return true;
4157}
4158
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004159std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
4160 const sp<IBinder>& token) const {
Robert Carr5c8a0262018-10-03 16:30:44 -07004161 size_t count = mInputChannelsByToken.count(token);
4162 if (count == 0) {
4163 return nullptr;
4164 }
4165 return mInputChannelsByToken.at(token);
4166}
4167
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004168void InputDispatcher::updateWindowHandlesForDisplayLocked(
4169 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
4170 if (inputWindowHandles.empty()) {
4171 // Remove all handles on a display if there are no windows left.
4172 mWindowHandlesByDisplay.erase(displayId);
4173 return;
4174 }
4175
4176 // Since we compare the pointer of input window handles across window updates, we need
4177 // to make sure the handle object for the same window stays unchanged across updates.
4178 const std::vector<sp<InputWindowHandle>>& oldHandles = getWindowHandlesLocked(displayId);
chaviwaf87b3e2019-10-01 16:59:28 -07004179 std::unordered_map<int32_t /*id*/, sp<InputWindowHandle>> oldHandlesById;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004180 for (const sp<InputWindowHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07004181 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004182 }
4183
4184 std::vector<sp<InputWindowHandle>> newHandles;
4185 for (const sp<InputWindowHandle>& handle : inputWindowHandles) {
4186 if (!handle->updateInfo()) {
4187 // handle no longer valid
4188 continue;
4189 }
4190
4191 const InputWindowInfo* info = handle->getInfo();
4192 if ((getInputChannelLocked(handle->getToken()) == nullptr &&
4193 info->portalToDisplayId == ADISPLAY_ID_NONE)) {
4194 const bool noInputChannel =
Michael Wright44753b12020-07-08 13:48:11 +01004195 info->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
4196 const bool canReceiveInput = !info->flags.test(InputWindowInfo::Flag::NOT_TOUCHABLE) ||
4197 !info->flags.test(InputWindowInfo::Flag::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004198 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07004199 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004200 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07004201 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004202 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004203 }
4204
4205 if (info->displayId != displayId) {
4206 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
4207 handle->getName().c_str(), displayId, info->displayId);
4208 continue;
4209 }
4210
Robert Carredd13602020-04-13 17:24:34 -07004211 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
4212 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviwaf87b3e2019-10-01 16:59:28 -07004213 const sp<InputWindowHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004214 oldHandle->updateFrom(handle);
4215 newHandles.push_back(oldHandle);
4216 } else {
4217 newHandles.push_back(handle);
4218 }
4219 }
4220
4221 // Insert or replace
4222 mWindowHandlesByDisplay[displayId] = newHandles;
4223}
4224
Arthur Hung72d8dc32020-03-28 00:48:39 +00004225void InputDispatcher::setInputWindows(
4226 const std::unordered_map<int32_t, std::vector<sp<InputWindowHandle>>>& handlesPerDisplay) {
4227 { // acquire lock
4228 std::scoped_lock _l(mLock);
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004229 for (const auto& [displayId, handles] : handlesPerDisplay) {
4230 setInputWindowsLocked(handles, displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004231 }
4232 }
4233 // Wake up poll loop since it may need to make new input dispatching choices.
4234 mLooper->wake();
4235}
4236
Arthur Hungb92218b2018-08-14 12:00:21 +08004237/**
4238 * Called from InputManagerService, update window handle list by displayId that can receive input.
4239 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
4240 * If set an empty list, remove all handles from the specific display.
4241 * For focused handle, check if need to change and send a cancel event to previous one.
4242 * For removed handle, check if need to send a cancel event if already in touch.
4243 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00004244void InputDispatcher::setInputWindowsLocked(
4245 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004246 if (DEBUG_FOCUS) {
4247 std::string windowList;
4248 for (const sp<InputWindowHandle>& iwh : inputWindowHandles) {
4249 windowList += iwh->getName() + " ";
4250 }
4251 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
4252 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004253
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004254 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
4255 for (const sp<InputWindowHandle>& window : inputWindowHandles) {
4256 const bool noInputWindow =
4257 window->getInfo()->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
4258 if (noInputWindow && window->getToken() != nullptr) {
4259 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
4260 window->getName().c_str());
4261 window->releaseChannel();
4262 }
4263 }
4264
Arthur Hung72d8dc32020-03-28 00:48:39 +00004265 // Copy old handles for release if they are no longer present.
4266 const std::vector<sp<InputWindowHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004267
Arthur Hung72d8dc32020-03-28 00:48:39 +00004268 updateWindowHandlesForDisplayLocked(inputWindowHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004269
Vishnu Nair958da932020-08-21 17:12:37 -07004270 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
4271 if (mLastHoverWindowHandle &&
4272 std::find(windowHandles.begin(), windowHandles.end(), mLastHoverWindowHandle) ==
4273 windowHandles.end()) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004274 mLastHoverWindowHandle = nullptr;
4275 }
4276
Vishnu Nair958da932020-08-21 17:12:37 -07004277 sp<IBinder> focusedToken = getValueByKey(mFocusedWindowTokenByDisplay, displayId);
4278 if (focusedToken) {
4279 FocusResult result = checkTokenFocusableLocked(focusedToken, displayId);
4280 if (result != FocusResult::OK) {
4281 onFocusChangedLocked(focusedToken, nullptr, displayId, typeToString(result));
4282 }
4283 }
4284
4285 std::optional<FocusRequest> focusRequest =
4286 getOptionalValueByKey(mPendingFocusRequests, displayId);
4287 if (focusRequest) {
4288 // If the window from the pending request is now visible, provide it focus.
4289 FocusResult result = handleFocusRequestLocked(*focusRequest);
4290 if (result != FocusResult::NOT_VISIBLE) {
4291 // Drop the request if we were able to change the focus or we cannot change
4292 // it for another reason.
4293 mPendingFocusRequests.erase(displayId);
4294 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004295 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004296
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004297 std::unordered_map<int32_t, TouchState>::iterator stateIt =
4298 mTouchStatesByDisplay.find(displayId);
4299 if (stateIt != mTouchStatesByDisplay.end()) {
4300 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00004301 for (size_t i = 0; i < state.windows.size();) {
4302 TouchedWindow& touchedWindow = state.windows[i];
Mady Mellor017bcd12020-06-23 19:12:00 +00004303 if (!hasWindowHandleLocked(touchedWindow.windowHandle)) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004304 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004305 ALOGD("Touched window was removed: %s in display %" PRId32,
4306 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004307 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004308 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00004309 getInputChannelLocked(touchedWindow.windowHandle->getToken());
4310 if (touchedInputChannel != nullptr) {
4311 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4312 "touched window was removed");
4313 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004314 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004315 state.windows.erase(state.windows.begin() + i);
4316 } else {
4317 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004318 }
4319 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004320 }
Arthur Hung25e2af12020-03-26 12:58:37 +00004321
Arthur Hung72d8dc32020-03-28 00:48:39 +00004322 // Release information for windows that are no longer present.
4323 // This ensures that unused input channels are released promptly.
4324 // Otherwise, they might stick around until the window handle is destroyed
4325 // which might not happen until the next GC.
4326 for (const sp<InputWindowHandle>& oldWindowHandle : oldWindowHandles) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004327 if (!hasWindowHandleLocked(oldWindowHandle)) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004328 if (DEBUG_FOCUS) {
4329 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00004330 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004331 oldWindowHandle->releaseChannel();
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004332 // To avoid making too many calls into the compat framework, only
4333 // check for window flags when windows are going away.
4334 // TODO(b/157929241) : delete this. This is only needed temporarily
4335 // in order to gather some data about the flag usage
4336 if (oldWindowHandle->getInfo()->flags.test(InputWindowInfo::Flag::SLIPPERY)) {
4337 ALOGW("%s has FLAG_SLIPPERY. Please report this in b/157929241",
4338 oldWindowHandle->getName().c_str());
4339 if (mCompatService != nullptr) {
4340 mCompatService->reportChangeByUid(IInputConstants::BLOCK_FLAG_SLIPPERY,
4341 oldWindowHandle->getInfo()->ownerUid);
4342 }
4343 }
Arthur Hung25e2af12020-03-26 12:58:37 +00004344 }
chaviw291d88a2019-02-14 10:33:58 -08004345 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004346}
4347
4348void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07004349 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004350 if (DEBUG_FOCUS) {
4351 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
4352 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
4353 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004354 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004355 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004356
Chris Yea209fde2020-07-22 13:54:51 -07004357 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08004358 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004359
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004360 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
4361 return; // This application is already focused. No need to wake up or change anything.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004362 }
4363
Chris Yea209fde2020-07-22 13:54:51 -07004364 // Set the new application handle.
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004365 if (inputApplicationHandle != nullptr) {
4366 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
4367 } else {
4368 mFocusedApplicationHandlesByDisplay.erase(displayId);
4369 }
4370
4371 // No matter what the old focused application was, stop waiting on it because it is
4372 // no longer focused.
4373 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004374 } // release lock
4375
4376 // Wake up poll loop since it may need to make new input dispatching choices.
4377 mLooper->wake();
4378}
4379
Tiger Huang721e26f2018-07-24 22:26:19 +08004380/**
4381 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
4382 * the display not specified.
4383 *
4384 * We track any unreleased events for each window. If a window loses the ability to receive the
4385 * released event, we will send a cancel event to it. So when the focused display is changed, we
4386 * cancel all the unreleased display-unspecified events for the focused window on the old focused
4387 * display. The display-specified events won't be affected.
4388 */
4389void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004390 if (DEBUG_FOCUS) {
4391 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
4392 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004393 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004394 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08004395
4396 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004397 sp<IBinder> oldFocusedWindowToken =
4398 getValueByKey(mFocusedWindowTokenByDisplay, mFocusedDisplayId);
4399 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004400 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07004401 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08004402 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004403 CancelationOptions
4404 options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
4405 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004406 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08004407 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
4408 }
4409 }
4410 mFocusedDisplayId = displayId;
4411
Chris Ye3c2d6f52020-08-09 10:39:48 -07004412 // Find new focused window and validate
Vishnu Nairad321cd2020-08-20 16:40:21 -07004413 sp<IBinder> newFocusedWindowToken =
4414 getValueByKey(mFocusedWindowTokenByDisplay, displayId);
4415 notifyFocusChangedLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08004416
Vishnu Nairad321cd2020-08-20 16:40:21 -07004417 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08004418 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07004419 if (!mFocusedWindowTokenByDisplay.empty()) {
4420 ALOGE("But another display has a focused window\n%s",
4421 dumpFocusedWindowsLocked().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08004422 }
4423 }
4424 }
4425
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004426 if (DEBUG_FOCUS) {
4427 logDispatchStateLocked();
4428 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004429 } // release lock
4430
4431 // Wake up poll loop since it may need to make new input dispatching choices.
4432 mLooper->wake();
4433}
4434
Michael Wrightd02c5b62014-02-10 15:10:22 -08004435void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004436 if (DEBUG_FOCUS) {
4437 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
4438 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004439
4440 bool changed;
4441 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004442 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004443
4444 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
4445 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004446 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004447 }
4448
4449 if (mDispatchEnabled && !enabled) {
4450 resetAndDropEverythingLocked("dispatcher is being disabled");
4451 }
4452
4453 mDispatchEnabled = enabled;
4454 mDispatchFrozen = frozen;
4455 changed = true;
4456 } else {
4457 changed = false;
4458 }
4459
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004460 if (DEBUG_FOCUS) {
4461 logDispatchStateLocked();
4462 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004463 } // release lock
4464
4465 if (changed) {
4466 // Wake up poll loop since it may need to make new input dispatching choices.
4467 mLooper->wake();
4468 }
4469}
4470
4471void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004472 if (DEBUG_FOCUS) {
4473 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
4474 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004475
4476 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004477 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004478
4479 if (mInputFilterEnabled == enabled) {
4480 return;
4481 }
4482
4483 mInputFilterEnabled = enabled;
4484 resetAndDropEverythingLocked("input filter is being enabled or disabled");
4485 } // release lock
4486
4487 // Wake up poll loop since there might be work to do to drop everything.
4488 mLooper->wake();
4489}
4490
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08004491void InputDispatcher::setInTouchMode(bool inTouchMode) {
4492 std::scoped_lock lock(mLock);
4493 mInTouchMode = inTouchMode;
4494}
4495
Bernardo Rufinoea97d182020-08-19 14:43:14 +01004496void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
4497 if (opacity < 0 || opacity > 1) {
4498 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
4499 return;
4500 }
4501
4502 std::scoped_lock lock(mLock);
4503 mMaximumObscuringOpacityForTouch = opacity;
4504}
4505
4506void InputDispatcher::setBlockUntrustedTouchesMode(BlockUntrustedTouchesMode mode) {
4507 std::scoped_lock lock(mLock);
4508 mBlockUntrustedTouchesMode = mode;
4509}
4510
chaviwfbe5d9c2018-12-26 12:23:37 -08004511bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken) {
4512 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004513 if (DEBUG_FOCUS) {
4514 ALOGD("Trivial transfer to same window.");
4515 }
chaviwfbe5d9c2018-12-26 12:23:37 -08004516 return true;
4517 }
4518
Michael Wrightd02c5b62014-02-10 15:10:22 -08004519 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004520 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004521
chaviwfbe5d9c2018-12-26 12:23:37 -08004522 sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromToken);
4523 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toToken);
Yi Kong9b14ac62018-07-17 13:48:38 -07004524 if (fromWindowHandle == nullptr || toWindowHandle == nullptr) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004525 ALOGW("Cannot transfer focus because from or to window not found.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004526 return false;
4527 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004528 if (DEBUG_FOCUS) {
4529 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
4530 fromWindowHandle->getName().c_str(), toWindowHandle->getName().c_str());
4531 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004532 if (fromWindowHandle->getInfo()->displayId != toWindowHandle->getInfo()->displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004533 if (DEBUG_FOCUS) {
4534 ALOGD("Cannot transfer focus because windows are on different displays.");
4535 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004536 return false;
4537 }
4538
4539 bool found = false;
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004540 for (std::pair<const int32_t, TouchState>& pair : mTouchStatesByDisplay) {
4541 TouchState& state = pair.second;
Jeff Brownf086ddb2014-02-11 14:28:48 -08004542 for (size_t i = 0; i < state.windows.size(); i++) {
4543 const TouchedWindow& touchedWindow = state.windows[i];
4544 if (touchedWindow.windowHandle == fromWindowHandle) {
4545 int32_t oldTargetFlags = touchedWindow.targetFlags;
4546 BitSet32 pointerIds = touchedWindow.pointerIds;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004547
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004548 state.windows.erase(state.windows.begin() + i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004549
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004550 int32_t newTargetFlags = oldTargetFlags &
4551 (InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_SPLIT |
4552 InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004553 state.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004554
Jeff Brownf086ddb2014-02-11 14:28:48 -08004555 found = true;
4556 goto Found;
4557 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004558 }
4559 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004560 Found:
Michael Wrightd02c5b62014-02-10 15:10:22 -08004561
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004562 if (!found) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004563 if (DEBUG_FOCUS) {
4564 ALOGD("Focus transfer failed because from window did not have focus.");
4565 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004566 return false;
4567 }
4568
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004569 sp<Connection> fromConnection = getConnectionLocked(fromToken);
4570 sp<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004571 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004572 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004573 CancelationOptions
4574 options(CancelationOptions::CANCEL_POINTER_EVENTS,
4575 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004576 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004577 synthesizePointerDownEventsForConnectionLocked(toConnection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004578 }
4579
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004580 if (DEBUG_FOCUS) {
4581 logDispatchStateLocked();
4582 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004583 } // release lock
4584
4585 // Wake up poll loop since it may need to make new input dispatching choices.
4586 mLooper->wake();
4587 return true;
4588}
4589
4590void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004591 if (DEBUG_FOCUS) {
4592 ALOGD("Resetting and dropping all events (%s).", reason);
4593 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004594
4595 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
4596 synthesizeCancelationEventsForAllConnectionsLocked(options);
4597
4598 resetKeyRepeatLocked();
4599 releasePendingEventLocked();
4600 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004601 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004602
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004603 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08004604 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004605 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07004606 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004607}
4608
4609void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004610 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004611 dumpDispatchStateLocked(dump);
4612
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004613 std::istringstream stream(dump);
4614 std::string line;
4615
4616 while (std::getline(stream, line, '\n')) {
4617 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004618 }
4619}
4620
Vishnu Nairad321cd2020-08-20 16:40:21 -07004621std::string InputDispatcher::dumpFocusedWindowsLocked() {
4622 if (mFocusedWindowTokenByDisplay.empty()) {
4623 return INDENT "FocusedWindows: <none>\n";
4624 }
4625
4626 std::string dump;
4627 dump += INDENT "FocusedWindows:\n";
4628 for (auto& it : mFocusedWindowTokenByDisplay) {
4629 const int32_t displayId = it.first;
4630 const sp<InputWindowHandle> windowHandle = getFocusedWindowHandleLocked(displayId);
4631 if (windowHandle) {
4632 dump += StringPrintf(INDENT2 "displayId=%" PRId32 ", name='%s'\n", displayId,
4633 windowHandle->getName().c_str());
4634 } else {
4635 dump += StringPrintf(INDENT2 "displayId=%" PRId32
4636 " has focused token without a window'\n",
4637 displayId);
4638 }
4639 }
4640 return dump;
4641}
4642
Siarhei Vishniakouad991402020-10-28 11:40:09 -05004643std::string InputDispatcher::dumpPendingFocusRequestsLocked() {
4644 if (mPendingFocusRequests.empty()) {
4645 return INDENT "mPendingFocusRequests: <none>\n";
4646 }
4647
4648 std::string dump;
4649 dump += INDENT "mPendingFocusRequests:\n";
4650 for (const auto& [displayId, focusRequest] : mPendingFocusRequests) {
4651 // Rather than printing raw values for focusRequest.token and focusRequest.focusedToken,
4652 // try to resolve them to actual windows.
4653 std::string windowName = getConnectionNameLocked(focusRequest.token);
4654 std::string focusedWindowName = getConnectionNameLocked(focusRequest.focusedToken);
4655 dump += StringPrintf(INDENT2 "displayId=%" PRId32 ", token->%s, focusedToken->%s\n",
4656 displayId, windowName.c_str(), focusedWindowName.c_str());
4657 }
4658 return dump;
4659}
4660
Prabir Pradhan99987712020-11-10 18:43:05 -08004661std::string InputDispatcher::dumpPointerCaptureStateLocked() {
4662 std::string dump;
4663
4664 dump += StringPrintf(INDENT "FocusedWindowRequestedPointerCapture: %s\n",
4665 toString(mFocusedWindowRequestedPointerCapture));
4666
4667 std::string windowName = "None";
4668 if (mWindowTokenWithPointerCapture) {
4669 const sp<InputWindowHandle> captureWindowHandle =
4670 getWindowHandleLocked(mWindowTokenWithPointerCapture);
4671 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
4672 : "token has capture without window";
4673 }
4674 dump += StringPrintf(INDENT "CurrentWindowWithPointerCapture: %s\n", windowName.c_str());
4675
4676 return dump;
4677}
4678
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004679void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07004680 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
4681 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
4682 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08004683 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004684
Tiger Huang721e26f2018-07-24 22:26:19 +08004685 if (!mFocusedApplicationHandlesByDisplay.empty()) {
4686 dump += StringPrintf(INDENT "FocusedApplications:\n");
4687 for (auto& it : mFocusedApplicationHandlesByDisplay) {
4688 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07004689 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05004690 const std::chrono::duration timeout =
4691 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004692 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004693 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05004694 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08004695 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004696 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08004697 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004698 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004699
Vishnu Nairad321cd2020-08-20 16:40:21 -07004700 dump += dumpFocusedWindowsLocked();
Siarhei Vishniakouad991402020-10-28 11:40:09 -05004701 dump += dumpPendingFocusRequestsLocked();
Prabir Pradhan99987712020-11-10 18:43:05 -08004702 dump += dumpPointerCaptureStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004703
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004704 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004705 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004706 for (const std::pair<int32_t, TouchState>& pair : mTouchStatesByDisplay) {
4707 const TouchState& state = pair.second;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004708 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004709 state.displayId, toString(state.down), toString(state.split),
4710 state.deviceId, state.source);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004711 if (!state.windows.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004712 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004713 for (size_t i = 0; i < state.windows.size(); i++) {
4714 const TouchedWindow& touchedWindow = state.windows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004715 dump += StringPrintf(INDENT4
4716 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
4717 i, touchedWindow.windowHandle->getName().c_str(),
4718 touchedWindow.pointerIds.value, touchedWindow.targetFlags);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004719 }
4720 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004721 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004722 }
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004723 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004724 dump += INDENT3 "Portal windows:\n";
4725 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004726 const sp<InputWindowHandle> portalWindowHandle = state.portalWindows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004727 dump += StringPrintf(INDENT4 "%zu: name='%s'\n", i,
4728 portalWindowHandle->getName().c_str());
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004729 }
4730 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004731 }
4732 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004733 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004734 }
4735
Arthur Hungb92218b2018-08-14 12:00:21 +08004736 if (!mWindowHandlesByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004737 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004738 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
Arthur Hung3b413f22018-10-26 18:05:34 +08004739 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", it.first);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004740 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004741 dump += INDENT2 "Windows:\n";
4742 for (size_t i = 0; i < windowHandles.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004743 const sp<InputWindowHandle>& windowHandle = windowHandles[i];
Arthur Hungb92218b2018-08-14 12:00:21 +08004744 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004745
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00004746 dump += StringPrintf(INDENT3 "%zu: name='%s', id=%" PRId32 ", displayId=%d, "
Vishnu Nair47074b82020-08-14 11:54:47 -07004747 "portalToDisplayId=%d, paused=%s, focusable=%s, "
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00004748 "hasWallpaper=%s, visible=%s, alpha=%.2f, "
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00004749 "flags=%s, type=%s, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004750 "frame=[%d,%d][%d,%d], globalScale=%f, "
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004751 "applicationInfo=%s, "
chaviw1ff3d1e2020-07-01 15:53:47 -07004752 "touchableRegion=",
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00004753 i, windowInfo->name.c_str(), windowInfo->id,
4754 windowInfo->displayId, windowInfo->portalToDisplayId,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004755 toString(windowInfo->paused),
Vishnu Nair47074b82020-08-14 11:54:47 -07004756 toString(windowInfo->focusable),
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004757 toString(windowInfo->hasWallpaper),
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00004758 toString(windowInfo->visible), windowInfo->alpha,
Michael Wright8759d672020-07-21 00:46:45 +01004759 windowInfo->flags.string().c_str(),
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00004760 NamedEnum::string(windowInfo->type).c_str(),
Michael Wright44753b12020-07-08 13:48:11 +01004761 windowInfo->frameLeft, windowInfo->frameTop,
4762 windowInfo->frameRight, windowInfo->frameBottom,
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004763 windowInfo->globalScaleFactor,
4764 windowInfo->applicationInfo.name.c_str());
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00004765 dump += dumpRegion(windowInfo->touchableRegion);
Michael Wright44753b12020-07-08 13:48:11 +01004766 dump += StringPrintf(", inputFeatures=%s",
4767 windowInfo->inputFeatures.string().c_str());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004768 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%" PRId64
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00004769 "ms, trustedOverlay=%s, hasToken=%s, "
4770 "touchOcclusionMode=%s\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004771 windowInfo->ownerPid, windowInfo->ownerUid,
Bernardo Rufinoc2f1fad2020-11-04 17:30:57 +00004772 millis(windowInfo->dispatchingTimeout),
4773 toString(windowInfo->trustedOverlay),
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00004774 toString(windowInfo->token != nullptr),
4775 toString(windowInfo->touchOcclusionMode).c_str());
chaviw85b44202020-07-24 11:46:21 -07004776 windowInfo->transform.dump(dump, "transform", INDENT4);
Arthur Hungb92218b2018-08-14 12:00:21 +08004777 }
4778 } else {
4779 dump += INDENT2 "Windows: <none>\n";
4780 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004781 }
4782 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08004783 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004784 }
4785
Michael Wright3dd60e22019-03-27 22:06:44 +00004786 if (!mGlobalMonitorsByDisplay.empty() || !mGestureMonitorsByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004787 for (auto& it : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004788 const std::vector<Monitor>& monitors = it.second;
4789 dump += StringPrintf(INDENT "Global monitors in display %" PRId32 ":\n", it.first);
4790 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004791 }
4792 for (auto& it : mGestureMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004793 const std::vector<Monitor>& monitors = it.second;
4794 dump += StringPrintf(INDENT "Gesture monitors in display %" PRId32 ":\n", it.first);
4795 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004796 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004797 } else {
Michael Wright3dd60e22019-03-27 22:06:44 +00004798 dump += INDENT "Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004799 }
4800
4801 nsecs_t currentTime = now();
4802
4803 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004804 if (!mRecentQueue.empty()) {
4805 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004806 for (std::shared_ptr<EventEntry>& entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004807 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05004808 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004809 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004810 }
4811 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004812 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004813 }
4814
4815 // Dump event currently being dispatched.
4816 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004817 dump += INDENT "PendingEvent:\n";
4818 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05004819 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004820 dump += StringPrintf(", age=%" PRId64 "ms\n",
4821 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004822 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004823 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004824 }
4825
4826 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004827 if (!mInboundQueue.empty()) {
4828 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004829 for (std::shared_ptr<EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004830 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05004831 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004832 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004833 }
4834 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004835 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004836 }
4837
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004838 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004839 dump += INDENT "ReplacedKeys:\n";
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004840 for (const std::pair<KeyReplacement, int32_t>& pair : mReplacedKeys) {
4841 const KeyReplacement& replacement = pair.first;
4842 int32_t newKeyCode = pair.second;
4843 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004844 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07004845 }
4846 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004847 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07004848 }
4849
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004850 if (!mConnectionsByFd.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004851 dump += INDENT "Connections:\n";
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004852 for (const auto& pair : mConnectionsByFd) {
4853 const sp<Connection>& connection = pair.second;
4854 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004855 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004856 pair.first, connection->getInputChannelName().c_str(),
4857 connection->getWindowName().c_str(), connection->getStatusLabel(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004858 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004859
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004860 if (!connection->outboundQueue.empty()) {
4861 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
4862 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05004863 dump += dumpQueue(connection->outboundQueue, currentTime);
4864
Michael Wrightd02c5b62014-02-10 15:10:22 -08004865 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004866 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004867 }
4868
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004869 if (!connection->waitQueue.empty()) {
4870 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
4871 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05004872 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004873 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004874 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004875 }
4876 }
4877 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004878 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004879 }
4880
4881 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004882 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
4883 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004884 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004885 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004886 }
4887
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004888 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004889 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
4890 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
4891 ns2ms(mConfig.keyRepeatTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004892}
4893
Michael Wright3dd60e22019-03-27 22:06:44 +00004894void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
4895 const size_t numMonitors = monitors.size();
4896 for (size_t i = 0; i < numMonitors; i++) {
4897 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004898 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00004899 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
4900 dump += "\n";
4901 }
4902}
4903
Garfield Tan15601662020-09-22 15:32:38 -07004904base::Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(
4905 const std::string& name) {
4906#if DEBUG_CHANNEL_CREATION
4907 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004908#endif
4909
Garfield Tan15601662020-09-22 15:32:38 -07004910 std::shared_ptr<InputChannel> serverChannel;
4911 std::unique_ptr<InputChannel> clientChannel;
4912 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
4913
4914 if (result) {
4915 return base::Error(result) << "Failed to open input channel pair with name " << name;
4916 }
4917
Michael Wrightd02c5b62014-02-10 15:10:22 -08004918 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004919 std::scoped_lock _l(mLock);
Garfield Tan15601662020-09-22 15:32:38 -07004920 sp<Connection> connection = new Connection(serverChannel, false /*monitor*/, mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004921
Garfield Tan15601662020-09-22 15:32:38 -07004922 int fd = serverChannel->getFd();
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004923 mConnectionsByFd[fd] = connection;
Garfield Tan15601662020-09-22 15:32:38 -07004924 mInputChannelsByToken[serverChannel->getConnectionToken()] = serverChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004925
Michael Wrightd02c5b62014-02-10 15:10:22 -08004926 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
4927 } // release lock
4928
4929 // Wake the looper because some connections have changed.
4930 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07004931 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004932}
4933
Garfield Tan15601662020-09-22 15:32:38 -07004934base::Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(
Siarhei Vishniakou58cfc602020-12-14 23:21:30 +00004935 int32_t displayId, bool isGestureMonitor, const std::string& name, int32_t pid) {
Garfield Tan15601662020-09-22 15:32:38 -07004936 std::shared_ptr<InputChannel> serverChannel;
4937 std::unique_ptr<InputChannel> clientChannel;
4938 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
4939 if (result) {
4940 return base::Error(result) << "Failed to open input channel pair with name " << name;
4941 }
4942
Michael Wright3dd60e22019-03-27 22:06:44 +00004943 { // acquire lock
4944 std::scoped_lock _l(mLock);
4945
4946 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07004947 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
4948 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00004949 }
4950
Garfield Tan15601662020-09-22 15:32:38 -07004951 sp<Connection> connection = new Connection(serverChannel, true /*monitor*/, mIdGenerator);
Michael Wright3dd60e22019-03-27 22:06:44 +00004952
Garfield Tan15601662020-09-22 15:32:38 -07004953 const int fd = serverChannel->getFd();
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004954 mConnectionsByFd[fd] = connection;
Garfield Tan15601662020-09-22 15:32:38 -07004955 mInputChannelsByToken[serverChannel->getConnectionToken()] = serverChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00004956
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004957 auto& monitorsByDisplay =
4958 isGestureMonitor ? mGestureMonitorsByDisplay : mGlobalMonitorsByDisplay;
Siarhei Vishniakou58cfc602020-12-14 23:21:30 +00004959 monitorsByDisplay[displayId].emplace_back(serverChannel, pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00004960
4961 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
Michael Wright3dd60e22019-03-27 22:06:44 +00004962 }
Garfield Tan15601662020-09-22 15:32:38 -07004963
Michael Wright3dd60e22019-03-27 22:06:44 +00004964 // Wake the looper because some connections have changed.
4965 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07004966 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00004967}
4968
Garfield Tan15601662020-09-22 15:32:38 -07004969status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004970 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004971 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004972
Garfield Tan15601662020-09-22 15:32:38 -07004973 status_t status = removeInputChannelLocked(connectionToken, false /*notify*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004974 if (status) {
4975 return status;
4976 }
4977 } // release lock
4978
4979 // Wake the poll loop because removing the connection may have changed the current
4980 // synchronization state.
4981 mLooper->wake();
4982 return OK;
4983}
4984
Garfield Tan15601662020-09-22 15:32:38 -07004985status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
4986 bool notify) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004987 sp<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004988 if (connection == nullptr) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004989 ALOGW("Attempted to unregister already unregistered input channel");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004990 return BAD_VALUE;
4991 }
4992
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004993 removeConnectionLocked(connection);
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004994 mInputChannelsByToken.erase(connectionToken);
Robert Carr5c8a0262018-10-03 16:30:44 -07004995
Michael Wrightd02c5b62014-02-10 15:10:22 -08004996 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004997 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004998 }
4999
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005000 mLooper->removeFd(connection->inputChannel->getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005001
5002 nsecs_t currentTime = now();
5003 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
5004
5005 connection->status = Connection::STATUS_ZOMBIE;
5006 return OK;
5007}
5008
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005009void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
5010 removeMonitorChannelLocked(connectionToken, mGlobalMonitorsByDisplay);
5011 removeMonitorChannelLocked(connectionToken, mGestureMonitorsByDisplay);
Michael Wright3dd60e22019-03-27 22:06:44 +00005012}
5013
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005014void InputDispatcher::removeMonitorChannelLocked(
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005015 const sp<IBinder>& connectionToken,
Michael Wright3dd60e22019-03-27 22:06:44 +00005016 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005017 for (auto it = monitorsByDisplay.begin(); it != monitorsByDisplay.end();) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005018 std::vector<Monitor>& monitors = it->second;
5019 const size_t numMonitors = monitors.size();
5020 for (size_t i = 0; i < numMonitors; i++) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005021 if (monitors[i].inputChannel->getConnectionToken() == connectionToken) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005022 monitors.erase(monitors.begin() + i);
5023 break;
5024 }
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005025 }
Michael Wright3dd60e22019-03-27 22:06:44 +00005026 if (monitors.empty()) {
5027 it = monitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005028 } else {
5029 ++it;
5030 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005031 }
5032}
5033
Michael Wright3dd60e22019-03-27 22:06:44 +00005034status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
5035 { // acquire lock
5036 std::scoped_lock _l(mLock);
5037 std::optional<int32_t> foundDisplayId = findGestureMonitorDisplayByTokenLocked(token);
5038
5039 if (!foundDisplayId) {
5040 ALOGW("Attempted to pilfer pointers from an un-registered monitor or invalid token");
5041 return BAD_VALUE;
5042 }
5043 int32_t displayId = foundDisplayId.value();
5044
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005045 std::unordered_map<int32_t, TouchState>::iterator stateIt =
5046 mTouchStatesByDisplay.find(displayId);
5047 if (stateIt == mTouchStatesByDisplay.end()) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005048 ALOGW("Failed to pilfer pointers: no pointers on display %" PRId32 ".", displayId);
5049 return BAD_VALUE;
5050 }
5051
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005052 TouchState& state = stateIt->second;
Michael Wright3dd60e22019-03-27 22:06:44 +00005053 std::optional<int32_t> foundDeviceId;
5054 for (const TouchedMonitor& touchedMonitor : state.gestureMonitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005055 if (touchedMonitor.monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005056 foundDeviceId = state.deviceId;
5057 }
5058 }
5059 if (!foundDeviceId || !state.down) {
5060 ALOGW("Attempted to pilfer points from a monitor without any on-going pointer streams."
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005061 " Ignoring.");
Michael Wright3dd60e22019-03-27 22:06:44 +00005062 return BAD_VALUE;
5063 }
5064 int32_t deviceId = foundDeviceId.value();
5065
5066 // Send cancel events to all the input channels we're stealing from.
5067 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005068 "gesture monitor stole pointer stream");
Michael Wright3dd60e22019-03-27 22:06:44 +00005069 options.deviceId = deviceId;
5070 options.displayId = displayId;
5071 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005072 std::shared_ptr<InputChannel> channel =
5073 getInputChannelLocked(window.windowHandle->getToken());
Michael Wright3a240c42019-12-10 20:53:41 +00005074 if (channel != nullptr) {
5075 synthesizeCancelationEventsForInputChannelLocked(channel, options);
5076 }
Michael Wright3dd60e22019-03-27 22:06:44 +00005077 }
5078 // Then clear the current touch state so we stop dispatching to them as well.
5079 state.filterNonMonitors();
5080 }
5081 return OK;
5082}
5083
Prabir Pradhan99987712020-11-10 18:43:05 -08005084void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
5085 { // acquire lock
5086 std::scoped_lock _l(mLock);
5087 if (DEBUG_FOCUS) {
5088 const sp<InputWindowHandle> windowHandle = getWindowHandleLocked(windowToken);
5089 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
5090 windowHandle != nullptr ? windowHandle->getName().c_str()
5091 : "token without window");
5092 }
5093
5094 const sp<IBinder> focusedToken =
5095 getValueByKey(mFocusedWindowTokenByDisplay, mFocusedDisplayId);
5096 if (focusedToken != windowToken) {
5097 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
5098 enabled ? "enable" : "disable");
5099 return;
5100 }
5101
5102 if (enabled == mFocusedWindowRequestedPointerCapture) {
5103 ALOGW("Ignoring request to %s Pointer Capture: "
5104 "window has %s requested pointer capture.",
5105 enabled ? "enable" : "disable", enabled ? "already" : "not");
5106 return;
5107 }
5108
5109 mFocusedWindowRequestedPointerCapture = enabled;
5110 setPointerCaptureLocked(enabled);
5111 } // release lock
5112
5113 // Wake the thread to process command entries.
5114 mLooper->wake();
5115}
5116
Michael Wright3dd60e22019-03-27 22:06:44 +00005117std::optional<int32_t> InputDispatcher::findGestureMonitorDisplayByTokenLocked(
5118 const sp<IBinder>& token) {
5119 for (const auto& it : mGestureMonitorsByDisplay) {
5120 const std::vector<Monitor>& monitors = it.second;
5121 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005122 if (monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005123 return it.first;
5124 }
5125 }
5126 }
5127 return std::nullopt;
5128}
5129
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005130sp<Connection> InputDispatcher::getConnectionLocked(const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005131 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005132 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08005133 }
5134
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005135 for (const auto& pair : mConnectionsByFd) {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005136 const sp<Connection>& connection = pair.second;
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005137 if (connection->inputChannel->getConnectionToken() == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005138 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005139 }
5140 }
Robert Carr4e670e52018-08-15 13:26:12 -07005141
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005142 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005143}
5144
Siarhei Vishniakouad991402020-10-28 11:40:09 -05005145std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
5146 sp<Connection> connection = getConnectionLocked(connectionToken);
5147 if (connection == nullptr) {
5148 return "<nullptr>";
5149 }
5150 return connection->getInputChannelName();
5151}
5152
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005153void InputDispatcher::removeConnectionLocked(const sp<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005154 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005155 removeByValue(mConnectionsByFd, connection);
5156}
5157
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005158void InputDispatcher::onDispatchCycleFinishedLocked(nsecs_t currentTime,
5159 const sp<Connection>& connection, uint32_t seq,
5160 bool handled) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005161 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5162 &InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005163 commandEntry->connection = connection;
5164 commandEntry->eventTime = currentTime;
5165 commandEntry->seq = seq;
5166 commandEntry->handled = handled;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005167 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005168}
5169
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005170void InputDispatcher::onDispatchCycleBrokenLocked(nsecs_t currentTime,
5171 const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005172 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005173 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005174
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005175 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5176 &InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005177 commandEntry->connection = connection;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005178 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005179}
5180
Vishnu Nairad321cd2020-08-20 16:40:21 -07005181void InputDispatcher::notifyFocusChangedLocked(const sp<IBinder>& oldToken,
5182 const sp<IBinder>& newToken) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005183 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5184 &InputDispatcher::doNotifyFocusChangedLockedInterruptible);
chaviw0c06c6e2019-01-09 13:27:07 -08005185 commandEntry->oldToken = oldToken;
5186 commandEntry->newToken = newToken;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005187 postCommandLocked(std::move(commandEntry));
Robert Carrf759f162018-11-13 12:57:11 -08005188}
5189
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -05005190void InputDispatcher::onAnrLocked(const Connection& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005191 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
5192 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -05005193 if (connection.waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005194 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -05005195 connection.inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005196 return;
5197 }
5198 /**
5199 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
5200 * may not be the one that caused the timeout to occur. One possibility is that window timeout
5201 * has changed. This could cause newer entries to time out before the already dispatched
5202 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
5203 * processes the events linearly. So providing information about the oldest entry seems to be
5204 * most useful.
5205 */
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -05005206 DispatchEntry* oldestEntry = *connection.waitQueue.begin();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005207 const nsecs_t currentWait = now() - oldestEntry->deliveryTime;
5208 std::string reason =
5209 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -05005210 connection.inputChannel->getName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005211 ns2ms(currentWait),
5212 oldestEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06005213 sp<IBinder> connectionToken = connection.inputChannel->getConnectionToken();
5214 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005215
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005216 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5217 &InputDispatcher::doNotifyConnectionUnresponsiveLockedInterruptible);
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06005218 commandEntry->connectionToken = connectionToken;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005219 commandEntry->reason = std::move(reason);
5220 postCommandLocked(std::move(commandEntry));
5221}
5222
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005223void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
5224 std::string reason =
5225 StringPrintf("%s does not have a focused window", application->getName().c_str());
5226 updateLastAnrStateLocked(*application, reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005227
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005228 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5229 &InputDispatcher::doNotifyNoFocusedWindowAnrLockedInterruptible);
5230 commandEntry->inputApplicationHandle = std::move(application);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005231 postCommandLocked(std::move(commandEntry));
5232}
5233
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00005234void InputDispatcher::onUntrustedTouchLocked(const std::string& obscuringPackage) {
5235 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5236 &InputDispatcher::doNotifyUntrustedTouchLockedInterruptible);
5237 commandEntry->obscuringPackage = obscuringPackage;
5238 postCommandLocked(std::move(commandEntry));
5239}
5240
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005241void InputDispatcher::updateLastAnrStateLocked(const sp<InputWindowHandle>& window,
5242 const std::string& reason) {
5243 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
5244 updateLastAnrStateLocked(windowLabel, reason);
5245}
5246
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005247void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
5248 const std::string& reason) {
5249 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005250 updateLastAnrStateLocked(windowLabel, reason);
5251}
5252
5253void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
5254 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005255 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07005256 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005257 struct tm tm;
5258 localtime_r(&t, &tm);
5259 char timestr[64];
5260 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005261 mLastAnrState.clear();
5262 mLastAnrState += INDENT "ANR:\n";
5263 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005264 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
5265 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005266 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005267}
5268
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005269void InputDispatcher::doNotifyConfigurationChangedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005270 mLock.unlock();
5271
5272 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
5273
5274 mLock.lock();
5275}
5276
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005277void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005278 sp<Connection> connection = commandEntry->connection;
5279
5280 if (connection->status != Connection::STATUS_ZOMBIE) {
5281 mLock.unlock();
5282
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005283 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005284
5285 mLock.lock();
5286 }
5287}
5288
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005289void InputDispatcher::doNotifyFocusChangedLockedInterruptible(CommandEntry* commandEntry) {
chaviw0c06c6e2019-01-09 13:27:07 -08005290 sp<IBinder> oldToken = commandEntry->oldToken;
5291 sp<IBinder> newToken = commandEntry->newToken;
Robert Carrf759f162018-11-13 12:57:11 -08005292 mLock.unlock();
chaviw0c06c6e2019-01-09 13:27:07 -08005293 mPolicy->notifyFocusChanged(oldToken, newToken);
Robert Carrf759f162018-11-13 12:57:11 -08005294 mLock.lock();
5295}
5296
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005297void InputDispatcher::doNotifyNoFocusedWindowAnrLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005298 mLock.unlock();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005299
5300 mPolicy->notifyNoFocusedWindowAnr(commandEntry->inputApplicationHandle);
5301
5302 mLock.lock();
5303}
5304
5305void InputDispatcher::doNotifyConnectionUnresponsiveLockedInterruptible(
5306 CommandEntry* commandEntry) {
5307 mLock.unlock();
5308
5309 mPolicy->notifyConnectionUnresponsive(commandEntry->connectionToken, commandEntry->reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005310
5311 mLock.lock();
5312
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005313 // stop waking up for events in this connection, it is already not responding
5314 sp<Connection> connection = getConnectionLocked(commandEntry->connectionToken);
5315 if (connection == nullptr) {
5316 return;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005317 }
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005318 cancelEventsForAnrLocked(connection);
5319}
5320
5321void InputDispatcher::doNotifyConnectionResponsiveLockedInterruptible(CommandEntry* commandEntry) {
5322 mLock.unlock();
5323
5324 mPolicy->notifyConnectionResponsive(commandEntry->connectionToken);
5325
5326 mLock.lock();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005327}
5328
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00005329void InputDispatcher::doNotifyUntrustedTouchLockedInterruptible(CommandEntry* commandEntry) {
5330 mLock.unlock();
5331
5332 mPolicy->notifyUntrustedTouch(commandEntry->obscuringPackage);
5333
5334 mLock.lock();
5335}
5336
Michael Wrightd02c5b62014-02-10 15:10:22 -08005337void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
5338 CommandEntry* commandEntry) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005339 KeyEntry& entry = *(commandEntry->keyEntry);
5340 KeyEvent event = createKeyEvent(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005341
5342 mLock.unlock();
5343
Michael Wright2b3c3302018-03-02 17:19:13 +00005344 android::base::Timer t;
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06005345 const sp<IBinder>& token = commandEntry->connectionToken;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005346 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(token, &event, entry.policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00005347 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
5348 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005349 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00005350 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005351
5352 mLock.lock();
5353
5354 if (delay < 0) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005355 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005356 } else if (!delay) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005357 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005358 } else {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005359 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
5360 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005361 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005362}
5363
chaviwfd6d3512019-03-25 13:23:49 -07005364void InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible(CommandEntry* commandEntry) {
5365 mLock.unlock();
5366 mPolicy->onPointerDownOutsideFocus(commandEntry->newToken);
5367 mLock.lock();
5368}
5369
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005370/**
5371 * Connection is responsive if it has no events in the waitQueue that are older than the
5372 * current time.
5373 */
5374static bool isConnectionResponsive(const Connection& connection) {
5375 const nsecs_t currentTime = now();
5376 for (const DispatchEntry* entry : connection.waitQueue) {
5377 if (entry->timeoutTime < currentTime) {
5378 return false;
5379 }
5380 }
5381 return true;
5382}
5383
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005384void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005385 sp<Connection> connection = commandEntry->connection;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005386 const nsecs_t finishTime = commandEntry->eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005387 uint32_t seq = commandEntry->seq;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005388 const bool handled = commandEntry->handled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005389
5390 // Handle post-event policy actions.
Garfield Tane84e6f92019-08-29 17:28:41 -07005391 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005392 if (dispatchEntryIt == connection->waitQueue.end()) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005393 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005394 }
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005395 DispatchEntry* dispatchEntry = *dispatchEntryIt;
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07005396 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005397 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005398 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
5399 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005400 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07005401 reportDispatchStatistics(std::chrono::nanoseconds(eventDuration), *connection, handled);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005402
5403 bool restartEvent;
Siarhei Vishniakou49483272019-10-22 13:13:47 -07005404 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005405 KeyEntry& keyEntry = static_cast<KeyEntry&>(*(dispatchEntry->eventEntry));
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005406 restartEvent =
5407 afterKeyEventLockedInterruptible(connection, dispatchEntry, keyEntry, handled);
Siarhei Vishniakou49483272019-10-22 13:13:47 -07005408 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005409 MotionEntry& motionEntry = static_cast<MotionEntry&>(*(dispatchEntry->eventEntry));
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005410 restartEvent = afterMotionEventLockedInterruptible(connection, dispatchEntry, motionEntry,
5411 handled);
5412 } else {
5413 restartEvent = false;
5414 }
5415
5416 // Dequeue the event and start the next cycle.
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07005417 // Because the lock might have been released, it is possible that the
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005418 // contents of the wait queue to have been drained, so we need to double-check
5419 // a few things.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005420 dispatchEntryIt = connection->findWaitQueueEntry(seq);
5421 if (dispatchEntryIt != connection->waitQueue.end()) {
5422 dispatchEntry = *dispatchEntryIt;
5423 connection->waitQueue.erase(dispatchEntryIt);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005424 const sp<IBinder>& connectionToken = connection->inputChannel->getConnectionToken();
5425 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005426 if (!connection->responsive) {
5427 connection->responsive = isConnectionResponsive(*connection);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005428 if (connection->responsive) {
5429 // The connection was unresponsive, and now it's responsive. Tell the policy
5430 // about it so that it can stop ANR.
5431 std::unique_ptr<CommandEntry> connectionResponsiveCommand =
5432 std::make_unique<CommandEntry>(
5433 &InputDispatcher::doNotifyConnectionResponsiveLockedInterruptible);
5434 connectionResponsiveCommand->connectionToken = connectionToken;
5435 postCommandLocked(std::move(connectionResponsiveCommand));
5436 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005437 }
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005438 traceWaitQueueLength(connection);
5439 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005440 connection->outboundQueue.push_front(dispatchEntry);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005441 traceOutboundQueueLength(connection);
5442 } else {
5443 releaseDispatchEntry(dispatchEntry);
5444 }
5445 }
5446
5447 // Start the next dispatch cycle for this connection.
5448 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005449}
5450
5451bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005452 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005453 KeyEntry& keyEntry, bool handled) {
5454 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005455 if (!handled) {
5456 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005457 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005458 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005459 return false;
5460 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005461
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005462 // Get the fallback key state.
5463 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005464 int32_t originalKeyCode = keyEntry.keyCode;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005465 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005466 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005467 connection->inputState.removeFallbackKey(originalKeyCode);
5468 }
5469
5470 if (handled || !dispatchEntry->hasForegroundTarget()) {
5471 // If the application handles the original key for which we previously
5472 // generated a fallback or if the window is not a foreground window,
5473 // then cancel the associated fallback key, if any.
5474 if (fallbackKeyCode != -1) {
5475 // Dispatch the unhandled key to the policy with the cancel flag.
Michael Wrightd02c5b62014-02-10 15:10:22 -08005476#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005477 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005478 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005479 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005480#endif
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005481 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005482 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005483
5484 mLock.unlock();
5485
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005486 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005487 keyEntry.policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005488
5489 mLock.lock();
5490
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005491 // Cancel the fallback key.
5492 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005493 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005494 "application handled the original non-fallback key "
5495 "or is no longer a foreground target, "
5496 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005497 options.keyCode = fallbackKeyCode;
5498 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005499 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005500 connection->inputState.removeFallbackKey(originalKeyCode);
5501 }
5502 } else {
5503 // If the application did not handle a non-fallback key, first check
5504 // that we are in a good state to perform unhandled key event processing
5505 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005506 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005507 if (fallbackKeyCode == -1 && !initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005508#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005509 ALOGD("Unhandled key event: Skipping unhandled key event processing "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005510 "since this is not an initial down. "
5511 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005512 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005513#endif
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005514 return false;
5515 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005516
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005517 // Dispatch the unhandled key to the policy.
5518#if DEBUG_OUTBOUND_EVENT_DETAILS
5519 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005520 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005521 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005522#endif
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005523 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005524
5525 mLock.unlock();
5526
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005527 bool fallback =
5528 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005529 &event, keyEntry.policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005530
5531 mLock.lock();
5532
5533 if (connection->status != Connection::STATUS_NORMAL) {
5534 connection->inputState.removeFallbackKey(originalKeyCode);
5535 return false;
5536 }
5537
5538 // Latch the fallback keycode for this key on an initial down.
5539 // The fallback keycode cannot change at any other point in the lifecycle.
5540 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005541 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005542 fallbackKeyCode = event.getKeyCode();
5543 } else {
5544 fallbackKeyCode = AKEYCODE_UNKNOWN;
5545 }
5546 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
5547 }
5548
5549 ALOG_ASSERT(fallbackKeyCode != -1);
5550
5551 // Cancel the fallback key if the policy decides not to send it anymore.
5552 // We will continue to dispatch the key to the policy but we will no
5553 // longer dispatch a fallback key to the application.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005554 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
5555 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005556#if DEBUG_OUTBOUND_EVENT_DETAILS
5557 if (fallback) {
5558 ALOGD("Unhandled key event: Policy requested to send key %d"
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005559 "as a fallback for %d, but on the DOWN it had requested "
5560 "to send %d instead. Fallback canceled.",
5561 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005562 } else {
5563 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005564 "but on the DOWN it had requested to send %d. "
5565 "Fallback canceled.",
5566 originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005567 }
5568#endif
5569
5570 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
5571 "canceling fallback, policy no longer desires it");
5572 options.keyCode = fallbackKeyCode;
5573 synthesizeCancelationEventsForConnectionLocked(connection, options);
5574
5575 fallback = false;
5576 fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005577 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005578 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005579 }
5580 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005581
5582#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005583 {
5584 std::string msg;
5585 const KeyedVector<int32_t, int32_t>& fallbackKeys =
5586 connection->inputState.getFallbackKeys();
5587 for (size_t i = 0; i < fallbackKeys.size(); i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005588 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005589 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005590 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005591 fallbackKeys.size(), msg.c_str());
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005592 }
5593#endif
5594
5595 if (fallback) {
5596 // Restart the dispatch cycle using the fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005597 keyEntry.eventTime = event.getEventTime();
5598 keyEntry.deviceId = event.getDeviceId();
5599 keyEntry.source = event.getSource();
5600 keyEntry.displayId = event.getDisplayId();
5601 keyEntry.flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
5602 keyEntry.keyCode = fallbackKeyCode;
5603 keyEntry.scanCode = event.getScanCode();
5604 keyEntry.metaState = event.getMetaState();
5605 keyEntry.repeatCount = event.getRepeatCount();
5606 keyEntry.downTime = event.getDownTime();
5607 keyEntry.syntheticRepeat = false;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005608
5609#if DEBUG_OUTBOUND_EVENT_DETAILS
5610 ALOGD("Unhandled key event: Dispatching fallback key. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005611 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005612 originalKeyCode, fallbackKeyCode, keyEntry.metaState);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005613#endif
5614 return true; // restart the event
5615 } else {
5616#if DEBUG_OUTBOUND_EVENT_DETAILS
5617 ALOGD("Unhandled key event: No fallback key.");
5618#endif
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005619
5620 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005621 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005622 }
5623 }
5624 return false;
5625}
5626
5627bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005628 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005629 MotionEntry& motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005630 return false;
5631}
5632
5633void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
5634 mLock.unlock();
5635
5636 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType);
5637
5638 mLock.lock();
5639}
5640
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07005641KeyEvent InputDispatcher::createKeyEvent(const KeyEntry& entry) {
5642 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08005643 event.initialize(entry.id, entry.deviceId, entry.source, entry.displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08005644 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
5645 entry.repeatCount, entry.downTime, entry.eventTime);
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07005646 return event;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005647}
5648
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07005649void InputDispatcher::reportDispatchStatistics(std::chrono::nanoseconds eventDuration,
5650 const Connection& connection, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005651 // TODO Write some statistics about how long we spend waiting.
5652}
5653
Siarhei Vishniakoude4bf152019-08-16 11:12:52 -05005654/**
5655 * Report the touch event latency to the statsd server.
5656 * Input events are reported for statistics if:
5657 * - This is a touchscreen event
5658 * - InputFilter is not enabled
5659 * - Event is not injected or synthesized
5660 *
5661 * Statistics should be reported before calling addValue, to prevent a fresh new sample
5662 * from getting aggregated with the "old" data.
5663 */
5664void InputDispatcher::reportTouchEventForStatistics(const MotionEntry& motionEntry)
5665 REQUIRES(mLock) {
5666 const bool reportForStatistics = (motionEntry.source == AINPUT_SOURCE_TOUCHSCREEN) &&
5667 !(motionEntry.isSynthesized()) && !mInputFilterEnabled;
5668 if (!reportForStatistics) {
5669 return;
5670 }
5671
5672 if (mTouchStatistics.shouldReport()) {
5673 android::util::stats_write(android::util::TOUCH_EVENT_REPORTED, mTouchStatistics.getMin(),
5674 mTouchStatistics.getMax(), mTouchStatistics.getMean(),
5675 mTouchStatistics.getStDev(), mTouchStatistics.getCount());
5676 mTouchStatistics.reset();
5677 }
5678 const float latencyMicros = nanoseconds_to_microseconds(now() - motionEntry.eventTime);
5679 mTouchStatistics.addValue(latencyMicros);
5680}
5681
Michael Wrightd02c5b62014-02-10 15:10:22 -08005682void InputDispatcher::traceInboundQueueLengthLocked() {
5683 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005684 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005685 }
5686}
5687
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08005688void InputDispatcher::traceOutboundQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005689 if (ATRACE_ENABLED()) {
5690 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08005691 snprintf(counterName, sizeof(counterName), "oq:%s", connection->getWindowName().c_str());
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005692 ATRACE_INT(counterName, connection->outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005693 }
5694}
5695
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08005696void InputDispatcher::traceWaitQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005697 if (ATRACE_ENABLED()) {
5698 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08005699 snprintf(counterName, sizeof(counterName), "wq:%s", connection->getWindowName().c_str());
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005700 ATRACE_INT(counterName, connection->waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005701 }
5702}
5703
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005704void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005705 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005706
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005707 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005708 dumpDispatchStateLocked(dump);
5709
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005710 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005711 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005712 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005713 }
5714}
5715
5716void InputDispatcher::monitor() {
5717 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005718 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005719 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005720 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005721}
5722
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08005723/**
5724 * Wake up the dispatcher and wait until it processes all events and commands.
5725 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
5726 * this method can be safely called from any thread, as long as you've ensured that
5727 * the work you are interested in completing has already been queued.
5728 */
5729bool InputDispatcher::waitForIdle() {
5730 /**
5731 * Timeout should represent the longest possible time that a device might spend processing
5732 * events and commands.
5733 */
5734 constexpr std::chrono::duration TIMEOUT = 100ms;
5735 std::unique_lock lock(mLock);
5736 mLooper->wake();
5737 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
5738 return result == std::cv_status::no_timeout;
5739}
5740
Vishnu Naire798b472020-07-23 13:52:21 -07005741/**
5742 * Sets focus to the window identified by the token. This must be called
5743 * after updating any input window handles.
5744 *
5745 * Params:
5746 * request.token - input channel token used to identify the window that should gain focus.
5747 * request.focusedToken - the token that the caller expects currently to be focused. If the
5748 * specified token does not match the currently focused window, this request will be dropped.
5749 * If the specified focused token matches the currently focused window, the call will succeed.
5750 * Set this to "null" if this call should succeed no matter what the currently focused token is.
5751 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
5752 * when requesting the focus change. This determines which request gets
5753 * precedence if there is a focus change request from another source such as pointer down.
5754 */
Vishnu Nair958da932020-08-21 17:12:37 -07005755void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
5756 { // acquire lock
5757 std::scoped_lock _l(mLock);
5758
5759 const int32_t displayId = request.displayId;
5760 const sp<IBinder> oldFocusedToken = getValueByKey(mFocusedWindowTokenByDisplay, displayId);
5761 if (request.focusedToken && oldFocusedToken != request.focusedToken) {
5762 ALOGD_IF(DEBUG_FOCUS,
5763 "setFocusedWindow on display %" PRId32
5764 " ignored, reason: focusedToken is not focused",
5765 displayId);
5766 return;
5767 }
5768
5769 mPendingFocusRequests.erase(displayId);
5770 FocusResult result = handleFocusRequestLocked(request);
5771 if (result == FocusResult::NOT_VISIBLE) {
5772 // The requested window is not currently visible. Wait for the window to become visible
5773 // and then provide it focus. This is to handle situations where a user action triggers
5774 // a new window to appear. We want to be able to queue any key events after the user
5775 // action and deliver it to the newly focused window. In order for this to happen, we
5776 // take focus from the currently focused window so key events can be queued.
5777 ALOGD_IF(DEBUG_FOCUS,
5778 "setFocusedWindow on display %" PRId32
5779 " pending, reason: window is not visible",
5780 displayId);
5781 mPendingFocusRequests[displayId] = request;
5782 onFocusChangedLocked(oldFocusedToken, nullptr, displayId,
5783 "setFocusedWindow_AwaitingWindowVisibility");
5784 } else if (result != FocusResult::OK) {
5785 ALOGW("setFocusedWindow on display %" PRId32 " ignored, reason:%s", displayId,
5786 typeToString(result));
5787 }
5788 } // release lock
5789 // Wake up poll loop since it may need to make new input dispatching choices.
5790 mLooper->wake();
5791}
5792
5793InputDispatcher::FocusResult InputDispatcher::handleFocusRequestLocked(
5794 const FocusRequest& request) {
5795 const int32_t displayId = request.displayId;
5796 const sp<IBinder> newFocusedToken = request.token;
5797 const sp<IBinder> oldFocusedToken = getValueByKey(mFocusedWindowTokenByDisplay, displayId);
5798
5799 if (oldFocusedToken == request.token) {
5800 ALOGD_IF(DEBUG_FOCUS,
5801 "setFocusedWindow on display %" PRId32 " ignored, reason: already focused",
5802 displayId);
5803 return FocusResult::OK;
5804 }
5805
5806 FocusResult result = checkTokenFocusableLocked(newFocusedToken, displayId);
5807 if (result != FocusResult::OK) {
5808 return result;
5809 }
5810
5811 std::string_view reason =
5812 (request.focusedToken) ? "setFocusedWindow_FocusCheck" : "setFocusedWindow";
5813 onFocusChangedLocked(oldFocusedToken, newFocusedToken, displayId, reason);
5814 return FocusResult::OK;
5815}
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005816
Vishnu Nairad321cd2020-08-20 16:40:21 -07005817void InputDispatcher::onFocusChangedLocked(const sp<IBinder>& oldFocusedToken,
5818 const sp<IBinder>& newFocusedToken, int32_t displayId,
5819 std::string_view reason) {
5820 if (oldFocusedToken) {
5821 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(oldFocusedToken);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005822 if (focusedInputChannel) {
5823 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
5824 "focus left window");
5825 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Vishnu Nairad321cd2020-08-20 16:40:21 -07005826 enqueueFocusEventLocked(oldFocusedToken, false /*hasFocus*/, reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005827 }
Vishnu Nairad321cd2020-08-20 16:40:21 -07005828 mFocusedWindowTokenByDisplay.erase(displayId);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005829 }
Vishnu Nairad321cd2020-08-20 16:40:21 -07005830 if (newFocusedToken) {
5831 mFocusedWindowTokenByDisplay[displayId] = newFocusedToken;
5832 enqueueFocusEventLocked(newFocusedToken, true /*hasFocus*/, reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005833 }
5834
Prabir Pradhan99987712020-11-10 18:43:05 -08005835 // If a window has pointer capture, then it must have focus. We need to ensure that this
5836 // contract is upheld when pointer capture is being disabled due to a loss of window focus.
5837 // If the window loses focus before it loses pointer capture, then the window can be in a state
5838 // where it has pointer capture but not focus, violating the contract. Therefore we must
5839 // dispatch the pointer capture event before the focus event. Since focus events are added to
5840 // the front of the queue (above), we add the pointer capture event to the front of the queue
5841 // after the focus events are added. This ensures the pointer capture event ends up at the
5842 // front.
5843 disablePointerCaptureForcedLocked();
5844
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005845 if (mFocusedDisplayId == displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005846 notifyFocusChangedLocked(oldFocusedToken, newFocusedToken);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005847 }
5848}
Vishnu Nair958da932020-08-21 17:12:37 -07005849
Prabir Pradhan99987712020-11-10 18:43:05 -08005850void InputDispatcher::disablePointerCaptureForcedLocked() {
5851 if (!mFocusedWindowRequestedPointerCapture && !mWindowTokenWithPointerCapture) {
5852 return;
5853 }
5854
5855 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
5856
5857 if (mFocusedWindowRequestedPointerCapture) {
5858 mFocusedWindowRequestedPointerCapture = false;
5859 setPointerCaptureLocked(false);
5860 }
5861
5862 if (!mWindowTokenWithPointerCapture) {
5863 // No need to send capture changes because no window has capture.
5864 return;
5865 }
5866
5867 if (mPendingEvent != nullptr) {
5868 // Move the pending event to the front of the queue. This will give the chance
5869 // for the pending event to be dropped if it is a captured event.
5870 mInboundQueue.push_front(mPendingEvent);
5871 mPendingEvent = nullptr;
5872 }
5873
5874 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
5875 false /* hasCapture */);
5876 mInboundQueue.push_front(std::move(entry));
5877}
5878
Vishnu Nair958da932020-08-21 17:12:37 -07005879/**
5880 * Checks if the window token can be focused on a display. The token can be focused if there is
5881 * at least one window handle that is visible with the same token and all window handles with the
5882 * same token are focusable.
5883 *
5884 * In the case of mirroring, two windows may share the same window token and their visibility
5885 * might be different. Example, the mirrored window can cover the window its mirroring. However,
5886 * we expect the focusability of the windows to match since its hard to reason why one window can
5887 * receive focus events and the other cannot when both are backed by the same input channel.
5888 */
5889InputDispatcher::FocusResult InputDispatcher::checkTokenFocusableLocked(const sp<IBinder>& token,
5890 int32_t displayId) const {
5891 bool allWindowsAreFocusable = true;
5892 bool visibleWindowFound = false;
5893 bool windowFound = false;
5894 for (const sp<InputWindowHandle>& window : getWindowHandlesLocked(displayId)) {
5895 if (window->getToken() != token) {
5896 continue;
5897 }
5898 windowFound = true;
5899 if (window->getInfo()->visible) {
5900 // Check if at least a single window is visible.
5901 visibleWindowFound = true;
5902 }
5903 if (!window->getInfo()->focusable) {
5904 // Check if all windows with the window token are focusable.
5905 allWindowsAreFocusable = false;
5906 break;
5907 }
5908 }
5909
5910 if (!windowFound) {
5911 return FocusResult::NO_WINDOW;
5912 }
5913 if (!allWindowsAreFocusable) {
5914 return FocusResult::NOT_FOCUSABLE;
5915 }
5916 if (!visibleWindowFound) {
5917 return FocusResult::NOT_VISIBLE;
5918 }
5919
5920 return FocusResult::OK;
5921}
Prabir Pradhan99987712020-11-10 18:43:05 -08005922
5923void InputDispatcher::setPointerCaptureLocked(bool enabled) {
5924 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5925 &InputDispatcher::doSetPointerCaptureLockedInterruptible);
5926 commandEntry->enabled = enabled;
5927 postCommandLocked(std::move(commandEntry));
5928}
5929
5930void InputDispatcher::doSetPointerCaptureLockedInterruptible(
5931 android::inputdispatcher::CommandEntry* commandEntry) {
5932 mLock.unlock();
5933
5934 mPolicy->setPointerCapture(commandEntry->enabled);
5935
5936 mLock.lock();
5937}
5938
Garfield Tane84e6f92019-08-29 17:28:41 -07005939} // namespace android::inputdispatcher