blob: 0122fb0375842047f544d87a3ac77f48f83a667d [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
arthurhungea3f4fc2020-12-21 23:18:53 +08003417 : (originalMotionEntry.flags & AMOTION_EVENT_FLAG_CANCELED) != 0
3418 ? AMOTION_EVENT_ACTION_CANCEL
3419 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003420 } else {
3421 // A secondary pointer went down/up.
3422 uint32_t splitPointerIndex = 0;
3423 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
3424 splitPointerIndex += 1;
3425 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003426 action = maskedAction |
3427 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003428 }
3429 } else {
3430 // An unrelated pointer changed.
3431 action = AMOTION_EVENT_ACTION_MOVE;
3432 }
3433 }
3434
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003435 int32_t newId = mIdGenerator.nextId();
3436 if (ATRACE_ENABLED()) {
3437 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
3438 ") to MotionEvent(id=0x%" PRIx32 ").",
3439 originalMotionEntry.id, newId);
3440 ATRACE_NAME(message.c_str());
3441 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003442 std::unique_ptr<MotionEntry> splitMotionEntry =
3443 std::make_unique<MotionEntry>(newId, originalMotionEntry.eventTime,
3444 originalMotionEntry.deviceId, originalMotionEntry.source,
3445 originalMotionEntry.displayId,
3446 originalMotionEntry.policyFlags, action,
3447 originalMotionEntry.actionButton,
3448 originalMotionEntry.flags, originalMotionEntry.metaState,
3449 originalMotionEntry.buttonState,
3450 originalMotionEntry.classification,
3451 originalMotionEntry.edgeFlags,
3452 originalMotionEntry.xPrecision,
3453 originalMotionEntry.yPrecision,
3454 originalMotionEntry.xCursorPosition,
3455 originalMotionEntry.yCursorPosition,
3456 originalMotionEntry.downTime, splitPointerCount,
3457 splitPointerProperties, splitPointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003458
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003459 if (originalMotionEntry.injectionState) {
3460 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003461 splitMotionEntry->injectionState->refCount += 1;
3462 }
3463
3464 return splitMotionEntry;
3465}
3466
3467void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
3468#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003469 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003470#endif
3471
3472 bool needWake;
3473 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003474 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003475
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003476 std::unique_ptr<ConfigurationChangedEntry> newEntry =
3477 std::make_unique<ConfigurationChangedEntry>(args->id, args->eventTime);
3478 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003479 } // release lock
3480
3481 if (needWake) {
3482 mLooper->wake();
3483 }
3484}
3485
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003486/**
3487 * If one of the meta shortcuts is detected, process them here:
3488 * Meta + Backspace -> generate BACK
3489 * Meta + Enter -> generate HOME
3490 * This will potentially overwrite keyCode and metaState.
3491 */
3492void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003493 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003494 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
3495 int32_t newKeyCode = AKEYCODE_UNKNOWN;
3496 if (keyCode == AKEYCODE_DEL) {
3497 newKeyCode = AKEYCODE_BACK;
3498 } else if (keyCode == AKEYCODE_ENTER) {
3499 newKeyCode = AKEYCODE_HOME;
3500 }
3501 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003502 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003503 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003504 mReplacedKeys[replacement] = newKeyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003505 keyCode = newKeyCode;
3506 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3507 }
3508 } else if (action == AKEY_EVENT_ACTION_UP) {
3509 // In order to maintain a consistent stream of up and down events, check to see if the key
3510 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
3511 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003512 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003513 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003514 auto replacementIt = mReplacedKeys.find(replacement);
3515 if (replacementIt != mReplacedKeys.end()) {
3516 keyCode = replacementIt->second;
3517 mReplacedKeys.erase(replacementIt);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003518 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3519 }
3520 }
3521}
3522
Michael Wrightd02c5b62014-02-10 15:10:22 -08003523void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
3524#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003525 ALOGD("notifyKey - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
3526 "policyFlags=0x%x, action=0x%x, "
3527 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
3528 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
3529 args->action, args->flags, args->keyCode, args->scanCode, args->metaState,
3530 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003531#endif
3532 if (!validateKeyEvent(args->action)) {
3533 return;
3534 }
3535
3536 uint32_t policyFlags = args->policyFlags;
3537 int32_t flags = args->flags;
3538 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07003539 // InputDispatcher tracks and generates key repeats on behalf of
3540 // whatever notifies it, so repeatCount should always be set to 0
3541 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003542 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
3543 policyFlags |= POLICY_FLAG_VIRTUAL;
3544 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
3545 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003546 if (policyFlags & POLICY_FLAG_FUNCTION) {
3547 metaState |= AMETA_FUNCTION_ON;
3548 }
3549
3550 policyFlags |= POLICY_FLAG_TRUSTED;
3551
Michael Wright78f24442014-08-06 15:55:28 -07003552 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003553 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07003554
Michael Wrightd02c5b62014-02-10 15:10:22 -08003555 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003556 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08003557 args->action, flags, keyCode, args->scanCode, metaState, repeatCount,
3558 args->downTime, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003559
Michael Wright2b3c3302018-03-02 17:19:13 +00003560 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003561 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003562 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3563 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003564 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003565 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003566
Michael Wrightd02c5b62014-02-10 15:10:22 -08003567 bool needWake;
3568 { // acquire lock
3569 mLock.lock();
3570
3571 if (shouldSendKeyToInputFilterLocked(args)) {
3572 mLock.unlock();
3573
3574 policyFlags |= POLICY_FLAG_FILTERED;
3575 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3576 return; // event was consumed by the filter
3577 }
3578
3579 mLock.lock();
3580 }
3581
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003582 std::unique_ptr<KeyEntry> newEntry =
3583 std::make_unique<KeyEntry>(args->id, args->eventTime, args->deviceId, args->source,
3584 args->displayId, policyFlags, args->action, flags,
3585 keyCode, args->scanCode, metaState, repeatCount,
3586 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003587
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003588 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003589 mLock.unlock();
3590 } // release lock
3591
3592 if (needWake) {
3593 mLooper->wake();
3594 }
3595}
3596
3597bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
3598 return mInputFilterEnabled;
3599}
3600
3601void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
3602#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003603 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
3604 "displayId=%" PRId32 ", policyFlags=0x%x, "
Garfield Tan00f511d2019-06-12 16:55:40 -07003605 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
3606 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
Garfield Tanab0ab9c2019-07-10 18:58:28 -07003607 "yCursorPosition=%f, downTime=%" PRId64,
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003608 args->id, args->eventTime, args->deviceId, args->source, args->displayId,
3609 args->policyFlags, args->action, args->actionButton, args->flags, args->metaState,
3610 args->buttonState, args->edgeFlags, args->xPrecision, args->yPrecision,
3611 args->xCursorPosition, args->yCursorPosition, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003612 for (uint32_t i = 0; i < args->pointerCount; i++) {
3613 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003614 "x=%f, y=%f, pressure=%f, size=%f, "
3615 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
3616 "orientation=%f",
3617 i, args->pointerProperties[i].id, args->pointerProperties[i].toolType,
3618 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
3619 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
3620 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
3621 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
3622 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
3623 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
3624 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
3625 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
3626 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003627 }
3628#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003629 if (!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
3630 args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003631 return;
3632 }
3633
3634 uint32_t policyFlags = args->policyFlags;
3635 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003636
3637 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08003638 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003639 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3640 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003641 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003642 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003643
3644 bool needWake;
3645 { // acquire lock
3646 mLock.lock();
3647
3648 if (shouldSendMotionToInputFilterLocked(args)) {
3649 mLock.unlock();
3650
3651 MotionEvent event;
chaviw9eaa22c2020-07-01 16:21:27 -07003652 ui::Transform transform;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003653 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
3654 args->action, args->actionButton, args->flags, args->edgeFlags,
chaviw9eaa22c2020-07-01 16:21:27 -07003655 args->metaState, args->buttonState, args->classification, transform,
3656 args->xPrecision, args->yPrecision, args->xCursorPosition,
3657 args->yCursorPosition, args->downTime, args->eventTime,
3658 args->pointerCount, args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003659
3660 policyFlags |= POLICY_FLAG_FILTERED;
3661 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3662 return; // event was consumed by the filter
3663 }
3664
3665 mLock.lock();
3666 }
3667
3668 // Just enqueue a new motion event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003669 std::unique_ptr<MotionEntry> newEntry =
3670 std::make_unique<MotionEntry>(args->id, args->eventTime, args->deviceId,
3671 args->source, args->displayId, policyFlags,
3672 args->action, args->actionButton, args->flags,
3673 args->metaState, args->buttonState,
3674 args->classification, args->edgeFlags,
3675 args->xPrecision, args->yPrecision,
3676 args->xCursorPosition, args->yCursorPosition,
3677 args->downTime, args->pointerCount,
3678 args->pointerProperties, args->pointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003679
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003680 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003681 mLock.unlock();
3682 } // release lock
3683
3684 if (needWake) {
3685 mLooper->wake();
3686 }
3687}
3688
Chris Yef59a2f42020-10-16 12:55:26 -07003689void InputDispatcher::notifySensor(const NotifySensorArgs* args) {
3690#if DEBUG_INBOUND_EVENT_DETAILS
3691 ALOGD("notifySensor - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
3692 " sensorType=%s",
3693 args->id, args->eventTime, args->deviceId, args->source,
3694 NamedEnum::string(args->sensorType).c_str());
3695#endif
3696
3697 bool needWake;
3698 { // acquire lock
3699 mLock.lock();
3700
3701 // Just enqueue a new sensor event.
3702 std::unique_ptr<SensorEntry> newEntry =
3703 std::make_unique<SensorEntry>(args->id, args->eventTime, args->deviceId,
3704 args->source, 0 /* policyFlags*/, args->hwTimestamp,
3705 args->sensorType, args->accuracy,
3706 args->accuracyChanged, args->values);
3707
3708 needWake = enqueueInboundEventLocked(std::move(newEntry));
3709 mLock.unlock();
3710 } // release lock
3711
3712 if (needWake) {
3713 mLooper->wake();
3714 }
3715}
3716
Michael Wrightd02c5b62014-02-10 15:10:22 -08003717bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08003718 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003719}
3720
3721void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
3722#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003723 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003724 "switchMask=0x%08x",
3725 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003726#endif
3727
3728 uint32_t policyFlags = args->policyFlags;
3729 policyFlags |= POLICY_FLAG_TRUSTED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003730 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003731}
3732
3733void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
3734#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003735 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
3736 args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003737#endif
3738
3739 bool needWake;
3740 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003741 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003742
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003743 std::unique_ptr<DeviceResetEntry> newEntry =
3744 std::make_unique<DeviceResetEntry>(args->id, args->eventTime, args->deviceId);
3745 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003746 } // release lock
3747
3748 if (needWake) {
3749 mLooper->wake();
3750 }
3751}
3752
Prabir Pradhan7e186182020-11-10 13:56:45 -08003753void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs* args) {
3754#if DEBUG_INBOUND_EVENT_DETAILS
3755 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args->eventTime,
3756 args->enabled ? "true" : "false");
3757#endif
3758
Prabir Pradhan99987712020-11-10 18:43:05 -08003759 bool needWake;
3760 { // acquire lock
3761 std::scoped_lock _l(mLock);
3762 auto entry = std::make_unique<PointerCaptureChangedEntry>(args->id, args->eventTime,
3763 args->enabled);
3764 needWake = enqueueInboundEventLocked(std::move(entry));
3765 } // release lock
3766
3767 if (needWake) {
3768 mLooper->wake();
3769 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08003770}
3771
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003772InputEventInjectionResult InputDispatcher::injectInputEvent(
3773 const InputEvent* event, int32_t injectorPid, int32_t injectorUid,
3774 InputEventInjectionSync syncMode, std::chrono::milliseconds timeout, uint32_t policyFlags) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003775#if DEBUG_INBOUND_EVENT_DETAILS
3776 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003777 "syncMode=%d, timeout=%lld, policyFlags=0x%08x",
3778 event->getType(), injectorPid, injectorUid, syncMode, timeout.count(), policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003779#endif
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003780 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003781
3782 policyFlags |= POLICY_FLAG_INJECTED;
3783 if (hasInjectionPermission(injectorPid, injectorUid)) {
3784 policyFlags |= POLICY_FLAG_TRUSTED;
3785 }
3786
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003787 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003788 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003789 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003790 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
3791 int32_t action = incomingKey.getAction();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003792 if (!validateKeyEvent(action)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003793 return InputEventInjectionResult::FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003794 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003795
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003796 int32_t flags = incomingKey.getFlags();
3797 int32_t keyCode = incomingKey.getKeyCode();
3798 int32_t metaState = incomingKey.getMetaState();
3799 accelerateMetaShortcuts(VIRTUAL_KEYBOARD_ID, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003800 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003801 KeyEvent keyEvent;
Garfield Tan4cc839f2020-01-24 11:26:14 -08003802 keyEvent.initialize(incomingKey.getId(), VIRTUAL_KEYBOARD_ID, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003803 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
3804 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
3805 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003806
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003807 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
3808 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00003809 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003810
3811 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
3812 android::base::Timer t;
3813 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
3814 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3815 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
3816 std::to_string(t.duration().count()).c_str());
3817 }
3818 }
3819
3820 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003821 std::unique_ptr<KeyEntry> injectedEntry =
3822 std::make_unique<KeyEntry>(incomingKey.getId(), incomingKey.getEventTime(),
3823 VIRTUAL_KEYBOARD_ID, incomingKey.getSource(),
3824 incomingKey.getDisplayId(), policyFlags, action,
3825 flags, keyCode, incomingKey.getScanCode(), metaState,
3826 incomingKey.getRepeatCount(),
3827 incomingKey.getDownTime());
3828 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003829 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003830 }
3831
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003832 case AINPUT_EVENT_TYPE_MOTION: {
3833 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
3834 int32_t action = motionEvent->getAction();
3835 size_t pointerCount = motionEvent->getPointerCount();
3836 const PointerProperties* pointerProperties = motionEvent->getPointerProperties();
3837 int32_t actionButton = motionEvent->getActionButton();
3838 int32_t displayId = motionEvent->getDisplayId();
3839 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003840 return InputEventInjectionResult::FAILED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003841 }
3842
3843 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
3844 nsecs_t eventTime = motionEvent->getEventTime();
3845 android::base::Timer t;
3846 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
3847 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3848 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
3849 std::to_string(t.duration().count()).c_str());
3850 }
3851 }
3852
3853 mLock.lock();
3854 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
3855 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003856 std::unique_ptr<MotionEntry> injectedEntry =
3857 std::make_unique<MotionEntry>(motionEvent->getId(), *sampleEventTimes,
3858 VIRTUAL_KEYBOARD_ID, motionEvent->getSource(),
3859 motionEvent->getDisplayId(), policyFlags, action,
3860 actionButton, motionEvent->getFlags(),
3861 motionEvent->getMetaState(),
3862 motionEvent->getButtonState(),
3863 motionEvent->getClassification(),
3864 motionEvent->getEdgeFlags(),
3865 motionEvent->getXPrecision(),
3866 motionEvent->getYPrecision(),
3867 motionEvent->getRawXCursorPosition(),
3868 motionEvent->getRawYCursorPosition(),
3869 motionEvent->getDownTime(),
3870 uint32_t(pointerCount), pointerProperties,
3871 samplePointerCoords, motionEvent->getXOffset(),
3872 motionEvent->getYOffset());
3873 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003874 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
3875 sampleEventTimes += 1;
3876 samplePointerCoords += pointerCount;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003877 std::unique_ptr<MotionEntry> nextInjectedEntry =
3878 std::make_unique<MotionEntry>(motionEvent->getId(), *sampleEventTimes,
3879 VIRTUAL_KEYBOARD_ID, motionEvent->getSource(),
3880 motionEvent->getDisplayId(), policyFlags,
3881 action, actionButton, motionEvent->getFlags(),
3882 motionEvent->getMetaState(),
3883 motionEvent->getButtonState(),
3884 motionEvent->getClassification(),
3885 motionEvent->getEdgeFlags(),
3886 motionEvent->getXPrecision(),
3887 motionEvent->getYPrecision(),
3888 motionEvent->getRawXCursorPosition(),
3889 motionEvent->getRawYCursorPosition(),
3890 motionEvent->getDownTime(),
3891 uint32_t(pointerCount), pointerProperties,
3892 samplePointerCoords,
3893 motionEvent->getXOffset(),
3894 motionEvent->getYOffset());
3895 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003896 }
3897 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003898 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003899
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003900 default:
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08003901 ALOGW("Cannot inject %s events", inputEventTypeToString(event->getType()));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003902 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003903 }
3904
3905 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003906 if (syncMode == InputEventInjectionSync::NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003907 injectionState->injectionIsAsync = true;
3908 }
3909
3910 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003911 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003912
3913 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003914 while (!injectedEntries.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003915 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003916 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003917 }
3918
3919 mLock.unlock();
3920
3921 if (needWake) {
3922 mLooper->wake();
3923 }
3924
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003925 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003926 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003927 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003928
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003929 if (syncMode == InputEventInjectionSync::NONE) {
3930 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003931 } else {
3932 for (;;) {
3933 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003934 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003935 break;
3936 }
3937
3938 nsecs_t remainingTimeout = endTime - now();
3939 if (remainingTimeout <= 0) {
3940#if DEBUG_INJECTION
3941 ALOGD("injectInputEvent - Timed out waiting for injection result "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003942 "to become available.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003943#endif
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003944 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003945 break;
3946 }
3947
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003948 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003949 }
3950
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003951 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
3952 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003953 while (injectionState->pendingForegroundDispatches != 0) {
3954#if DEBUG_INJECTION
3955 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003956 injectionState->pendingForegroundDispatches);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003957#endif
3958 nsecs_t remainingTimeout = endTime - now();
3959 if (remainingTimeout <= 0) {
3960#if DEBUG_INJECTION
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003961 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
3962 "dispatches to finish.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003963#endif
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003964 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003965 break;
3966 }
3967
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003968 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003969 }
3970 }
3971 }
3972
3973 injectionState->release();
3974 } // release lock
3975
3976#if DEBUG_INJECTION
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003977 ALOGD("injectInputEvent - Finished with result %d. injectorPid=%d, injectorUid=%d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003978 injectionResult, injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003979#endif
3980
3981 return injectionResult;
3982}
3983
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08003984std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05003985 std::array<uint8_t, 32> calculatedHmac;
3986 std::unique_ptr<VerifiedInputEvent> result;
3987 switch (event.getType()) {
3988 case AINPUT_EVENT_TYPE_KEY: {
3989 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
3990 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
3991 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07003992 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05003993 break;
3994 }
3995 case AINPUT_EVENT_TYPE_MOTION: {
3996 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
3997 VerifiedMotionEvent verifiedMotionEvent =
3998 verifiedMotionEventFromMotionEvent(motionEvent);
3999 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004000 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05004001 break;
4002 }
4003 default: {
4004 ALOGE("Cannot verify events of type %" PRId32, event.getType());
4005 return nullptr;
4006 }
4007 }
4008 if (calculatedHmac == INVALID_HMAC) {
4009 return nullptr;
4010 }
4011 if (calculatedHmac != event.getHmac()) {
4012 return nullptr;
4013 }
4014 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004015}
4016
Michael Wrightd02c5b62014-02-10 15:10:22 -08004017bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004018 return injectorUid == 0 ||
4019 mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004020}
4021
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004022void InputDispatcher::setInjectionResult(EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004023 InputEventInjectionResult injectionResult) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004024 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004025 if (injectionState) {
4026#if DEBUG_INJECTION
4027 ALOGD("Setting input event injection result to %d. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004028 "injectorPid=%d, injectorUid=%d",
4029 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004030#endif
4031
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004032 if (injectionState->injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004033 // Log the outcome since the injector did not wait for the injection result.
4034 switch (injectionResult) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004035 case InputEventInjectionResult::SUCCEEDED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004036 ALOGV("Asynchronous input event injection succeeded.");
4037 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004038 case InputEventInjectionResult::FAILED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004039 ALOGW("Asynchronous input event injection failed.");
4040 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004041 case InputEventInjectionResult::PERMISSION_DENIED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004042 ALOGW("Asynchronous input event injection permission denied.");
4043 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004044 case InputEventInjectionResult::TIMED_OUT:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004045 ALOGW("Asynchronous input event injection timed out.");
4046 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004047 case InputEventInjectionResult::PENDING:
4048 ALOGE("Setting result to 'PENDING' for asynchronous injection");
4049 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004050 }
4051 }
4052
4053 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004054 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004055 }
4056}
4057
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004058void InputDispatcher::incrementPendingForegroundDispatches(EventEntry& entry) {
4059 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004060 if (injectionState) {
4061 injectionState->pendingForegroundDispatches += 1;
4062 }
4063}
4064
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004065void InputDispatcher::decrementPendingForegroundDispatches(EventEntry& entry) {
4066 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004067 if (injectionState) {
4068 injectionState->pendingForegroundDispatches -= 1;
4069
4070 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004071 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004072 }
4073 }
4074}
4075
Vishnu Nairad321cd2020-08-20 16:40:21 -07004076const std::vector<sp<InputWindowHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004077 int32_t displayId) const {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004078 static const std::vector<sp<InputWindowHandle>> EMPTY_WINDOW_HANDLES;
4079 auto it = mWindowHandlesByDisplay.find(displayId);
4080 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08004081}
4082
Michael Wrightd02c5b62014-02-10 15:10:22 -08004083sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08004084 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08004085 if (windowHandleToken == nullptr) {
4086 return nullptr;
4087 }
4088
Arthur Hungb92218b2018-08-14 12:00:21 +08004089 for (auto& it : mWindowHandlesByDisplay) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004090 const std::vector<sp<InputWindowHandle>>& windowHandles = it.second;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004091 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004092 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004093 return windowHandle;
4094 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004095 }
4096 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004097 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004098}
4099
Vishnu Nairad321cd2020-08-20 16:40:21 -07004100sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(const sp<IBinder>& windowHandleToken,
4101 int displayId) const {
4102 if (windowHandleToken == nullptr) {
4103 return nullptr;
4104 }
4105
4106 for (const sp<InputWindowHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
4107 if (windowHandle->getToken() == windowHandleToken) {
4108 return windowHandle;
4109 }
4110 }
4111 return nullptr;
4112}
4113
4114sp<InputWindowHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
4115 sp<IBinder> focusedToken = getValueByKey(mFocusedWindowTokenByDisplay, displayId);
4116 return getWindowHandleLocked(focusedToken, displayId);
4117}
4118
Mady Mellor017bcd12020-06-23 19:12:00 +00004119bool InputDispatcher::hasWindowHandleLocked(const sp<InputWindowHandle>& windowHandle) const {
4120 for (auto& it : mWindowHandlesByDisplay) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004121 const std::vector<sp<InputWindowHandle>>& windowHandles = it.second;
Mady Mellor017bcd12020-06-23 19:12:00 +00004122 for (const sp<InputWindowHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08004123 if (handle->getId() == windowHandle->getId() &&
4124 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004125 if (windowHandle->getInfo()->displayId != it.first) {
4126 ALOGE("Found window %s in display %" PRId32
4127 ", but it should belong to display %" PRId32,
4128 windowHandle->getName().c_str(), it.first,
4129 windowHandle->getInfo()->displayId);
4130 }
4131 return true;
Arthur Hungb92218b2018-08-14 12:00:21 +08004132 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004133 }
4134 }
4135 return false;
4136}
4137
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004138bool InputDispatcher::hasResponsiveConnectionLocked(InputWindowHandle& windowHandle) const {
4139 sp<Connection> connection = getConnectionLocked(windowHandle.getToken());
4140 const bool noInputChannel =
4141 windowHandle.getInfo()->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
4142 if (connection != nullptr && noInputChannel) {
4143 ALOGW("%s has feature NO_INPUT_CHANNEL, but it matched to connection %s",
4144 windowHandle.getName().c_str(), connection->inputChannel->getName().c_str());
4145 return false;
4146 }
4147
4148 if (connection == nullptr) {
4149 if (!noInputChannel) {
4150 ALOGI("Could not find connection for %s", windowHandle.getName().c_str());
4151 }
4152 return false;
4153 }
4154 if (!connection->responsive) {
4155 ALOGW("Window %s is not responsive", windowHandle.getName().c_str());
4156 return false;
4157 }
4158 return true;
4159}
4160
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004161std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
4162 const sp<IBinder>& token) const {
Robert Carr5c8a0262018-10-03 16:30:44 -07004163 size_t count = mInputChannelsByToken.count(token);
4164 if (count == 0) {
4165 return nullptr;
4166 }
4167 return mInputChannelsByToken.at(token);
4168}
4169
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004170void InputDispatcher::updateWindowHandlesForDisplayLocked(
4171 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
4172 if (inputWindowHandles.empty()) {
4173 // Remove all handles on a display if there are no windows left.
4174 mWindowHandlesByDisplay.erase(displayId);
4175 return;
4176 }
4177
4178 // Since we compare the pointer of input window handles across window updates, we need
4179 // to make sure the handle object for the same window stays unchanged across updates.
4180 const std::vector<sp<InputWindowHandle>>& oldHandles = getWindowHandlesLocked(displayId);
chaviwaf87b3e2019-10-01 16:59:28 -07004181 std::unordered_map<int32_t /*id*/, sp<InputWindowHandle>> oldHandlesById;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004182 for (const sp<InputWindowHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07004183 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004184 }
4185
4186 std::vector<sp<InputWindowHandle>> newHandles;
4187 for (const sp<InputWindowHandle>& handle : inputWindowHandles) {
4188 if (!handle->updateInfo()) {
4189 // handle no longer valid
4190 continue;
4191 }
4192
4193 const InputWindowInfo* info = handle->getInfo();
4194 if ((getInputChannelLocked(handle->getToken()) == nullptr &&
4195 info->portalToDisplayId == ADISPLAY_ID_NONE)) {
4196 const bool noInputChannel =
Michael Wright44753b12020-07-08 13:48:11 +01004197 info->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
4198 const bool canReceiveInput = !info->flags.test(InputWindowInfo::Flag::NOT_TOUCHABLE) ||
4199 !info->flags.test(InputWindowInfo::Flag::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004200 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07004201 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004202 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07004203 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004204 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004205 }
4206
4207 if (info->displayId != displayId) {
4208 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
4209 handle->getName().c_str(), displayId, info->displayId);
4210 continue;
4211 }
4212
Robert Carredd13602020-04-13 17:24:34 -07004213 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
4214 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviwaf87b3e2019-10-01 16:59:28 -07004215 const sp<InputWindowHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004216 oldHandle->updateFrom(handle);
4217 newHandles.push_back(oldHandle);
4218 } else {
4219 newHandles.push_back(handle);
4220 }
4221 }
4222
4223 // Insert or replace
4224 mWindowHandlesByDisplay[displayId] = newHandles;
4225}
4226
Arthur Hung72d8dc32020-03-28 00:48:39 +00004227void InputDispatcher::setInputWindows(
4228 const std::unordered_map<int32_t, std::vector<sp<InputWindowHandle>>>& handlesPerDisplay) {
4229 { // acquire lock
4230 std::scoped_lock _l(mLock);
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004231 for (const auto& [displayId, handles] : handlesPerDisplay) {
4232 setInputWindowsLocked(handles, displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004233 }
4234 }
4235 // Wake up poll loop since it may need to make new input dispatching choices.
4236 mLooper->wake();
4237}
4238
Arthur Hungb92218b2018-08-14 12:00:21 +08004239/**
4240 * Called from InputManagerService, update window handle list by displayId that can receive input.
4241 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
4242 * If set an empty list, remove all handles from the specific display.
4243 * For focused handle, check if need to change and send a cancel event to previous one.
4244 * For removed handle, check if need to send a cancel event if already in touch.
4245 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00004246void InputDispatcher::setInputWindowsLocked(
4247 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004248 if (DEBUG_FOCUS) {
4249 std::string windowList;
4250 for (const sp<InputWindowHandle>& iwh : inputWindowHandles) {
4251 windowList += iwh->getName() + " ";
4252 }
4253 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
4254 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004255
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004256 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
4257 for (const sp<InputWindowHandle>& window : inputWindowHandles) {
4258 const bool noInputWindow =
4259 window->getInfo()->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
4260 if (noInputWindow && window->getToken() != nullptr) {
4261 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
4262 window->getName().c_str());
4263 window->releaseChannel();
4264 }
4265 }
4266
Arthur Hung72d8dc32020-03-28 00:48:39 +00004267 // Copy old handles for release if they are no longer present.
4268 const std::vector<sp<InputWindowHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004269
Arthur Hung72d8dc32020-03-28 00:48:39 +00004270 updateWindowHandlesForDisplayLocked(inputWindowHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004271
Vishnu Nair958da932020-08-21 17:12:37 -07004272 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
4273 if (mLastHoverWindowHandle &&
4274 std::find(windowHandles.begin(), windowHandles.end(), mLastHoverWindowHandle) ==
4275 windowHandles.end()) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004276 mLastHoverWindowHandle = nullptr;
4277 }
4278
Vishnu Nair958da932020-08-21 17:12:37 -07004279 sp<IBinder> focusedToken = getValueByKey(mFocusedWindowTokenByDisplay, displayId);
4280 if (focusedToken) {
4281 FocusResult result = checkTokenFocusableLocked(focusedToken, displayId);
4282 if (result != FocusResult::OK) {
4283 onFocusChangedLocked(focusedToken, nullptr, displayId, typeToString(result));
4284 }
4285 }
4286
4287 std::optional<FocusRequest> focusRequest =
4288 getOptionalValueByKey(mPendingFocusRequests, displayId);
4289 if (focusRequest) {
4290 // If the window from the pending request is now visible, provide it focus.
4291 FocusResult result = handleFocusRequestLocked(*focusRequest);
4292 if (result != FocusResult::NOT_VISIBLE) {
4293 // Drop the request if we were able to change the focus or we cannot change
4294 // it for another reason.
4295 mPendingFocusRequests.erase(displayId);
4296 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004297 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004298
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004299 std::unordered_map<int32_t, TouchState>::iterator stateIt =
4300 mTouchStatesByDisplay.find(displayId);
4301 if (stateIt != mTouchStatesByDisplay.end()) {
4302 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00004303 for (size_t i = 0; i < state.windows.size();) {
4304 TouchedWindow& touchedWindow = state.windows[i];
Mady Mellor017bcd12020-06-23 19:12:00 +00004305 if (!hasWindowHandleLocked(touchedWindow.windowHandle)) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004306 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004307 ALOGD("Touched window was removed: %s in display %" PRId32,
4308 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004309 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004310 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00004311 getInputChannelLocked(touchedWindow.windowHandle->getToken());
4312 if (touchedInputChannel != nullptr) {
4313 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4314 "touched window was removed");
4315 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004316 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004317 state.windows.erase(state.windows.begin() + i);
4318 } else {
4319 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004320 }
4321 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004322 }
Arthur Hung25e2af12020-03-26 12:58:37 +00004323
Arthur Hung72d8dc32020-03-28 00:48:39 +00004324 // Release information for windows that are no longer present.
4325 // This ensures that unused input channels are released promptly.
4326 // Otherwise, they might stick around until the window handle is destroyed
4327 // which might not happen until the next GC.
4328 for (const sp<InputWindowHandle>& oldWindowHandle : oldWindowHandles) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004329 if (!hasWindowHandleLocked(oldWindowHandle)) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004330 if (DEBUG_FOCUS) {
4331 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00004332 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004333 oldWindowHandle->releaseChannel();
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004334 // To avoid making too many calls into the compat framework, only
4335 // check for window flags when windows are going away.
4336 // TODO(b/157929241) : delete this. This is only needed temporarily
4337 // in order to gather some data about the flag usage
4338 if (oldWindowHandle->getInfo()->flags.test(InputWindowInfo::Flag::SLIPPERY)) {
4339 ALOGW("%s has FLAG_SLIPPERY. Please report this in b/157929241",
4340 oldWindowHandle->getName().c_str());
4341 if (mCompatService != nullptr) {
4342 mCompatService->reportChangeByUid(IInputConstants::BLOCK_FLAG_SLIPPERY,
4343 oldWindowHandle->getInfo()->ownerUid);
4344 }
4345 }
Arthur Hung25e2af12020-03-26 12:58:37 +00004346 }
chaviw291d88a2019-02-14 10:33:58 -08004347 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004348}
4349
4350void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07004351 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004352 if (DEBUG_FOCUS) {
4353 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
4354 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
4355 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004356 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004357 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004358
Chris Yea209fde2020-07-22 13:54:51 -07004359 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08004360 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004361
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004362 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
4363 return; // This application is already focused. No need to wake up or change anything.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004364 }
4365
Chris Yea209fde2020-07-22 13:54:51 -07004366 // Set the new application handle.
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004367 if (inputApplicationHandle != nullptr) {
4368 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
4369 } else {
4370 mFocusedApplicationHandlesByDisplay.erase(displayId);
4371 }
4372
4373 // No matter what the old focused application was, stop waiting on it because it is
4374 // no longer focused.
4375 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004376 } // release lock
4377
4378 // Wake up poll loop since it may need to make new input dispatching choices.
4379 mLooper->wake();
4380}
4381
Tiger Huang721e26f2018-07-24 22:26:19 +08004382/**
4383 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
4384 * the display not specified.
4385 *
4386 * We track any unreleased events for each window. If a window loses the ability to receive the
4387 * released event, we will send a cancel event to it. So when the focused display is changed, we
4388 * cancel all the unreleased display-unspecified events for the focused window on the old focused
4389 * display. The display-specified events won't be affected.
4390 */
4391void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004392 if (DEBUG_FOCUS) {
4393 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
4394 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004395 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004396 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08004397
4398 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004399 sp<IBinder> oldFocusedWindowToken =
4400 getValueByKey(mFocusedWindowTokenByDisplay, mFocusedDisplayId);
4401 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004402 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07004403 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08004404 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004405 CancelationOptions
4406 options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
4407 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004408 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08004409 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
4410 }
4411 }
4412 mFocusedDisplayId = displayId;
4413
Chris Ye3c2d6f52020-08-09 10:39:48 -07004414 // Find new focused window and validate
Vishnu Nairad321cd2020-08-20 16:40:21 -07004415 sp<IBinder> newFocusedWindowToken =
4416 getValueByKey(mFocusedWindowTokenByDisplay, displayId);
4417 notifyFocusChangedLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08004418
Vishnu Nairad321cd2020-08-20 16:40:21 -07004419 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08004420 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07004421 if (!mFocusedWindowTokenByDisplay.empty()) {
4422 ALOGE("But another display has a focused window\n%s",
4423 dumpFocusedWindowsLocked().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08004424 }
4425 }
4426 }
4427
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004428 if (DEBUG_FOCUS) {
4429 logDispatchStateLocked();
4430 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004431 } // release lock
4432
4433 // Wake up poll loop since it may need to make new input dispatching choices.
4434 mLooper->wake();
4435}
4436
Michael Wrightd02c5b62014-02-10 15:10:22 -08004437void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004438 if (DEBUG_FOCUS) {
4439 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
4440 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004441
4442 bool changed;
4443 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004444 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004445
4446 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
4447 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004448 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004449 }
4450
4451 if (mDispatchEnabled && !enabled) {
4452 resetAndDropEverythingLocked("dispatcher is being disabled");
4453 }
4454
4455 mDispatchEnabled = enabled;
4456 mDispatchFrozen = frozen;
4457 changed = true;
4458 } else {
4459 changed = false;
4460 }
4461
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004462 if (DEBUG_FOCUS) {
4463 logDispatchStateLocked();
4464 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004465 } // release lock
4466
4467 if (changed) {
4468 // Wake up poll loop since it may need to make new input dispatching choices.
4469 mLooper->wake();
4470 }
4471}
4472
4473void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004474 if (DEBUG_FOCUS) {
4475 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
4476 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004477
4478 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004479 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004480
4481 if (mInputFilterEnabled == enabled) {
4482 return;
4483 }
4484
4485 mInputFilterEnabled = enabled;
4486 resetAndDropEverythingLocked("input filter is being enabled or disabled");
4487 } // release lock
4488
4489 // Wake up poll loop since there might be work to do to drop everything.
4490 mLooper->wake();
4491}
4492
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08004493void InputDispatcher::setInTouchMode(bool inTouchMode) {
4494 std::scoped_lock lock(mLock);
4495 mInTouchMode = inTouchMode;
4496}
4497
Bernardo Rufinoea97d182020-08-19 14:43:14 +01004498void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
4499 if (opacity < 0 || opacity > 1) {
4500 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
4501 return;
4502 }
4503
4504 std::scoped_lock lock(mLock);
4505 mMaximumObscuringOpacityForTouch = opacity;
4506}
4507
4508void InputDispatcher::setBlockUntrustedTouchesMode(BlockUntrustedTouchesMode mode) {
4509 std::scoped_lock lock(mLock);
4510 mBlockUntrustedTouchesMode = mode;
4511}
4512
chaviwfbe5d9c2018-12-26 12:23:37 -08004513bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken) {
4514 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004515 if (DEBUG_FOCUS) {
4516 ALOGD("Trivial transfer to same window.");
4517 }
chaviwfbe5d9c2018-12-26 12:23:37 -08004518 return true;
4519 }
4520
Michael Wrightd02c5b62014-02-10 15:10:22 -08004521 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004522 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004523
chaviwfbe5d9c2018-12-26 12:23:37 -08004524 sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromToken);
4525 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toToken);
Yi Kong9b14ac62018-07-17 13:48:38 -07004526 if (fromWindowHandle == nullptr || toWindowHandle == nullptr) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004527 ALOGW("Cannot transfer focus because from or to window not found.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004528 return false;
4529 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004530 if (DEBUG_FOCUS) {
4531 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
4532 fromWindowHandle->getName().c_str(), toWindowHandle->getName().c_str());
4533 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004534 if (fromWindowHandle->getInfo()->displayId != toWindowHandle->getInfo()->displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004535 if (DEBUG_FOCUS) {
4536 ALOGD("Cannot transfer focus because windows are on different displays.");
4537 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004538 return false;
4539 }
4540
4541 bool found = false;
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004542 for (std::pair<const int32_t, TouchState>& pair : mTouchStatesByDisplay) {
4543 TouchState& state = pair.second;
Jeff Brownf086ddb2014-02-11 14:28:48 -08004544 for (size_t i = 0; i < state.windows.size(); i++) {
4545 const TouchedWindow& touchedWindow = state.windows[i];
4546 if (touchedWindow.windowHandle == fromWindowHandle) {
4547 int32_t oldTargetFlags = touchedWindow.targetFlags;
4548 BitSet32 pointerIds = touchedWindow.pointerIds;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004549
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004550 state.windows.erase(state.windows.begin() + i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004551
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004552 int32_t newTargetFlags = oldTargetFlags &
4553 (InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_SPLIT |
4554 InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004555 state.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004556
Jeff Brownf086ddb2014-02-11 14:28:48 -08004557 found = true;
4558 goto Found;
4559 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004560 }
4561 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004562 Found:
Michael Wrightd02c5b62014-02-10 15:10:22 -08004563
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004564 if (!found) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004565 if (DEBUG_FOCUS) {
4566 ALOGD("Focus transfer failed because from window did not have focus.");
4567 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004568 return false;
4569 }
4570
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004571 sp<Connection> fromConnection = getConnectionLocked(fromToken);
4572 sp<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004573 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004574 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004575 CancelationOptions
4576 options(CancelationOptions::CANCEL_POINTER_EVENTS,
4577 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004578 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004579 synthesizePointerDownEventsForConnectionLocked(toConnection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004580 }
4581
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004582 if (DEBUG_FOCUS) {
4583 logDispatchStateLocked();
4584 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004585 } // release lock
4586
4587 // Wake up poll loop since it may need to make new input dispatching choices.
4588 mLooper->wake();
4589 return true;
4590}
4591
4592void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004593 if (DEBUG_FOCUS) {
4594 ALOGD("Resetting and dropping all events (%s).", reason);
4595 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004596
4597 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
4598 synthesizeCancelationEventsForAllConnectionsLocked(options);
4599
4600 resetKeyRepeatLocked();
4601 releasePendingEventLocked();
4602 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004603 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004604
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004605 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08004606 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004607 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07004608 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004609}
4610
4611void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004612 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004613 dumpDispatchStateLocked(dump);
4614
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004615 std::istringstream stream(dump);
4616 std::string line;
4617
4618 while (std::getline(stream, line, '\n')) {
4619 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004620 }
4621}
4622
Vishnu Nairad321cd2020-08-20 16:40:21 -07004623std::string InputDispatcher::dumpFocusedWindowsLocked() {
4624 if (mFocusedWindowTokenByDisplay.empty()) {
4625 return INDENT "FocusedWindows: <none>\n";
4626 }
4627
4628 std::string dump;
4629 dump += INDENT "FocusedWindows:\n";
4630 for (auto& it : mFocusedWindowTokenByDisplay) {
4631 const int32_t displayId = it.first;
4632 const sp<InputWindowHandle> windowHandle = getFocusedWindowHandleLocked(displayId);
4633 if (windowHandle) {
4634 dump += StringPrintf(INDENT2 "displayId=%" PRId32 ", name='%s'\n", displayId,
4635 windowHandle->getName().c_str());
4636 } else {
4637 dump += StringPrintf(INDENT2 "displayId=%" PRId32
4638 " has focused token without a window'\n",
4639 displayId);
4640 }
4641 }
4642 return dump;
4643}
4644
Siarhei Vishniakouad991402020-10-28 11:40:09 -05004645std::string InputDispatcher::dumpPendingFocusRequestsLocked() {
4646 if (mPendingFocusRequests.empty()) {
4647 return INDENT "mPendingFocusRequests: <none>\n";
4648 }
4649
4650 std::string dump;
4651 dump += INDENT "mPendingFocusRequests:\n";
4652 for (const auto& [displayId, focusRequest] : mPendingFocusRequests) {
4653 // Rather than printing raw values for focusRequest.token and focusRequest.focusedToken,
4654 // try to resolve them to actual windows.
4655 std::string windowName = getConnectionNameLocked(focusRequest.token);
4656 std::string focusedWindowName = getConnectionNameLocked(focusRequest.focusedToken);
4657 dump += StringPrintf(INDENT2 "displayId=%" PRId32 ", token->%s, focusedToken->%s\n",
4658 displayId, windowName.c_str(), focusedWindowName.c_str());
4659 }
4660 return dump;
4661}
4662
Prabir Pradhan99987712020-11-10 18:43:05 -08004663std::string InputDispatcher::dumpPointerCaptureStateLocked() {
4664 std::string dump;
4665
4666 dump += StringPrintf(INDENT "FocusedWindowRequestedPointerCapture: %s\n",
4667 toString(mFocusedWindowRequestedPointerCapture));
4668
4669 std::string windowName = "None";
4670 if (mWindowTokenWithPointerCapture) {
4671 const sp<InputWindowHandle> captureWindowHandle =
4672 getWindowHandleLocked(mWindowTokenWithPointerCapture);
4673 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
4674 : "token has capture without window";
4675 }
4676 dump += StringPrintf(INDENT "CurrentWindowWithPointerCapture: %s\n", windowName.c_str());
4677
4678 return dump;
4679}
4680
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004681void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07004682 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
4683 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
4684 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08004685 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004686
Tiger Huang721e26f2018-07-24 22:26:19 +08004687 if (!mFocusedApplicationHandlesByDisplay.empty()) {
4688 dump += StringPrintf(INDENT "FocusedApplications:\n");
4689 for (auto& it : mFocusedApplicationHandlesByDisplay) {
4690 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07004691 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05004692 const std::chrono::duration timeout =
4693 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004694 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004695 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05004696 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08004697 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004698 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08004699 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004700 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004701
Vishnu Nairad321cd2020-08-20 16:40:21 -07004702 dump += dumpFocusedWindowsLocked();
Siarhei Vishniakouad991402020-10-28 11:40:09 -05004703 dump += dumpPendingFocusRequestsLocked();
Prabir Pradhan99987712020-11-10 18:43:05 -08004704 dump += dumpPointerCaptureStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004705
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004706 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004707 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004708 for (const std::pair<int32_t, TouchState>& pair : mTouchStatesByDisplay) {
4709 const TouchState& state = pair.second;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004710 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004711 state.displayId, toString(state.down), toString(state.split),
4712 state.deviceId, state.source);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004713 if (!state.windows.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004714 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004715 for (size_t i = 0; i < state.windows.size(); i++) {
4716 const TouchedWindow& touchedWindow = state.windows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004717 dump += StringPrintf(INDENT4
4718 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
4719 i, touchedWindow.windowHandle->getName().c_str(),
4720 touchedWindow.pointerIds.value, touchedWindow.targetFlags);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004721 }
4722 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004723 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004724 }
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004725 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004726 dump += INDENT3 "Portal windows:\n";
4727 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004728 const sp<InputWindowHandle> portalWindowHandle = state.portalWindows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004729 dump += StringPrintf(INDENT4 "%zu: name='%s'\n", i,
4730 portalWindowHandle->getName().c_str());
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004731 }
4732 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004733 }
4734 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004735 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004736 }
4737
Arthur Hungb92218b2018-08-14 12:00:21 +08004738 if (!mWindowHandlesByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004739 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004740 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
Arthur Hung3b413f22018-10-26 18:05:34 +08004741 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", it.first);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004742 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004743 dump += INDENT2 "Windows:\n";
4744 for (size_t i = 0; i < windowHandles.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004745 const sp<InputWindowHandle>& windowHandle = windowHandles[i];
Arthur Hungb92218b2018-08-14 12:00:21 +08004746 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004747
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00004748 dump += StringPrintf(INDENT3 "%zu: name='%s', id=%" PRId32 ", displayId=%d, "
Vishnu Nair47074b82020-08-14 11:54:47 -07004749 "portalToDisplayId=%d, paused=%s, focusable=%s, "
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00004750 "hasWallpaper=%s, visible=%s, alpha=%.2f, "
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00004751 "flags=%s, type=%s, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004752 "frame=[%d,%d][%d,%d], globalScale=%f, "
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004753 "applicationInfo=%s, "
chaviw1ff3d1e2020-07-01 15:53:47 -07004754 "touchableRegion=",
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00004755 i, windowInfo->name.c_str(), windowInfo->id,
4756 windowInfo->displayId, windowInfo->portalToDisplayId,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004757 toString(windowInfo->paused),
Vishnu Nair47074b82020-08-14 11:54:47 -07004758 toString(windowInfo->focusable),
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004759 toString(windowInfo->hasWallpaper),
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00004760 toString(windowInfo->visible), windowInfo->alpha,
Michael Wright8759d672020-07-21 00:46:45 +01004761 windowInfo->flags.string().c_str(),
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00004762 NamedEnum::string(windowInfo->type).c_str(),
Michael Wright44753b12020-07-08 13:48:11 +01004763 windowInfo->frameLeft, windowInfo->frameTop,
4764 windowInfo->frameRight, windowInfo->frameBottom,
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004765 windowInfo->globalScaleFactor,
4766 windowInfo->applicationInfo.name.c_str());
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00004767 dump += dumpRegion(windowInfo->touchableRegion);
Michael Wright44753b12020-07-08 13:48:11 +01004768 dump += StringPrintf(", inputFeatures=%s",
4769 windowInfo->inputFeatures.string().c_str());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004770 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%" PRId64
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00004771 "ms, trustedOverlay=%s, hasToken=%s, "
4772 "touchOcclusionMode=%s\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004773 windowInfo->ownerPid, windowInfo->ownerUid,
Bernardo Rufinoc2f1fad2020-11-04 17:30:57 +00004774 millis(windowInfo->dispatchingTimeout),
4775 toString(windowInfo->trustedOverlay),
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00004776 toString(windowInfo->token != nullptr),
4777 toString(windowInfo->touchOcclusionMode).c_str());
chaviw85b44202020-07-24 11:46:21 -07004778 windowInfo->transform.dump(dump, "transform", INDENT4);
Arthur Hungb92218b2018-08-14 12:00:21 +08004779 }
4780 } else {
4781 dump += INDENT2 "Windows: <none>\n";
4782 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004783 }
4784 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08004785 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004786 }
4787
Michael Wright3dd60e22019-03-27 22:06:44 +00004788 if (!mGlobalMonitorsByDisplay.empty() || !mGestureMonitorsByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004789 for (auto& it : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004790 const std::vector<Monitor>& monitors = it.second;
4791 dump += StringPrintf(INDENT "Global monitors in display %" PRId32 ":\n", it.first);
4792 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004793 }
4794 for (auto& it : mGestureMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004795 const std::vector<Monitor>& monitors = it.second;
4796 dump += StringPrintf(INDENT "Gesture monitors in display %" PRId32 ":\n", it.first);
4797 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004798 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004799 } else {
Michael Wright3dd60e22019-03-27 22:06:44 +00004800 dump += INDENT "Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004801 }
4802
4803 nsecs_t currentTime = now();
4804
4805 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004806 if (!mRecentQueue.empty()) {
4807 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004808 for (std::shared_ptr<EventEntry>& entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004809 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05004810 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004811 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004812 }
4813 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004814 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004815 }
4816
4817 // Dump event currently being dispatched.
4818 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004819 dump += INDENT "PendingEvent:\n";
4820 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05004821 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004822 dump += StringPrintf(", age=%" PRId64 "ms\n",
4823 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004824 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004825 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004826 }
4827
4828 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004829 if (!mInboundQueue.empty()) {
4830 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004831 for (std::shared_ptr<EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004832 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05004833 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004834 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004835 }
4836 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004837 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004838 }
4839
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004840 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004841 dump += INDENT "ReplacedKeys:\n";
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004842 for (const std::pair<KeyReplacement, int32_t>& pair : mReplacedKeys) {
4843 const KeyReplacement& replacement = pair.first;
4844 int32_t newKeyCode = pair.second;
4845 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004846 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07004847 }
4848 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004849 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07004850 }
4851
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004852 if (!mConnectionsByFd.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004853 dump += INDENT "Connections:\n";
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004854 for (const auto& pair : mConnectionsByFd) {
4855 const sp<Connection>& connection = pair.second;
4856 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004857 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004858 pair.first, connection->getInputChannelName().c_str(),
4859 connection->getWindowName().c_str(), connection->getStatusLabel(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004860 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004861
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004862 if (!connection->outboundQueue.empty()) {
4863 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
4864 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05004865 dump += dumpQueue(connection->outboundQueue, currentTime);
4866
Michael Wrightd02c5b62014-02-10 15:10:22 -08004867 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004868 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004869 }
4870
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004871 if (!connection->waitQueue.empty()) {
4872 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
4873 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05004874 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004875 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004876 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004877 }
4878 }
4879 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004880 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004881 }
4882
4883 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004884 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
4885 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004886 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004887 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004888 }
4889
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004890 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004891 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
4892 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
4893 ns2ms(mConfig.keyRepeatTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004894}
4895
Michael Wright3dd60e22019-03-27 22:06:44 +00004896void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
4897 const size_t numMonitors = monitors.size();
4898 for (size_t i = 0; i < numMonitors; i++) {
4899 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004900 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00004901 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
4902 dump += "\n";
4903 }
4904}
4905
Garfield Tan15601662020-09-22 15:32:38 -07004906base::Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(
4907 const std::string& name) {
4908#if DEBUG_CHANNEL_CREATION
4909 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004910#endif
4911
Garfield Tan15601662020-09-22 15:32:38 -07004912 std::shared_ptr<InputChannel> serverChannel;
4913 std::unique_ptr<InputChannel> clientChannel;
4914 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
4915
4916 if (result) {
4917 return base::Error(result) << "Failed to open input channel pair with name " << name;
4918 }
4919
Michael Wrightd02c5b62014-02-10 15:10:22 -08004920 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004921 std::scoped_lock _l(mLock);
Garfield Tan15601662020-09-22 15:32:38 -07004922 sp<Connection> connection = new Connection(serverChannel, false /*monitor*/, mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004923
Garfield Tan15601662020-09-22 15:32:38 -07004924 int fd = serverChannel->getFd();
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004925 mConnectionsByFd[fd] = connection;
Garfield Tan15601662020-09-22 15:32:38 -07004926 mInputChannelsByToken[serverChannel->getConnectionToken()] = serverChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004927
Michael Wrightd02c5b62014-02-10 15:10:22 -08004928 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
4929 } // release lock
4930
4931 // Wake the looper because some connections have changed.
4932 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07004933 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004934}
4935
Garfield Tan15601662020-09-22 15:32:38 -07004936base::Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(
Siarhei Vishniakou58cfc602020-12-14 23:21:30 +00004937 int32_t displayId, bool isGestureMonitor, const std::string& name, int32_t pid) {
Garfield Tan15601662020-09-22 15:32:38 -07004938 std::shared_ptr<InputChannel> serverChannel;
4939 std::unique_ptr<InputChannel> clientChannel;
4940 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
4941 if (result) {
4942 return base::Error(result) << "Failed to open input channel pair with name " << name;
4943 }
4944
Michael Wright3dd60e22019-03-27 22:06:44 +00004945 { // acquire lock
4946 std::scoped_lock _l(mLock);
4947
4948 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07004949 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
4950 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00004951 }
4952
Garfield Tan15601662020-09-22 15:32:38 -07004953 sp<Connection> connection = new Connection(serverChannel, true /*monitor*/, mIdGenerator);
Michael Wright3dd60e22019-03-27 22:06:44 +00004954
Garfield Tan15601662020-09-22 15:32:38 -07004955 const int fd = serverChannel->getFd();
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004956 mConnectionsByFd[fd] = connection;
Garfield Tan15601662020-09-22 15:32:38 -07004957 mInputChannelsByToken[serverChannel->getConnectionToken()] = serverChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00004958
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004959 auto& monitorsByDisplay =
4960 isGestureMonitor ? mGestureMonitorsByDisplay : mGlobalMonitorsByDisplay;
Siarhei Vishniakou58cfc602020-12-14 23:21:30 +00004961 monitorsByDisplay[displayId].emplace_back(serverChannel, pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00004962
4963 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
Michael Wright3dd60e22019-03-27 22:06:44 +00004964 }
Garfield Tan15601662020-09-22 15:32:38 -07004965
Michael Wright3dd60e22019-03-27 22:06:44 +00004966 // Wake the looper because some connections have changed.
4967 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07004968 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00004969}
4970
Garfield Tan15601662020-09-22 15:32:38 -07004971status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004972 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004973 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004974
Garfield Tan15601662020-09-22 15:32:38 -07004975 status_t status = removeInputChannelLocked(connectionToken, false /*notify*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004976 if (status) {
4977 return status;
4978 }
4979 } // release lock
4980
4981 // Wake the poll loop because removing the connection may have changed the current
4982 // synchronization state.
4983 mLooper->wake();
4984 return OK;
4985}
4986
Garfield Tan15601662020-09-22 15:32:38 -07004987status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
4988 bool notify) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004989 sp<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004990 if (connection == nullptr) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004991 ALOGW("Attempted to unregister already unregistered input channel");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004992 return BAD_VALUE;
4993 }
4994
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004995 removeConnectionLocked(connection);
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004996 mInputChannelsByToken.erase(connectionToken);
Robert Carr5c8a0262018-10-03 16:30:44 -07004997
Michael Wrightd02c5b62014-02-10 15:10:22 -08004998 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004999 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005000 }
5001
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005002 mLooper->removeFd(connection->inputChannel->getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005003
5004 nsecs_t currentTime = now();
5005 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
5006
5007 connection->status = Connection::STATUS_ZOMBIE;
5008 return OK;
5009}
5010
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005011void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
5012 removeMonitorChannelLocked(connectionToken, mGlobalMonitorsByDisplay);
5013 removeMonitorChannelLocked(connectionToken, mGestureMonitorsByDisplay);
Michael Wright3dd60e22019-03-27 22:06:44 +00005014}
5015
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005016void InputDispatcher::removeMonitorChannelLocked(
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005017 const sp<IBinder>& connectionToken,
Michael Wright3dd60e22019-03-27 22:06:44 +00005018 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005019 for (auto it = monitorsByDisplay.begin(); it != monitorsByDisplay.end();) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005020 std::vector<Monitor>& monitors = it->second;
5021 const size_t numMonitors = monitors.size();
5022 for (size_t i = 0; i < numMonitors; i++) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005023 if (monitors[i].inputChannel->getConnectionToken() == connectionToken) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005024 monitors.erase(monitors.begin() + i);
5025 break;
5026 }
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005027 }
Michael Wright3dd60e22019-03-27 22:06:44 +00005028 if (monitors.empty()) {
5029 it = monitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005030 } else {
5031 ++it;
5032 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005033 }
5034}
5035
Michael Wright3dd60e22019-03-27 22:06:44 +00005036status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
5037 { // acquire lock
5038 std::scoped_lock _l(mLock);
5039 std::optional<int32_t> foundDisplayId = findGestureMonitorDisplayByTokenLocked(token);
5040
5041 if (!foundDisplayId) {
5042 ALOGW("Attempted to pilfer pointers from an un-registered monitor or invalid token");
5043 return BAD_VALUE;
5044 }
5045 int32_t displayId = foundDisplayId.value();
5046
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005047 std::unordered_map<int32_t, TouchState>::iterator stateIt =
5048 mTouchStatesByDisplay.find(displayId);
5049 if (stateIt == mTouchStatesByDisplay.end()) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005050 ALOGW("Failed to pilfer pointers: no pointers on display %" PRId32 ".", displayId);
5051 return BAD_VALUE;
5052 }
5053
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005054 TouchState& state = stateIt->second;
Michael Wright3dd60e22019-03-27 22:06:44 +00005055 std::optional<int32_t> foundDeviceId;
5056 for (const TouchedMonitor& touchedMonitor : state.gestureMonitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005057 if (touchedMonitor.monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005058 foundDeviceId = state.deviceId;
5059 }
5060 }
5061 if (!foundDeviceId || !state.down) {
5062 ALOGW("Attempted to pilfer points from a monitor without any on-going pointer streams."
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005063 " Ignoring.");
Michael Wright3dd60e22019-03-27 22:06:44 +00005064 return BAD_VALUE;
5065 }
5066 int32_t deviceId = foundDeviceId.value();
5067
5068 // Send cancel events to all the input channels we're stealing from.
5069 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005070 "gesture monitor stole pointer stream");
Michael Wright3dd60e22019-03-27 22:06:44 +00005071 options.deviceId = deviceId;
5072 options.displayId = displayId;
5073 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005074 std::shared_ptr<InputChannel> channel =
5075 getInputChannelLocked(window.windowHandle->getToken());
Michael Wright3a240c42019-12-10 20:53:41 +00005076 if (channel != nullptr) {
5077 synthesizeCancelationEventsForInputChannelLocked(channel, options);
5078 }
Michael Wright3dd60e22019-03-27 22:06:44 +00005079 }
5080 // Then clear the current touch state so we stop dispatching to them as well.
5081 state.filterNonMonitors();
5082 }
5083 return OK;
5084}
5085
Prabir Pradhan99987712020-11-10 18:43:05 -08005086void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
5087 { // acquire lock
5088 std::scoped_lock _l(mLock);
5089 if (DEBUG_FOCUS) {
5090 const sp<InputWindowHandle> windowHandle = getWindowHandleLocked(windowToken);
5091 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
5092 windowHandle != nullptr ? windowHandle->getName().c_str()
5093 : "token without window");
5094 }
5095
5096 const sp<IBinder> focusedToken =
5097 getValueByKey(mFocusedWindowTokenByDisplay, mFocusedDisplayId);
5098 if (focusedToken != windowToken) {
5099 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
5100 enabled ? "enable" : "disable");
5101 return;
5102 }
5103
5104 if (enabled == mFocusedWindowRequestedPointerCapture) {
5105 ALOGW("Ignoring request to %s Pointer Capture: "
5106 "window has %s requested pointer capture.",
5107 enabled ? "enable" : "disable", enabled ? "already" : "not");
5108 return;
5109 }
5110
5111 mFocusedWindowRequestedPointerCapture = enabled;
5112 setPointerCaptureLocked(enabled);
5113 } // release lock
5114
5115 // Wake the thread to process command entries.
5116 mLooper->wake();
5117}
5118
Michael Wright3dd60e22019-03-27 22:06:44 +00005119std::optional<int32_t> InputDispatcher::findGestureMonitorDisplayByTokenLocked(
5120 const sp<IBinder>& token) {
5121 for (const auto& it : mGestureMonitorsByDisplay) {
5122 const std::vector<Monitor>& monitors = it.second;
5123 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005124 if (monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005125 return it.first;
5126 }
5127 }
5128 }
5129 return std::nullopt;
5130}
5131
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005132sp<Connection> InputDispatcher::getConnectionLocked(const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005133 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005134 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08005135 }
5136
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005137 for (const auto& pair : mConnectionsByFd) {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005138 const sp<Connection>& connection = pair.second;
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005139 if (connection->inputChannel->getConnectionToken() == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005140 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005141 }
5142 }
Robert Carr4e670e52018-08-15 13:26:12 -07005143
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005144 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005145}
5146
Siarhei Vishniakouad991402020-10-28 11:40:09 -05005147std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
5148 sp<Connection> connection = getConnectionLocked(connectionToken);
5149 if (connection == nullptr) {
5150 return "<nullptr>";
5151 }
5152 return connection->getInputChannelName();
5153}
5154
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005155void InputDispatcher::removeConnectionLocked(const sp<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005156 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005157 removeByValue(mConnectionsByFd, connection);
5158}
5159
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005160void InputDispatcher::onDispatchCycleFinishedLocked(nsecs_t currentTime,
5161 const sp<Connection>& connection, uint32_t seq,
5162 bool handled) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005163 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5164 &InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005165 commandEntry->connection = connection;
5166 commandEntry->eventTime = currentTime;
5167 commandEntry->seq = seq;
5168 commandEntry->handled = handled;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005169 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005170}
5171
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005172void InputDispatcher::onDispatchCycleBrokenLocked(nsecs_t currentTime,
5173 const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005174 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005175 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005176
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005177 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5178 &InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005179 commandEntry->connection = connection;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005180 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005181}
5182
Vishnu Nairad321cd2020-08-20 16:40:21 -07005183void InputDispatcher::notifyFocusChangedLocked(const sp<IBinder>& oldToken,
5184 const sp<IBinder>& newToken) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005185 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5186 &InputDispatcher::doNotifyFocusChangedLockedInterruptible);
chaviw0c06c6e2019-01-09 13:27:07 -08005187 commandEntry->oldToken = oldToken;
5188 commandEntry->newToken = newToken;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005189 postCommandLocked(std::move(commandEntry));
Robert Carrf759f162018-11-13 12:57:11 -08005190}
5191
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -05005192void InputDispatcher::onAnrLocked(const Connection& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005193 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
5194 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -05005195 if (connection.waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005196 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -05005197 connection.inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005198 return;
5199 }
5200 /**
5201 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
5202 * may not be the one that caused the timeout to occur. One possibility is that window timeout
5203 * has changed. This could cause newer entries to time out before the already dispatched
5204 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
5205 * processes the events linearly. So providing information about the oldest entry seems to be
5206 * most useful.
5207 */
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -05005208 DispatchEntry* oldestEntry = *connection.waitQueue.begin();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005209 const nsecs_t currentWait = now() - oldestEntry->deliveryTime;
5210 std::string reason =
5211 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -05005212 connection.inputChannel->getName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005213 ns2ms(currentWait),
5214 oldestEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06005215 sp<IBinder> connectionToken = connection.inputChannel->getConnectionToken();
5216 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005217
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005218 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5219 &InputDispatcher::doNotifyConnectionUnresponsiveLockedInterruptible);
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06005220 commandEntry->connectionToken = connectionToken;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005221 commandEntry->reason = std::move(reason);
5222 postCommandLocked(std::move(commandEntry));
5223}
5224
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005225void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
5226 std::string reason =
5227 StringPrintf("%s does not have a focused window", application->getName().c_str());
5228 updateLastAnrStateLocked(*application, reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005229
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005230 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5231 &InputDispatcher::doNotifyNoFocusedWindowAnrLockedInterruptible);
5232 commandEntry->inputApplicationHandle = std::move(application);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005233 postCommandLocked(std::move(commandEntry));
5234}
5235
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00005236void InputDispatcher::onUntrustedTouchLocked(const std::string& obscuringPackage) {
5237 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5238 &InputDispatcher::doNotifyUntrustedTouchLockedInterruptible);
5239 commandEntry->obscuringPackage = obscuringPackage;
5240 postCommandLocked(std::move(commandEntry));
5241}
5242
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005243void InputDispatcher::updateLastAnrStateLocked(const sp<InputWindowHandle>& window,
5244 const std::string& reason) {
5245 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
5246 updateLastAnrStateLocked(windowLabel, reason);
5247}
5248
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005249void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
5250 const std::string& reason) {
5251 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005252 updateLastAnrStateLocked(windowLabel, reason);
5253}
5254
5255void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
5256 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005257 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07005258 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005259 struct tm tm;
5260 localtime_r(&t, &tm);
5261 char timestr[64];
5262 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005263 mLastAnrState.clear();
5264 mLastAnrState += INDENT "ANR:\n";
5265 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005266 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
5267 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005268 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005269}
5270
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005271void InputDispatcher::doNotifyConfigurationChangedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005272 mLock.unlock();
5273
5274 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
5275
5276 mLock.lock();
5277}
5278
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005279void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005280 sp<Connection> connection = commandEntry->connection;
5281
5282 if (connection->status != Connection::STATUS_ZOMBIE) {
5283 mLock.unlock();
5284
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005285 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005286
5287 mLock.lock();
5288 }
5289}
5290
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005291void InputDispatcher::doNotifyFocusChangedLockedInterruptible(CommandEntry* commandEntry) {
chaviw0c06c6e2019-01-09 13:27:07 -08005292 sp<IBinder> oldToken = commandEntry->oldToken;
5293 sp<IBinder> newToken = commandEntry->newToken;
Robert Carrf759f162018-11-13 12:57:11 -08005294 mLock.unlock();
chaviw0c06c6e2019-01-09 13:27:07 -08005295 mPolicy->notifyFocusChanged(oldToken, newToken);
Robert Carrf759f162018-11-13 12:57:11 -08005296 mLock.lock();
5297}
5298
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005299void InputDispatcher::doNotifyNoFocusedWindowAnrLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005300 mLock.unlock();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005301
5302 mPolicy->notifyNoFocusedWindowAnr(commandEntry->inputApplicationHandle);
5303
5304 mLock.lock();
5305}
5306
5307void InputDispatcher::doNotifyConnectionUnresponsiveLockedInterruptible(
5308 CommandEntry* commandEntry) {
5309 mLock.unlock();
5310
5311 mPolicy->notifyConnectionUnresponsive(commandEntry->connectionToken, commandEntry->reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005312
5313 mLock.lock();
5314
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005315 // stop waking up for events in this connection, it is already not responding
5316 sp<Connection> connection = getConnectionLocked(commandEntry->connectionToken);
5317 if (connection == nullptr) {
5318 return;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005319 }
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005320 cancelEventsForAnrLocked(connection);
5321}
5322
5323void InputDispatcher::doNotifyConnectionResponsiveLockedInterruptible(CommandEntry* commandEntry) {
5324 mLock.unlock();
5325
5326 mPolicy->notifyConnectionResponsive(commandEntry->connectionToken);
5327
5328 mLock.lock();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005329}
5330
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00005331void InputDispatcher::doNotifyUntrustedTouchLockedInterruptible(CommandEntry* commandEntry) {
5332 mLock.unlock();
5333
5334 mPolicy->notifyUntrustedTouch(commandEntry->obscuringPackage);
5335
5336 mLock.lock();
5337}
5338
Michael Wrightd02c5b62014-02-10 15:10:22 -08005339void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
5340 CommandEntry* commandEntry) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005341 KeyEntry& entry = *(commandEntry->keyEntry);
5342 KeyEvent event = createKeyEvent(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005343
5344 mLock.unlock();
5345
Michael Wright2b3c3302018-03-02 17:19:13 +00005346 android::base::Timer t;
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06005347 const sp<IBinder>& token = commandEntry->connectionToken;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005348 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(token, &event, entry.policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00005349 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
5350 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005351 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00005352 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005353
5354 mLock.lock();
5355
5356 if (delay < 0) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005357 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005358 } else if (!delay) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005359 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005360 } else {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005361 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
5362 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005363 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005364}
5365
chaviwfd6d3512019-03-25 13:23:49 -07005366void InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible(CommandEntry* commandEntry) {
5367 mLock.unlock();
5368 mPolicy->onPointerDownOutsideFocus(commandEntry->newToken);
5369 mLock.lock();
5370}
5371
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005372/**
5373 * Connection is responsive if it has no events in the waitQueue that are older than the
5374 * current time.
5375 */
5376static bool isConnectionResponsive(const Connection& connection) {
5377 const nsecs_t currentTime = now();
5378 for (const DispatchEntry* entry : connection.waitQueue) {
5379 if (entry->timeoutTime < currentTime) {
5380 return false;
5381 }
5382 }
5383 return true;
5384}
5385
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005386void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005387 sp<Connection> connection = commandEntry->connection;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005388 const nsecs_t finishTime = commandEntry->eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005389 uint32_t seq = commandEntry->seq;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005390 const bool handled = commandEntry->handled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005391
5392 // Handle post-event policy actions.
Garfield Tane84e6f92019-08-29 17:28:41 -07005393 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005394 if (dispatchEntryIt == connection->waitQueue.end()) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005395 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005396 }
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005397 DispatchEntry* dispatchEntry = *dispatchEntryIt;
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07005398 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005399 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005400 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
5401 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005402 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07005403 reportDispatchStatistics(std::chrono::nanoseconds(eventDuration), *connection, handled);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005404
5405 bool restartEvent;
Siarhei Vishniakou49483272019-10-22 13:13:47 -07005406 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005407 KeyEntry& keyEntry = static_cast<KeyEntry&>(*(dispatchEntry->eventEntry));
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005408 restartEvent =
5409 afterKeyEventLockedInterruptible(connection, dispatchEntry, keyEntry, handled);
Siarhei Vishniakou49483272019-10-22 13:13:47 -07005410 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005411 MotionEntry& motionEntry = static_cast<MotionEntry&>(*(dispatchEntry->eventEntry));
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005412 restartEvent = afterMotionEventLockedInterruptible(connection, dispatchEntry, motionEntry,
5413 handled);
5414 } else {
5415 restartEvent = false;
5416 }
5417
5418 // Dequeue the event and start the next cycle.
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07005419 // Because the lock might have been released, it is possible that the
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005420 // contents of the wait queue to have been drained, so we need to double-check
5421 // a few things.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005422 dispatchEntryIt = connection->findWaitQueueEntry(seq);
5423 if (dispatchEntryIt != connection->waitQueue.end()) {
5424 dispatchEntry = *dispatchEntryIt;
5425 connection->waitQueue.erase(dispatchEntryIt);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005426 const sp<IBinder>& connectionToken = connection->inputChannel->getConnectionToken();
5427 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005428 if (!connection->responsive) {
5429 connection->responsive = isConnectionResponsive(*connection);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005430 if (connection->responsive) {
5431 // The connection was unresponsive, and now it's responsive. Tell the policy
5432 // about it so that it can stop ANR.
5433 std::unique_ptr<CommandEntry> connectionResponsiveCommand =
5434 std::make_unique<CommandEntry>(
5435 &InputDispatcher::doNotifyConnectionResponsiveLockedInterruptible);
5436 connectionResponsiveCommand->connectionToken = connectionToken;
5437 postCommandLocked(std::move(connectionResponsiveCommand));
5438 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005439 }
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005440 traceWaitQueueLength(connection);
5441 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005442 connection->outboundQueue.push_front(dispatchEntry);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005443 traceOutboundQueueLength(connection);
5444 } else {
5445 releaseDispatchEntry(dispatchEntry);
5446 }
5447 }
5448
5449 // Start the next dispatch cycle for this connection.
5450 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005451}
5452
5453bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005454 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005455 KeyEntry& keyEntry, bool handled) {
5456 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005457 if (!handled) {
5458 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005459 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005460 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005461 return false;
5462 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005463
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005464 // Get the fallback key state.
5465 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005466 int32_t originalKeyCode = keyEntry.keyCode;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005467 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005468 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005469 connection->inputState.removeFallbackKey(originalKeyCode);
5470 }
5471
5472 if (handled || !dispatchEntry->hasForegroundTarget()) {
5473 // If the application handles the original key for which we previously
5474 // generated a fallback or if the window is not a foreground window,
5475 // then cancel the associated fallback key, if any.
5476 if (fallbackKeyCode != -1) {
5477 // Dispatch the unhandled key to the policy with the cancel flag.
Michael Wrightd02c5b62014-02-10 15:10:22 -08005478#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005479 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005480 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005481 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005482#endif
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005483 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005484 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005485
5486 mLock.unlock();
5487
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005488 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005489 keyEntry.policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005490
5491 mLock.lock();
5492
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005493 // Cancel the fallback key.
5494 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005495 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005496 "application handled the original non-fallback key "
5497 "or is no longer a foreground target, "
5498 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005499 options.keyCode = fallbackKeyCode;
5500 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005501 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005502 connection->inputState.removeFallbackKey(originalKeyCode);
5503 }
5504 } else {
5505 // If the application did not handle a non-fallback key, first check
5506 // that we are in a good state to perform unhandled key event processing
5507 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005508 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005509 if (fallbackKeyCode == -1 && !initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005510#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005511 ALOGD("Unhandled key event: Skipping unhandled key event processing "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005512 "since this is not an initial down. "
5513 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005514 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005515#endif
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005516 return false;
5517 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005518
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005519 // Dispatch the unhandled key to the policy.
5520#if DEBUG_OUTBOUND_EVENT_DETAILS
5521 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005522 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005523 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005524#endif
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005525 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005526
5527 mLock.unlock();
5528
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005529 bool fallback =
5530 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005531 &event, keyEntry.policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005532
5533 mLock.lock();
5534
5535 if (connection->status != Connection::STATUS_NORMAL) {
5536 connection->inputState.removeFallbackKey(originalKeyCode);
5537 return false;
5538 }
5539
5540 // Latch the fallback keycode for this key on an initial down.
5541 // The fallback keycode cannot change at any other point in the lifecycle.
5542 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005543 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005544 fallbackKeyCode = event.getKeyCode();
5545 } else {
5546 fallbackKeyCode = AKEYCODE_UNKNOWN;
5547 }
5548 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
5549 }
5550
5551 ALOG_ASSERT(fallbackKeyCode != -1);
5552
5553 // Cancel the fallback key if the policy decides not to send it anymore.
5554 // We will continue to dispatch the key to the policy but we will no
5555 // longer dispatch a fallback key to the application.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005556 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
5557 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005558#if DEBUG_OUTBOUND_EVENT_DETAILS
5559 if (fallback) {
5560 ALOGD("Unhandled key event: Policy requested to send key %d"
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005561 "as a fallback for %d, but on the DOWN it had requested "
5562 "to send %d instead. Fallback canceled.",
5563 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005564 } else {
5565 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005566 "but on the DOWN it had requested to send %d. "
5567 "Fallback canceled.",
5568 originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005569 }
5570#endif
5571
5572 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
5573 "canceling fallback, policy no longer desires it");
5574 options.keyCode = fallbackKeyCode;
5575 synthesizeCancelationEventsForConnectionLocked(connection, options);
5576
5577 fallback = false;
5578 fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005579 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005580 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005581 }
5582 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005583
5584#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005585 {
5586 std::string msg;
5587 const KeyedVector<int32_t, int32_t>& fallbackKeys =
5588 connection->inputState.getFallbackKeys();
5589 for (size_t i = 0; i < fallbackKeys.size(); i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005590 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005591 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005592 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005593 fallbackKeys.size(), msg.c_str());
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005594 }
5595#endif
5596
5597 if (fallback) {
5598 // Restart the dispatch cycle using the fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005599 keyEntry.eventTime = event.getEventTime();
5600 keyEntry.deviceId = event.getDeviceId();
5601 keyEntry.source = event.getSource();
5602 keyEntry.displayId = event.getDisplayId();
5603 keyEntry.flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
5604 keyEntry.keyCode = fallbackKeyCode;
5605 keyEntry.scanCode = event.getScanCode();
5606 keyEntry.metaState = event.getMetaState();
5607 keyEntry.repeatCount = event.getRepeatCount();
5608 keyEntry.downTime = event.getDownTime();
5609 keyEntry.syntheticRepeat = false;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005610
5611#if DEBUG_OUTBOUND_EVENT_DETAILS
5612 ALOGD("Unhandled key event: Dispatching fallback key. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005613 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005614 originalKeyCode, fallbackKeyCode, keyEntry.metaState);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005615#endif
5616 return true; // restart the event
5617 } else {
5618#if DEBUG_OUTBOUND_EVENT_DETAILS
5619 ALOGD("Unhandled key event: No fallback key.");
5620#endif
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005621
5622 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005623 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005624 }
5625 }
5626 return false;
5627}
5628
5629bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005630 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005631 MotionEntry& motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005632 return false;
5633}
5634
5635void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
5636 mLock.unlock();
5637
5638 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType);
5639
5640 mLock.lock();
5641}
5642
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07005643KeyEvent InputDispatcher::createKeyEvent(const KeyEntry& entry) {
5644 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08005645 event.initialize(entry.id, entry.deviceId, entry.source, entry.displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08005646 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
5647 entry.repeatCount, entry.downTime, entry.eventTime);
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07005648 return event;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005649}
5650
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07005651void InputDispatcher::reportDispatchStatistics(std::chrono::nanoseconds eventDuration,
5652 const Connection& connection, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005653 // TODO Write some statistics about how long we spend waiting.
5654}
5655
Siarhei Vishniakoude4bf152019-08-16 11:12:52 -05005656/**
5657 * Report the touch event latency to the statsd server.
5658 * Input events are reported for statistics if:
5659 * - This is a touchscreen event
5660 * - InputFilter is not enabled
5661 * - Event is not injected or synthesized
5662 *
5663 * Statistics should be reported before calling addValue, to prevent a fresh new sample
5664 * from getting aggregated with the "old" data.
5665 */
5666void InputDispatcher::reportTouchEventForStatistics(const MotionEntry& motionEntry)
5667 REQUIRES(mLock) {
5668 const bool reportForStatistics = (motionEntry.source == AINPUT_SOURCE_TOUCHSCREEN) &&
5669 !(motionEntry.isSynthesized()) && !mInputFilterEnabled;
5670 if (!reportForStatistics) {
5671 return;
5672 }
5673
5674 if (mTouchStatistics.shouldReport()) {
5675 android::util::stats_write(android::util::TOUCH_EVENT_REPORTED, mTouchStatistics.getMin(),
5676 mTouchStatistics.getMax(), mTouchStatistics.getMean(),
5677 mTouchStatistics.getStDev(), mTouchStatistics.getCount());
5678 mTouchStatistics.reset();
5679 }
5680 const float latencyMicros = nanoseconds_to_microseconds(now() - motionEntry.eventTime);
5681 mTouchStatistics.addValue(latencyMicros);
5682}
5683
Michael Wrightd02c5b62014-02-10 15:10:22 -08005684void InputDispatcher::traceInboundQueueLengthLocked() {
5685 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005686 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005687 }
5688}
5689
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08005690void InputDispatcher::traceOutboundQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005691 if (ATRACE_ENABLED()) {
5692 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08005693 snprintf(counterName, sizeof(counterName), "oq:%s", connection->getWindowName().c_str());
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005694 ATRACE_INT(counterName, connection->outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005695 }
5696}
5697
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08005698void InputDispatcher::traceWaitQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005699 if (ATRACE_ENABLED()) {
5700 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08005701 snprintf(counterName, sizeof(counterName), "wq:%s", connection->getWindowName().c_str());
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005702 ATRACE_INT(counterName, connection->waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005703 }
5704}
5705
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005706void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005707 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005708
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005709 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005710 dumpDispatchStateLocked(dump);
5711
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005712 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005713 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005714 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005715 }
5716}
5717
5718void InputDispatcher::monitor() {
5719 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005720 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005721 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005722 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005723}
5724
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08005725/**
5726 * Wake up the dispatcher and wait until it processes all events and commands.
5727 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
5728 * this method can be safely called from any thread, as long as you've ensured that
5729 * the work you are interested in completing has already been queued.
5730 */
5731bool InputDispatcher::waitForIdle() {
5732 /**
5733 * Timeout should represent the longest possible time that a device might spend processing
5734 * events and commands.
5735 */
5736 constexpr std::chrono::duration TIMEOUT = 100ms;
5737 std::unique_lock lock(mLock);
5738 mLooper->wake();
5739 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
5740 return result == std::cv_status::no_timeout;
5741}
5742
Vishnu Naire798b472020-07-23 13:52:21 -07005743/**
5744 * Sets focus to the window identified by the token. This must be called
5745 * after updating any input window handles.
5746 *
5747 * Params:
5748 * request.token - input channel token used to identify the window that should gain focus.
5749 * request.focusedToken - the token that the caller expects currently to be focused. If the
5750 * specified token does not match the currently focused window, this request will be dropped.
5751 * If the specified focused token matches the currently focused window, the call will succeed.
5752 * Set this to "null" if this call should succeed no matter what the currently focused token is.
5753 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
5754 * when requesting the focus change. This determines which request gets
5755 * precedence if there is a focus change request from another source such as pointer down.
5756 */
Vishnu Nair958da932020-08-21 17:12:37 -07005757void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
5758 { // acquire lock
5759 std::scoped_lock _l(mLock);
5760
5761 const int32_t displayId = request.displayId;
5762 const sp<IBinder> oldFocusedToken = getValueByKey(mFocusedWindowTokenByDisplay, displayId);
5763 if (request.focusedToken && oldFocusedToken != request.focusedToken) {
5764 ALOGD_IF(DEBUG_FOCUS,
5765 "setFocusedWindow on display %" PRId32
5766 " ignored, reason: focusedToken is not focused",
5767 displayId);
5768 return;
5769 }
5770
5771 mPendingFocusRequests.erase(displayId);
5772 FocusResult result = handleFocusRequestLocked(request);
5773 if (result == FocusResult::NOT_VISIBLE) {
5774 // The requested window is not currently visible. Wait for the window to become visible
5775 // and then provide it focus. This is to handle situations where a user action triggers
5776 // a new window to appear. We want to be able to queue any key events after the user
5777 // action and deliver it to the newly focused window. In order for this to happen, we
5778 // take focus from the currently focused window so key events can be queued.
5779 ALOGD_IF(DEBUG_FOCUS,
5780 "setFocusedWindow on display %" PRId32
5781 " pending, reason: window is not visible",
5782 displayId);
5783 mPendingFocusRequests[displayId] = request;
5784 onFocusChangedLocked(oldFocusedToken, nullptr, displayId,
5785 "setFocusedWindow_AwaitingWindowVisibility");
5786 } else if (result != FocusResult::OK) {
5787 ALOGW("setFocusedWindow on display %" PRId32 " ignored, reason:%s", displayId,
5788 typeToString(result));
5789 }
5790 } // release lock
5791 // Wake up poll loop since it may need to make new input dispatching choices.
5792 mLooper->wake();
5793}
5794
5795InputDispatcher::FocusResult InputDispatcher::handleFocusRequestLocked(
5796 const FocusRequest& request) {
5797 const int32_t displayId = request.displayId;
5798 const sp<IBinder> newFocusedToken = request.token;
5799 const sp<IBinder> oldFocusedToken = getValueByKey(mFocusedWindowTokenByDisplay, displayId);
5800
5801 if (oldFocusedToken == request.token) {
5802 ALOGD_IF(DEBUG_FOCUS,
5803 "setFocusedWindow on display %" PRId32 " ignored, reason: already focused",
5804 displayId);
5805 return FocusResult::OK;
5806 }
5807
5808 FocusResult result = checkTokenFocusableLocked(newFocusedToken, displayId);
5809 if (result != FocusResult::OK) {
5810 return result;
5811 }
5812
5813 std::string_view reason =
5814 (request.focusedToken) ? "setFocusedWindow_FocusCheck" : "setFocusedWindow";
5815 onFocusChangedLocked(oldFocusedToken, newFocusedToken, displayId, reason);
5816 return FocusResult::OK;
5817}
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005818
Vishnu Nairad321cd2020-08-20 16:40:21 -07005819void InputDispatcher::onFocusChangedLocked(const sp<IBinder>& oldFocusedToken,
5820 const sp<IBinder>& newFocusedToken, int32_t displayId,
5821 std::string_view reason) {
5822 if (oldFocusedToken) {
5823 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(oldFocusedToken);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005824 if (focusedInputChannel) {
5825 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
5826 "focus left window");
5827 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Vishnu Nairad321cd2020-08-20 16:40:21 -07005828 enqueueFocusEventLocked(oldFocusedToken, false /*hasFocus*/, reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005829 }
Vishnu Nairad321cd2020-08-20 16:40:21 -07005830 mFocusedWindowTokenByDisplay.erase(displayId);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005831 }
Vishnu Nairad321cd2020-08-20 16:40:21 -07005832 if (newFocusedToken) {
5833 mFocusedWindowTokenByDisplay[displayId] = newFocusedToken;
5834 enqueueFocusEventLocked(newFocusedToken, true /*hasFocus*/, reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005835 }
5836
Prabir Pradhan99987712020-11-10 18:43:05 -08005837 // If a window has pointer capture, then it must have focus. We need to ensure that this
5838 // contract is upheld when pointer capture is being disabled due to a loss of window focus.
5839 // If the window loses focus before it loses pointer capture, then the window can be in a state
5840 // where it has pointer capture but not focus, violating the contract. Therefore we must
5841 // dispatch the pointer capture event before the focus event. Since focus events are added to
5842 // the front of the queue (above), we add the pointer capture event to the front of the queue
5843 // after the focus events are added. This ensures the pointer capture event ends up at the
5844 // front.
5845 disablePointerCaptureForcedLocked();
5846
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005847 if (mFocusedDisplayId == displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005848 notifyFocusChangedLocked(oldFocusedToken, newFocusedToken);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005849 }
5850}
Vishnu Nair958da932020-08-21 17:12:37 -07005851
Prabir Pradhan99987712020-11-10 18:43:05 -08005852void InputDispatcher::disablePointerCaptureForcedLocked() {
5853 if (!mFocusedWindowRequestedPointerCapture && !mWindowTokenWithPointerCapture) {
5854 return;
5855 }
5856
5857 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
5858
5859 if (mFocusedWindowRequestedPointerCapture) {
5860 mFocusedWindowRequestedPointerCapture = false;
5861 setPointerCaptureLocked(false);
5862 }
5863
5864 if (!mWindowTokenWithPointerCapture) {
5865 // No need to send capture changes because no window has capture.
5866 return;
5867 }
5868
5869 if (mPendingEvent != nullptr) {
5870 // Move the pending event to the front of the queue. This will give the chance
5871 // for the pending event to be dropped if it is a captured event.
5872 mInboundQueue.push_front(mPendingEvent);
5873 mPendingEvent = nullptr;
5874 }
5875
5876 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
5877 false /* hasCapture */);
5878 mInboundQueue.push_front(std::move(entry));
5879}
5880
Vishnu Nair958da932020-08-21 17:12:37 -07005881/**
5882 * Checks if the window token can be focused on a display. The token can be focused if there is
5883 * at least one window handle that is visible with the same token and all window handles with the
5884 * same token are focusable.
5885 *
5886 * In the case of mirroring, two windows may share the same window token and their visibility
5887 * might be different. Example, the mirrored window can cover the window its mirroring. However,
5888 * we expect the focusability of the windows to match since its hard to reason why one window can
5889 * receive focus events and the other cannot when both are backed by the same input channel.
5890 */
5891InputDispatcher::FocusResult InputDispatcher::checkTokenFocusableLocked(const sp<IBinder>& token,
5892 int32_t displayId) const {
5893 bool allWindowsAreFocusable = true;
5894 bool visibleWindowFound = false;
5895 bool windowFound = false;
5896 for (const sp<InputWindowHandle>& window : getWindowHandlesLocked(displayId)) {
5897 if (window->getToken() != token) {
5898 continue;
5899 }
5900 windowFound = true;
5901 if (window->getInfo()->visible) {
5902 // Check if at least a single window is visible.
5903 visibleWindowFound = true;
5904 }
5905 if (!window->getInfo()->focusable) {
5906 // Check if all windows with the window token are focusable.
5907 allWindowsAreFocusable = false;
5908 break;
5909 }
5910 }
5911
5912 if (!windowFound) {
5913 return FocusResult::NO_WINDOW;
5914 }
5915 if (!allWindowsAreFocusable) {
5916 return FocusResult::NOT_FOCUSABLE;
5917 }
5918 if (!visibleWindowFound) {
5919 return FocusResult::NOT_VISIBLE;
5920 }
5921
5922 return FocusResult::OK;
5923}
Prabir Pradhan99987712020-11-10 18:43:05 -08005924
5925void InputDispatcher::setPointerCaptureLocked(bool enabled) {
5926 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5927 &InputDispatcher::doSetPointerCaptureLockedInterruptible);
5928 commandEntry->enabled = enabled;
5929 postCommandLocked(std::move(commandEntry));
5930}
5931
5932void InputDispatcher::doSetPointerCaptureLockedInterruptible(
5933 android::inputdispatcher::CommandEntry* commandEntry) {
5934 mLock.unlock();
5935
5936 mPolicy->setPointerCapture(commandEntry->enabled);
5937
5938 mLock.lock();
5939}
5940
Garfield Tane84e6f92019-08-29 17:28:41 -07005941} // namespace android::inputdispatcher