blob: f3d969e93f99789ec005a4081db2dab411c9b0a1 [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) {
yunho.shinf4a80b82020-11-16 21:13:57 +0900324 if (eventEntry->type == EventEntry::Type::MOTION) {
325 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
326 if (motionEntry.source & AINPUT_SOURCE_CLASS_JOYSTICK) {
327 const ui::Transform identityTransform;
328 // Use identity transform for joystick events events because they don't depend on
329 // the window info
330 return std::make_unique<DispatchEntry>(eventEntry, inputTargetFlags, identityTransform,
331 1.0f /*globalScaleFactor*/);
332 }
333 }
334
chaviw1ff3d1e2020-07-01 15:53:47 -0700335 if (inputTarget.useDefaultPointerTransform()) {
336 const ui::Transform& transform = inputTarget.getDefaultPointerTransform();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700337 return std::make_unique<DispatchEntry>(eventEntry, inputTargetFlags, transform,
chaviw1ff3d1e2020-07-01 15:53:47 -0700338 inputTarget.globalScaleFactor);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000339 }
340
341 ALOG_ASSERT(eventEntry->type == EventEntry::Type::MOTION);
342 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
343
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700344 std::vector<PointerCoords> pointerCoords;
345 pointerCoords.resize(motionEntry.pointerCount);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000346
347 // Use the first pointer information to normalize all other pointers. This could be any pointer
348 // as long as all other pointers are normalized to the same value and the final DispatchEntry
chaviw1ff3d1e2020-07-01 15:53:47 -0700349 // uses the transform for the normalized pointer.
350 const ui::Transform& firstPointerTransform =
351 inputTarget.pointerTransforms[inputTarget.pointerIds.firstMarkedBit()];
352 ui::Transform inverseFirstTransform = firstPointerTransform.inverse();
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000353
354 // Iterate through all pointers in the event to normalize against the first.
355 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.pointerCount; pointerIndex++) {
356 const PointerProperties& pointerProperties = motionEntry.pointerProperties[pointerIndex];
357 uint32_t pointerId = uint32_t(pointerProperties.id);
chaviw1ff3d1e2020-07-01 15:53:47 -0700358 const ui::Transform& currTransform = inputTarget.pointerTransforms[pointerId];
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000359
360 pointerCoords[pointerIndex].copyFrom(motionEntry.pointerCoords[pointerIndex]);
chaviw1ff3d1e2020-07-01 15:53:47 -0700361 // First, apply the current pointer's transform to update the coordinates into
362 // window space.
363 pointerCoords[pointerIndex].transform(currTransform);
364 // Next, apply the inverse transform of the normalized coordinates so the
365 // current coordinates are transformed into the normalized coordinate space.
366 pointerCoords[pointerIndex].transform(inverseFirstTransform);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000367 }
368
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700369 std::unique_ptr<MotionEntry> combinedMotionEntry =
370 std::make_unique<MotionEntry>(motionEntry.id, motionEntry.eventTime,
371 motionEntry.deviceId, motionEntry.source,
372 motionEntry.displayId, motionEntry.policyFlags,
373 motionEntry.action, motionEntry.actionButton,
374 motionEntry.flags, motionEntry.metaState,
375 motionEntry.buttonState, motionEntry.classification,
376 motionEntry.edgeFlags, motionEntry.xPrecision,
377 motionEntry.yPrecision, motionEntry.xCursorPosition,
378 motionEntry.yCursorPosition, motionEntry.downTime,
379 motionEntry.pointerCount, motionEntry.pointerProperties,
380 pointerCoords.data(), 0 /* xOffset */, 0 /* yOffset */);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000381
382 if (motionEntry.injectionState) {
383 combinedMotionEntry->injectionState = motionEntry.injectionState;
384 combinedMotionEntry->injectionState->refCount += 1;
385 }
386
387 std::unique_ptr<DispatchEntry> dispatchEntry =
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700388 std::make_unique<DispatchEntry>(std::move(combinedMotionEntry), inputTargetFlags,
389 firstPointerTransform, inputTarget.globalScaleFactor);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000390 return dispatchEntry;
391}
392
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -0700393static void addGestureMonitors(const std::vector<Monitor>& monitors,
394 std::vector<TouchedMonitor>& outTouchedMonitors, float xOffset = 0,
395 float yOffset = 0) {
396 if (monitors.empty()) {
397 return;
398 }
399 outTouchedMonitors.reserve(monitors.size() + outTouchedMonitors.size());
400 for (const Monitor& monitor : monitors) {
401 outTouchedMonitors.emplace_back(monitor, xOffset, yOffset);
402 }
403}
404
Garfield Tan15601662020-09-22 15:32:38 -0700405static status_t openInputChannelPair(const std::string& name,
406 std::shared_ptr<InputChannel>& serverChannel,
407 std::unique_ptr<InputChannel>& clientChannel) {
408 std::unique_ptr<InputChannel> uniqueServerChannel;
409 status_t result = InputChannel::openInputChannelPair(name, uniqueServerChannel, clientChannel);
410
411 serverChannel = std::move(uniqueServerChannel);
412 return result;
413}
414
Vishnu Nair958da932020-08-21 17:12:37 -0700415const char* InputDispatcher::typeToString(InputDispatcher::FocusResult result) {
416 switch (result) {
417 case InputDispatcher::FocusResult::OK:
418 return "Ok";
419 case InputDispatcher::FocusResult::NO_WINDOW:
420 return "Window not found";
421 case InputDispatcher::FocusResult::NOT_FOCUSABLE:
422 return "Window not focusable";
423 case InputDispatcher::FocusResult::NOT_VISIBLE:
424 return "Window not visible";
425 }
426}
427
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500428template <typename T>
429static bool sharedPointersEqual(const std::shared_ptr<T>& lhs, const std::shared_ptr<T>& rhs) {
430 if (lhs == nullptr && rhs == nullptr) {
431 return true;
432 }
433 if (lhs == nullptr || rhs == nullptr) {
434 return false;
435 }
436 return *lhs == *rhs;
437}
438
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000439static sp<IPlatformCompatNative> getCompatService() {
440 sp<IBinder> service(defaultServiceManager()->getService(String16("platform_compat_native")));
441 if (service == nullptr) {
442 ALOGE("Failed to link to compat service");
443 return nullptr;
444 }
445 return interface_cast<IPlatformCompatNative>(service);
446}
447
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +0000448static KeyEvent createKeyEvent(const KeyEntry& entry) {
449 KeyEvent event;
450 event.initialize(entry.id, entry.deviceId, entry.source, entry.displayId, INVALID_HMAC,
451 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
452 entry.repeatCount, entry.downTime, entry.eventTime);
453 return event;
454}
455
Michael Wrightd02c5b62014-02-10 15:10:22 -0800456// --- InputDispatcher ---
457
Garfield Tan00f511d2019-06-12 16:55:40 -0700458InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy)
459 : mPolicy(policy),
460 mPendingEvent(nullptr),
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700461 mLastDropReason(DropReason::NOT_DROPPED),
Garfield Tanff1f1bb2020-01-28 13:24:04 -0800462 mIdGenerator(IdGenerator::Source::INPUT_DISPATCHER),
Garfield Tan00f511d2019-06-12 16:55:40 -0700463 mAppSwitchSawKeyDown(false),
464 mAppSwitchDueTime(LONG_LONG_MAX),
465 mNextUnblockedEvent(nullptr),
466 mDispatchEnabled(false),
467 mDispatchFrozen(false),
468 mInputFilterEnabled(false),
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -0800469 // mInTouchMode will be initialized by the WindowManager to the default device config.
470 // To avoid leaking stack in case that call never comes, and for tests,
471 // initialize it here anyways.
472 mInTouchMode(true),
Bernardo Rufinoea97d182020-08-19 14:43:14 +0100473 mMaximumObscuringOpacityForTouch(1.0f),
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000474 mFocusedDisplayId(ADISPLAY_ID_DEFAULT),
Prabir Pradhan99987712020-11-10 18:43:05 -0800475 mFocusedWindowRequestedPointerCapture(false),
476 mWindowTokenWithPointerCapture(nullptr),
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000477 mCompatService(getCompatService()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800478 mLooper = new Looper(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800479 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800480
Yi Kong9b14ac62018-07-17 13:48:38 -0700481 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800482
483 policy->getDispatcherConfiguration(&mConfig);
484}
485
486InputDispatcher::~InputDispatcher() {
487 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800488 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800489
490 resetKeyRepeatLocked();
491 releasePendingEventLocked();
492 drainInboundQueueLocked();
493 }
494
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700495 while (!mConnectionsByFd.empty()) {
496 sp<Connection> connection = mConnectionsByFd.begin()->second;
Garfield Tan15601662020-09-22 15:32:38 -0700497 removeInputChannel(connection->inputChannel->getConnectionToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800498 }
499}
500
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700501status_t InputDispatcher::start() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700502 if (mThread) {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700503 return ALREADY_EXISTS;
504 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700505 mThread = std::make_unique<InputThread>(
506 "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
507 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700508}
509
510status_t InputDispatcher::stop() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700511 if (mThread && mThread->isCallingThread()) {
512 ALOGE("InputDispatcher cannot be stopped from its own thread!");
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700513 return INVALID_OPERATION;
514 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700515 mThread.reset();
516 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700517}
518
Michael Wrightd02c5b62014-02-10 15:10:22 -0800519void InputDispatcher::dispatchOnce() {
520 nsecs_t nextWakeupTime = LONG_LONG_MAX;
521 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800522 std::scoped_lock _l(mLock);
523 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800524
525 // Run a dispatch loop if there are no pending commands.
526 // The dispatch loop might enqueue commands to run afterwards.
527 if (!haveCommandsLocked()) {
528 dispatchOnceInnerLocked(&nextWakeupTime);
529 }
530
531 // Run all pending commands if there are any.
532 // If any commands were run then force the next poll to wake up immediately.
533 if (runCommandsLockedInterruptible()) {
534 nextWakeupTime = LONG_LONG_MIN;
535 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800536
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700537 // If we are still waiting for ack on some events,
538 // we might have to wake up earlier to check if an app is anr'ing.
539 const nsecs_t nextAnrCheck = processAnrsLocked();
540 nextWakeupTime = std::min(nextWakeupTime, nextAnrCheck);
541
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800542 // We are about to enter an infinitely long sleep, because we have no commands or
543 // pending or queued events
544 if (nextWakeupTime == LONG_LONG_MAX) {
545 mDispatcherEnteredIdle.notify_all();
546 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800547 } // release lock
548
549 // Wait for callback or timeout or wake. (make sure we round up, not down)
550 nsecs_t currentTime = now();
551 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
552 mLooper->pollOnce(timeoutMillis);
553}
554
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700555/**
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500556 * Raise ANR if there is no focused window.
557 * Before the ANR is raised, do a final state check:
558 * 1. The currently focused application must be the same one we are waiting for.
559 * 2. Ensure we still don't have a focused window.
560 */
561void InputDispatcher::processNoFocusedWindowAnrLocked() {
562 // Check if the application that we are waiting for is still focused.
563 std::shared_ptr<InputApplicationHandle> focusedApplication =
564 getValueByKey(mFocusedApplicationHandlesByDisplay, mAwaitedApplicationDisplayId);
565 if (focusedApplication == nullptr ||
566 focusedApplication->getApplicationToken() !=
567 mAwaitedFocusedApplication->getApplicationToken()) {
568 // Unexpected because we should have reset the ANR timer when focused application changed
569 ALOGE("Waited for a focused window, but focused application has already changed to %s",
570 focusedApplication->getName().c_str());
571 return; // The focused application has changed.
572 }
573
574 const sp<InputWindowHandle>& focusedWindowHandle =
575 getFocusedWindowHandleLocked(mAwaitedApplicationDisplayId);
576 if (focusedWindowHandle != nullptr) {
577 return; // We now have a focused window. No need for ANR.
578 }
579 onAnrLocked(mAwaitedFocusedApplication);
580}
581
582/**
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700583 * Check if any of the connections' wait queues have events that are too old.
584 * If we waited for events to be ack'ed for more than the window timeout, raise an ANR.
585 * Return the time at which we should wake up next.
586 */
587nsecs_t InputDispatcher::processAnrsLocked() {
588 const nsecs_t currentTime = now();
589 nsecs_t nextAnrCheck = LONG_LONG_MAX;
590 // Check if we are waiting for a focused window to appear. Raise ANR if waited too long
591 if (mNoFocusedWindowTimeoutTime.has_value() && mAwaitedFocusedApplication != nullptr) {
592 if (currentTime >= *mNoFocusedWindowTimeoutTime) {
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500593 processNoFocusedWindowAnrLocked();
Chris Yea209fde2020-07-22 13:54:51 -0700594 mAwaitedFocusedApplication.reset();
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500595 mNoFocusedWindowTimeoutTime = std::nullopt;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700596 return LONG_LONG_MIN;
597 } else {
Siarhei Vishniakou38a6d272020-10-20 20:29:33 -0500598 // Keep waiting. We will drop the event when mNoFocusedWindowTimeoutTime comes.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700599 nextAnrCheck = *mNoFocusedWindowTimeoutTime;
600 }
601 }
602
603 // Check if any connection ANRs are due
604 nextAnrCheck = std::min(nextAnrCheck, mAnrTracker.firstTimeout());
605 if (currentTime < nextAnrCheck) { // most likely scenario
606 return nextAnrCheck; // everything is normal. Let's check again at nextAnrCheck
607 }
608
609 // If we reached here, we have an unresponsive connection.
610 sp<Connection> connection = getConnectionLocked(mAnrTracker.firstToken());
611 if (connection == nullptr) {
612 ALOGE("Could not find connection for entry %" PRId64, mAnrTracker.firstTimeout());
613 return nextAnrCheck;
614 }
615 connection->responsive = false;
616 // Stop waking up for this unresponsive connection
617 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -0500618 onAnrLocked(*connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700619 return LONG_LONG_MIN;
620}
621
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500622std::chrono::nanoseconds InputDispatcher::getDispatchingTimeoutLocked(const sp<IBinder>& token) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700623 sp<InputWindowHandle> window = getWindowHandleLocked(token);
624 if (window != nullptr) {
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500625 return window->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700626 }
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500627 return DEFAULT_INPUT_DISPATCHING_TIMEOUT;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700628}
629
Michael Wrightd02c5b62014-02-10 15:10:22 -0800630void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
631 nsecs_t currentTime = now();
632
Jeff Browndc5992e2014-04-11 01:27:26 -0700633 // Reset the key repeat timer whenever normal dispatch is suspended while the
634 // device is in a non-interactive state. This is to ensure that we abort a key
635 // repeat if the device is just coming out of sleep.
636 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800637 resetKeyRepeatLocked();
638 }
639
640 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
641 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +0100642 if (DEBUG_FOCUS) {
643 ALOGD("Dispatch frozen. Waiting some more.");
644 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800645 return;
646 }
647
648 // Optimize latency of app switches.
649 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
650 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
651 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
652 if (mAppSwitchDueTime < *nextWakeupTime) {
653 *nextWakeupTime = mAppSwitchDueTime;
654 }
655
656 // Ready to start a new event.
657 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700658 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700659 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800660 if (isAppSwitchDue) {
661 // The inbound queue is empty so the app switch key we were waiting
662 // for will never arrive. Stop waiting for it.
663 resetPendingAppSwitchLocked(false);
664 isAppSwitchDue = false;
665 }
666
667 // Synthesize a key repeat if appropriate.
668 if (mKeyRepeatState.lastKeyEntry) {
669 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
670 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
671 } else {
672 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
673 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
674 }
675 }
676 }
677
678 // Nothing to do if there is no pending event.
679 if (!mPendingEvent) {
680 return;
681 }
682 } else {
683 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700684 mPendingEvent = mInboundQueue.front();
685 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800686 traceInboundQueueLengthLocked();
687 }
688
689 // Poke user activity for this event.
690 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700691 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800692 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800693 }
694
695 // Now we have an event to dispatch.
696 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700697 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800698 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700699 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800700 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700701 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800702 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700703 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800704 }
705
706 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700707 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800708 }
709
710 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700711 case EventEntry::Type::CONFIGURATION_CHANGED: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700712 const ConfigurationChangedEntry& typedEntry =
713 static_cast<const ConfigurationChangedEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700714 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700715 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700716 break;
717 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800718
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700719 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700720 const DeviceResetEntry& typedEntry =
721 static_cast<const DeviceResetEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700722 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700723 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700724 break;
725 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800726
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100727 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700728 std::shared_ptr<FocusEntry> typedEntry =
729 std::static_pointer_cast<FocusEntry>(mPendingEvent);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100730 dispatchFocusLocked(currentTime, typedEntry);
731 done = true;
732 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
733 break;
734 }
735
Prabir Pradhan99987712020-11-10 18:43:05 -0800736 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
737 const auto typedEntry =
738 std::static_pointer_cast<PointerCaptureChangedEntry>(mPendingEvent);
739 dispatchPointerCaptureChangedLocked(currentTime, typedEntry, dropReason);
740 done = true;
741 break;
742 }
743
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700744 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700745 std::shared_ptr<KeyEntry> keyEntry = std::static_pointer_cast<KeyEntry>(mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700746 if (isAppSwitchDue) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700747 if (isAppSwitchKeyEvent(*keyEntry)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700748 resetPendingAppSwitchLocked(true);
749 isAppSwitchDue = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700750 } else if (dropReason == DropReason::NOT_DROPPED) {
751 dropReason = DropReason::APP_SWITCH;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700752 }
753 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700754 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *keyEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700755 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700756 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700757 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
758 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700759 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700760 done = dispatchKeyLocked(currentTime, keyEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700761 break;
762 }
763
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700764 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700765 std::shared_ptr<MotionEntry> motionEntry =
766 std::static_pointer_cast<MotionEntry>(mPendingEvent);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700767 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
768 dropReason = DropReason::APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800769 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700770 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *motionEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700771 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700772 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700773 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
774 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700775 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700776 done = dispatchMotionLocked(currentTime, motionEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700777 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800778 }
Chris Yef59a2f42020-10-16 12:55:26 -0700779
780 case EventEntry::Type::SENSOR: {
781 std::shared_ptr<SensorEntry> sensorEntry =
782 std::static_pointer_cast<SensorEntry>(mPendingEvent);
783 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
784 dropReason = DropReason::APP_SWITCH;
785 }
786 // Sensor timestamps use SYSTEM_TIME_BOOTTIME time base, so we can't use
787 // 'currentTime' here, get SYSTEM_TIME_BOOTTIME instead.
788 nsecs_t bootTime = systemTime(SYSTEM_TIME_BOOTTIME);
789 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(bootTime, *sensorEntry)) {
790 dropReason = DropReason::STALE;
791 }
792 dispatchSensorLocked(currentTime, sensorEntry, &dropReason, nextWakeupTime);
793 done = true;
794 break;
795 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800796 }
797
798 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700799 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700800 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800801 }
Michael Wright3a981722015-06-10 15:26:13 +0100802 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800803
804 releasePendingEventLocked();
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700805 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -0800806 }
807}
808
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700809/**
810 * Return true if the events preceding this incoming motion event should be dropped
811 * Return false otherwise (the default behaviour)
812 */
813bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700814 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700815 (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700816
817 // Optimize case where the current application is unresponsive and the user
818 // decides to touch a window in a different application.
819 // If the application takes too long to catch up then we drop all events preceding
820 // the touch into the other window.
821 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700822 int32_t displayId = motionEntry.displayId;
823 int32_t x = static_cast<int32_t>(
824 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
825 int32_t y = static_cast<int32_t>(
826 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
827 sp<InputWindowHandle> touchedWindowHandle =
828 findTouchedWindowAtLocked(displayId, x, y, nullptr);
829 if (touchedWindowHandle != nullptr &&
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700830 touchedWindowHandle->getApplicationToken() !=
831 mAwaitedFocusedApplication->getApplicationToken()) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700832 // User touched a different application than the one we are waiting on.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700833 ALOGI("Pruning input queue because user touched a different application while waiting "
834 "for %s",
835 mAwaitedFocusedApplication->getName().c_str());
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700836 return true;
837 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700838
839 // Alternatively, maybe there's a gesture monitor that could handle this event
840 std::vector<TouchedMonitor> gestureMonitors =
841 findTouchedGestureMonitorsLocked(displayId, {});
842 for (TouchedMonitor& gestureMonitor : gestureMonitors) {
843 sp<Connection> connection =
844 getConnectionLocked(gestureMonitor.monitor.inputChannel->getConnectionToken());
Siarhei Vishniakou34ed4d42020-06-18 00:43:02 +0000845 if (connection != nullptr && connection->responsive) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700846 // This monitor could take more input. Drop all events preceding this
847 // event, so that gesture monitor could get a chance to receive the stream
848 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
849 "responsive gesture monitor that may handle the event",
850 mAwaitedFocusedApplication->getName().c_str());
851 return true;
852 }
853 }
854 }
855
856 // Prevent getting stuck: if we have a pending key event, and some motion events that have not
857 // yet been processed by some connections, the dispatcher will wait for these motion
858 // events to be processed before dispatching the key event. This is because these motion events
859 // may cause a new window to be launched, which the user might expect to receive focus.
860 // To prevent waiting forever for such events, just send the key to the currently focused window
861 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
862 ALOGD("Received a new pointer down event, stop waiting for events to process and "
863 "just send the pending key event to the focused window.");
864 mKeyIsWaitingForEventsTimeout = now();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700865 }
866 return false;
867}
868
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700869bool InputDispatcher::enqueueInboundEventLocked(std::unique_ptr<EventEntry> newEntry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700870 bool needWake = mInboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700871 mInboundQueue.push_back(std::move(newEntry));
872 EventEntry& entry = *(mInboundQueue.back());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800873 traceInboundQueueLengthLocked();
874
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700875 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700876 case EventEntry::Type::KEY: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700877 // Optimize app switch latency.
878 // If the application takes too long to catch up then we drop all events preceding
879 // the app switch key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700880 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700881 if (isAppSwitchKeyEvent(keyEntry)) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700882 if (keyEntry.action == AKEY_EVENT_ACTION_DOWN) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700883 mAppSwitchSawKeyDown = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700884 } else if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700885 if (mAppSwitchSawKeyDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800886#if DEBUG_APP_SWITCH
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700887 ALOGD("App switch is pending!");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800888#endif
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700889 mAppSwitchDueTime = keyEntry.eventTime + APP_SWITCH_TIMEOUT;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700890 mAppSwitchSawKeyDown = false;
891 needWake = true;
892 }
893 }
894 }
895 break;
896 }
897
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700898 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700899 if (shouldPruneInboundQueueLocked(static_cast<MotionEntry&>(entry))) {
900 mNextUnblockedEvent = mInboundQueue.back();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700901 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800902 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700903 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800904 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100905 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700906 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
907 break;
908 }
909 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -0800910 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -0700911 case EventEntry::Type::SENSOR:
Prabir Pradhan99987712020-11-10 18:43:05 -0800912 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700913 // nothing to do
914 break;
915 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800916 }
917
918 return needWake;
919}
920
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700921void InputDispatcher::addRecentEventLocked(std::shared_ptr<EventEntry> entry) {
Chris Yef59a2f42020-10-16 12:55:26 -0700922 // Do not store sensor event in recent queue to avoid flooding the queue.
923 if (entry->type != EventEntry::Type::SENSOR) {
924 mRecentQueue.push_back(entry);
925 }
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700926 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700927 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800928 }
929}
930
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700931sp<InputWindowHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, int32_t x,
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700932 int32_t y, TouchState* touchState,
933 bool addOutsideTargets,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700934 bool addPortalWindows) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700935 if ((addPortalWindows || addOutsideTargets) && touchState == nullptr) {
936 LOG_ALWAYS_FATAL(
937 "Must provide a valid touch state if adding portal windows or outside targets");
938 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800939 // Traverse windows from front to back to find touched window.
Vishnu Nairad321cd2020-08-20 16:40:21 -0700940 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800941 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800942 const InputWindowInfo* windowInfo = windowHandle->getInfo();
943 if (windowInfo->displayId == displayId) {
Michael Wright44753b12020-07-08 13:48:11 +0100944 auto flags = windowInfo->flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800945
946 if (windowInfo->visible) {
Michael Wright44753b12020-07-08 13:48:11 +0100947 if (!flags.test(InputWindowInfo::Flag::NOT_TOUCHABLE)) {
948 bool isTouchModal = !flags.test(InputWindowInfo::Flag::NOT_FOCUSABLE) &&
949 !flags.test(InputWindowInfo::Flag::NOT_TOUCH_MODAL);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800950 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800951 int32_t portalToDisplayId = windowInfo->portalToDisplayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700952 if (portalToDisplayId != ADISPLAY_ID_NONE &&
953 portalToDisplayId != displayId) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800954 if (addPortalWindows) {
955 // For the monitoring channels of the display.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700956 touchState->addPortalWindow(windowHandle);
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800957 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700958 return findTouchedWindowAtLocked(portalToDisplayId, x, y, touchState,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700959 addOutsideTargets, addPortalWindows);
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800960 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800961 // Found window.
962 return windowHandle;
963 }
964 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800965
Michael Wright44753b12020-07-08 13:48:11 +0100966 if (addOutsideTargets && flags.test(InputWindowInfo::Flag::WATCH_OUTSIDE_TOUCH)) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700967 touchState->addOrUpdateWindow(windowHandle,
968 InputTarget::FLAG_DISPATCH_AS_OUTSIDE,
969 BitSet32(0));
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800970 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800971 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800972 }
973 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700974 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800975}
976
Garfield Tane84e6f92019-08-29 17:28:41 -0700977std::vector<TouchedMonitor> InputDispatcher::findTouchedGestureMonitorsLocked(
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -0700978 int32_t displayId, const std::vector<sp<InputWindowHandle>>& portalWindows) const {
Michael Wright3dd60e22019-03-27 22:06:44 +0000979 std::vector<TouchedMonitor> touchedMonitors;
980
981 std::vector<Monitor> monitors = getValueByKey(mGestureMonitorsByDisplay, displayId);
982 addGestureMonitors(monitors, touchedMonitors);
983 for (const sp<InputWindowHandle>& portalWindow : portalWindows) {
984 const InputWindowInfo* windowInfo = portalWindow->getInfo();
985 monitors = getValueByKey(mGestureMonitorsByDisplay, windowInfo->portalToDisplayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700986 addGestureMonitors(monitors, touchedMonitors, -windowInfo->frameLeft,
987 -windowInfo->frameTop);
Michael Wright3dd60e22019-03-27 22:06:44 +0000988 }
989 return touchedMonitors;
990}
991
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700992void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800993 const char* reason;
994 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700995 case DropReason::POLICY:
Michael Wrightd02c5b62014-02-10 15:10:22 -0800996#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700997 ALOGD("Dropped event because policy consumed it.");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800998#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700999 reason = "inbound event was dropped because the policy consumed it";
1000 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001001 case DropReason::DISABLED:
1002 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001003 ALOGI("Dropped event because input dispatch is disabled.");
1004 }
1005 reason = "inbound event was dropped because input dispatch is disabled";
1006 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001007 case DropReason::APP_SWITCH:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001008 ALOGI("Dropped event because of pending overdue app switch.");
1009 reason = "inbound event was dropped because of pending overdue app switch";
1010 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001011 case DropReason::BLOCKED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001012 ALOGI("Dropped event because the current application is not responding and the user "
1013 "has started interacting with a different application.");
1014 reason = "inbound event was dropped because the current application is not responding "
1015 "and the user has started interacting with a different application";
1016 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001017 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001018 ALOGI("Dropped event because it is stale.");
1019 reason = "inbound event was dropped because it is stale";
1020 break;
Prabir Pradhan99987712020-11-10 18:43:05 -08001021 case DropReason::NO_POINTER_CAPTURE:
1022 ALOGI("Dropped event because there is no window with Pointer Capture.");
1023 reason = "inbound event was dropped because there is no window with Pointer Capture";
1024 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001025 case DropReason::NOT_DROPPED: {
1026 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001027 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001028 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001029 }
1030
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001031 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001032 case EventEntry::Type::KEY: {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001033 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
1034 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001035 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001036 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001037 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001038 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1039 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001040 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
1041 synthesizeCancelationEventsForAllConnectionsLocked(options);
1042 } else {
1043 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
1044 synthesizeCancelationEventsForAllConnectionsLocked(options);
1045 }
1046 break;
1047 }
Chris Yef59a2f42020-10-16 12:55:26 -07001048 case EventEntry::Type::SENSOR: {
1049 break;
1050 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001051 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
1052 break;
1053 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001054 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001055 case EventEntry::Type::CONFIGURATION_CHANGED:
1056 case EventEntry::Type::DEVICE_RESET: {
Chris Yef59a2f42020-10-16 12:55:26 -07001057 LOG_ALWAYS_FATAL("Should not drop %s events", NamedEnum::string(entry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001058 break;
1059 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001060 }
1061}
1062
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001063static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001064 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
1065 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001066}
1067
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001068bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
1069 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
1070 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
1071 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001072}
1073
1074bool InputDispatcher::isAppSwitchPendingLocked() {
1075 return mAppSwitchDueTime != LONG_LONG_MAX;
1076}
1077
1078void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
1079 mAppSwitchDueTime = LONG_LONG_MAX;
1080
1081#if DEBUG_APP_SWITCH
1082 if (handled) {
1083 ALOGD("App switch has arrived.");
1084 } else {
1085 ALOGD("App switch was abandoned.");
1086 }
1087#endif
1088}
1089
Michael Wrightd02c5b62014-02-10 15:10:22 -08001090bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001091 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001092}
1093
1094bool InputDispatcher::runCommandsLockedInterruptible() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001095 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001096 return false;
1097 }
1098
1099 do {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001100 std::unique_ptr<CommandEntry> commandEntry = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001101 mCommandQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001102 Command command = commandEntry->command;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001103 command(*this, commandEntry.get()); // commands are implicitly 'LockedInterruptible'
Michael Wrightd02c5b62014-02-10 15:10:22 -08001104
1105 commandEntry->connection.clear();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001106 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001107 return true;
1108}
1109
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001110void InputDispatcher::postCommandLocked(std::unique_ptr<CommandEntry> commandEntry) {
1111 mCommandQueue.push_back(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001112}
1113
1114void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001115 while (!mInboundQueue.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001116 std::shared_ptr<EventEntry> entry = mInboundQueue.front();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001117 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001118 releaseInboundEventLocked(entry);
1119 }
1120 traceInboundQueueLengthLocked();
1121}
1122
1123void InputDispatcher::releasePendingEventLocked() {
1124 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001125 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -07001126 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001127 }
1128}
1129
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001130void InputDispatcher::releaseInboundEventLocked(std::shared_ptr<EventEntry> entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001131 InjectionState* injectionState = entry->injectionState;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001132 if (injectionState && injectionState->injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001133#if DEBUG_DISPATCH_CYCLE
1134 ALOGD("Injected inbound event was dropped.");
1135#endif
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001136 setInjectionResult(*entry, InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001137 }
1138 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001139 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001140 }
1141 addRecentEventLocked(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001142}
1143
1144void InputDispatcher::resetKeyRepeatLocked() {
1145 if (mKeyRepeatState.lastKeyEntry) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001146 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001147 }
1148}
1149
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001150std::shared_ptr<KeyEntry> InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
1151 std::shared_ptr<KeyEntry> entry = mKeyRepeatState.lastKeyEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001152
Michael Wright2e732952014-09-24 13:26:59 -07001153 uint32_t policyFlags = entry->policyFlags &
1154 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001155
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001156 std::shared_ptr<KeyEntry> newEntry =
1157 std::make_unique<KeyEntry>(mIdGenerator.nextId(), currentTime, entry->deviceId,
1158 entry->source, entry->displayId, policyFlags, entry->action,
1159 entry->flags, entry->keyCode, entry->scanCode,
1160 entry->metaState, entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001161
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001162 newEntry->syntheticRepeat = true;
1163 mKeyRepeatState.lastKeyEntry = newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001164 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001165 return newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001166}
1167
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001168bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001169 const ConfigurationChangedEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001170#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001171 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry.eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001172#endif
1173
1174 // Reset key repeating in case a keyboard device was added or removed or something.
1175 resetKeyRepeatLocked();
1176
1177 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001178 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
1179 &InputDispatcher::doNotifyConfigurationChangedLockedInterruptible);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001180 commandEntry->eventTime = entry.eventTime;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001181 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001182 return true;
1183}
1184
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001185bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime,
1186 const DeviceResetEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001187#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001188 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry.eventTime,
1189 entry.deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001190#endif
1191
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001192 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, "device was reset");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001193 options.deviceId = entry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001194 synthesizeCancelationEventsForAllConnectionsLocked(options);
1195 return true;
1196}
1197
Vishnu Nairad321cd2020-08-20 16:40:21 -07001198void InputDispatcher::enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus,
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001199 std::string_view reason) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001200 if (mPendingEvent != nullptr) {
1201 // Move the pending event to the front of the queue. This will give the chance
1202 // for the pending event to get dispatched to the newly focused window
1203 mInboundQueue.push_front(mPendingEvent);
1204 mPendingEvent = nullptr;
1205 }
1206
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001207 std::unique_ptr<FocusEntry> focusEntry =
1208 std::make_unique<FocusEntry>(mIdGenerator.nextId(), now(), windowToken, hasFocus,
1209 reason);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001210
1211 // This event should go to the front of the queue, but behind all other focus events
1212 // Find the last focus event, and insert right after it
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001213 std::deque<std::shared_ptr<EventEntry>>::reverse_iterator it =
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001214 std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001215 [](const std::shared_ptr<EventEntry>& event) {
1216 return event->type == EventEntry::Type::FOCUS;
1217 });
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001218
1219 // Maintain the order of focus events. Insert the entry after all other focus events.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001220 mInboundQueue.insert(it.base(), std::move(focusEntry));
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001221}
1222
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001223void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime, std::shared_ptr<FocusEntry> entry) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05001224 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001225 if (channel == nullptr) {
1226 return; // Window has gone away
1227 }
1228 InputTarget target;
1229 target.inputChannel = channel;
1230 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1231 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001232 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
1233 channel->getName();
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001234 std::string reason = std::string("reason=").append(entry->reason);
1235 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001236 dispatchEventLocked(currentTime, entry, {target});
1237}
1238
Prabir Pradhan99987712020-11-10 18:43:05 -08001239void InputDispatcher::dispatchPointerCaptureChangedLocked(
1240 nsecs_t currentTime, const std::shared_ptr<PointerCaptureChangedEntry>& entry,
1241 DropReason& dropReason) {
1242 const bool haveWindowWithPointerCapture = mWindowTokenWithPointerCapture != nullptr;
1243 if (entry->pointerCaptureEnabled == haveWindowWithPointerCapture) {
1244 LOG_ALWAYS_FATAL_IF(mFocusedWindowRequestedPointerCapture,
1245 "The Pointer Capture state has already been dispatched to the window.");
1246 // Pointer capture was already forcefully disabled because of focus change.
1247 dropReason = DropReason::NOT_DROPPED;
1248 return;
1249 }
1250
1251 // Set drop reason for early returns
1252 dropReason = DropReason::NO_POINTER_CAPTURE;
1253
1254 sp<IBinder> token;
1255 if (entry->pointerCaptureEnabled) {
1256 // Enable Pointer Capture
1257 if (!mFocusedWindowRequestedPointerCapture) {
1258 // This can happen if a window requests capture and immediately releases capture.
1259 ALOGW("No window requested Pointer Capture.");
1260 return;
1261 }
1262 token = getValueByKey(mFocusedWindowTokenByDisplay, mFocusedDisplayId);
1263 LOG_ALWAYS_FATAL_IF(!token, "Cannot find focused window for Pointer Capture.");
1264 mWindowTokenWithPointerCapture = token;
1265 } else {
1266 // Disable Pointer Capture
1267 token = mWindowTokenWithPointerCapture;
1268 mWindowTokenWithPointerCapture = nullptr;
1269 mFocusedWindowRequestedPointerCapture = false;
1270 }
1271
1272 auto channel = getInputChannelLocked(token);
1273 if (channel == nullptr) {
1274 // Window has gone away, clean up Pointer Capture state.
1275 mWindowTokenWithPointerCapture = nullptr;
1276 mFocusedWindowRequestedPointerCapture = false;
1277 return;
1278 }
1279 InputTarget target;
1280 target.inputChannel = channel;
1281 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1282 entry->dispatchInProgress = true;
1283 dispatchEventLocked(currentTime, entry, {target});
1284
1285 dropReason = DropReason::NOT_DROPPED;
1286}
1287
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001288bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, std::shared_ptr<KeyEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001289 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001290 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001291 if (!entry->dispatchInProgress) {
1292 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1293 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1294 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1295 if (mKeyRepeatState.lastKeyEntry &&
Chris Ye2ad95392020-09-01 13:44:44 -07001296 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode &&
Michael Wrightd02c5b62014-02-10 15:10:22 -08001297 // We have seen two identical key downs in a row which indicates that the device
1298 // driver is automatically generating key repeats itself. We take note of the
1299 // repeat here, but we disable our own next key repeat timer since it is clear that
1300 // we will not need to synthesize key repeats ourselves.
Chris Ye2ad95392020-09-01 13:44:44 -07001301 mKeyRepeatState.lastKeyEntry->deviceId == entry->deviceId) {
1302 // Make sure we don't get key down from a different device. If a different
1303 // device Id has same key pressed down, the new device Id will replace the
1304 // current one to hold the key repeat with repeat count reset.
1305 // In the future when got a KEY_UP on the device id, drop it and do not
1306 // stop the key repeat on current device.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001307 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1308 resetKeyRepeatLocked();
1309 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
1310 } else {
1311 // Not a repeat. Save key down state in case we do see a repeat later.
1312 resetKeyRepeatLocked();
1313 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1314 }
1315 mKeyRepeatState.lastKeyEntry = entry;
Chris Ye2ad95392020-09-01 13:44:44 -07001316 } else if (entry->action == AKEY_EVENT_ACTION_UP && mKeyRepeatState.lastKeyEntry &&
1317 mKeyRepeatState.lastKeyEntry->deviceId != entry->deviceId) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001318 // The key on device 'deviceId' is still down, do not stop key repeat
Chris Ye2ad95392020-09-01 13:44:44 -07001319#if DEBUG_INBOUND_EVENT_DETAILS
1320 ALOGD("deviceId=%d got KEY_UP as stale", entry->deviceId);
1321#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001322 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001323 resetKeyRepeatLocked();
1324 }
1325
1326 if (entry->repeatCount == 1) {
1327 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1328 } else {
1329 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1330 }
1331
1332 entry->dispatchInProgress = true;
1333
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001334 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001335 }
1336
1337 // Handle case where the policy asked us to try again later last time.
1338 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
1339 if (currentTime < entry->interceptKeyWakeupTime) {
1340 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1341 *nextWakeupTime = entry->interceptKeyWakeupTime;
1342 }
1343 return false; // wait until next wakeup
1344 }
1345 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
1346 entry->interceptKeyWakeupTime = 0;
1347 }
1348
1349 // Give the policy a chance to intercept the key.
1350 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
1351 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001352 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
Siarhei Vishniakou49a350a2019-07-26 18:44:23 -07001353 &InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible);
Vishnu Nairad321cd2020-08-20 16:40:21 -07001354 sp<IBinder> focusedWindowToken =
1355 getValueByKey(mFocusedWindowTokenByDisplay, getTargetDisplayId(*entry));
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06001356 commandEntry->connectionToken = focusedWindowToken;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001357 commandEntry->keyEntry = entry;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001358 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001359 return false; // wait for the command to run
1360 } else {
1361 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
1362 }
1363 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001364 if (*dropReason == DropReason::NOT_DROPPED) {
1365 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001366 }
1367 }
1368
1369 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001370 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001371 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001372 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1373 : InputEventInjectionResult::FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001374 mReporter->reportDroppedKey(entry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001375 return true;
1376 }
1377
1378 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001379 std::vector<InputTarget> inputTargets;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001380 InputEventInjectionResult injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001381 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001382 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001383 return false;
1384 }
1385
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001386 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001387 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001388 return true;
1389 }
1390
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001391 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001392 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001393
1394 // Dispatch the key.
1395 dispatchEventLocked(currentTime, entry, inputTargets);
1396 return true;
1397}
1398
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001399void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001400#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01001401 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001402 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1403 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001404 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1405 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
1406 entry.repeatCount, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001407#endif
1408}
1409
Chris Yef59a2f42020-10-16 12:55:26 -07001410void InputDispatcher::doNotifySensorLockedInterruptible(CommandEntry* commandEntry) {
1411 mLock.unlock();
1412
1413 const std::shared_ptr<SensorEntry>& entry = commandEntry->sensorEntry;
1414 if (entry->accuracyChanged) {
1415 mPolicy->notifySensorAccuracy(entry->deviceId, entry->sensorType, entry->accuracy);
1416 }
1417 mPolicy->notifySensorEvent(entry->deviceId, entry->sensorType, entry->accuracy,
1418 entry->hwTimestamp, entry->values);
1419 mLock.lock();
1420}
1421
1422void InputDispatcher::dispatchSensorLocked(nsecs_t currentTime, std::shared_ptr<SensorEntry> entry,
1423 DropReason* dropReason, nsecs_t* nextWakeupTime) {
1424#if DEBUG_OUTBOUND_EVENT_DETAILS
1425 ALOGD("notifySensorEvent eventTime=%" PRId64 ", hwTimestamp=%" PRId64 ", deviceId=%d, "
1426 "source=0x%x, sensorType=%s",
1427 entry->eventTime, entry->hwTimestamp, entry->deviceId, entry->source,
1428 NamedEnum::string(sensorType).c_str());
1429#endif
1430 std::unique_ptr<CommandEntry> commandEntry =
1431 std::make_unique<CommandEntry>(&InputDispatcher::doNotifySensorLockedInterruptible);
1432 commandEntry->sensorEntry = entry;
1433 postCommandLocked(std::move(commandEntry));
1434}
1435
1436bool InputDispatcher::flushSensor(int deviceId, InputDeviceSensorType sensorType) {
1437#if DEBUG_OUTBOUND_EVENT_DETAILS
1438 ALOGD("flushSensor deviceId=%d, sensorType=%s", deviceId,
1439 NamedEnum::string(sensorType).c_str());
1440#endif
1441 { // acquire lock
1442 std::scoped_lock _l(mLock);
1443
1444 for (auto it = mInboundQueue.begin(); it != mInboundQueue.end(); it++) {
1445 std::shared_ptr<EventEntry> entry = *it;
1446 if (entry->type == EventEntry::Type::SENSOR) {
1447 it = mInboundQueue.erase(it);
1448 releaseInboundEventLocked(entry);
1449 }
1450 }
1451 }
1452 return true;
1453}
1454
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001455bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, std::shared_ptr<MotionEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001456 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001457 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001458 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001459 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001460 entry->dispatchInProgress = true;
1461
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001462 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001463 }
1464
1465 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001466 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001467 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001468 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1469 : InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001470 return true;
1471 }
1472
1473 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
1474
1475 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001476 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001477
1478 bool conflictingPointerActions = false;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001479 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001480 if (isPointerEvent) {
1481 // Pointer event. (eg. touchscreen)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001482 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001483 findTouchedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001484 &conflictingPointerActions);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001485 } else {
1486 // Non touch event. (eg. trackball)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001487 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001488 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001489 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001490 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001491 return false;
1492 }
1493
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001494 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001495 if (injectionResult == InputEventInjectionResult::PERMISSION_DENIED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001496 ALOGW("Permission denied, dropping the motion (isPointer=%s)", toString(isPointerEvent));
1497 return true;
1498 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001499 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001500 CancelationOptions::Mode mode(isPointerEvent
1501 ? CancelationOptions::CANCEL_POINTER_EVENTS
1502 : CancelationOptions::CANCEL_NON_POINTER_EVENTS);
1503 CancelationOptions options(mode, "input event injection failed");
1504 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001505 return true;
1506 }
1507
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001508 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001509 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001510
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001511 if (isPointerEvent) {
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07001512 std::unordered_map<int32_t, TouchState>::iterator it =
1513 mTouchStatesByDisplay.find(entry->displayId);
1514 if (it != mTouchStatesByDisplay.end()) {
1515 const TouchState& state = it->second;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001516 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001517 // The event has gone through these portal windows, so we add monitoring targets of
1518 // the corresponding displays as well.
1519 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001520 const InputWindowInfo* windowInfo = state.portalWindows[i]->getInfo();
Michael Wright3dd60e22019-03-27 22:06:44 +00001521 addGlobalMonitoringTargetsLocked(inputTargets, windowInfo->portalToDisplayId,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001522 -windowInfo->frameLeft, -windowInfo->frameTop);
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001523 }
1524 }
1525 }
1526 }
1527
Michael Wrightd02c5b62014-02-10 15:10:22 -08001528 // Dispatch the motion.
1529 if (conflictingPointerActions) {
1530 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001531 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001532 synthesizeCancelationEventsForAllConnectionsLocked(options);
1533 }
1534 dispatchEventLocked(currentTime, entry, inputTargets);
1535 return true;
1536}
1537
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001538void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001539#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08001540 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001541 ", policyFlags=0x%x, "
1542 "action=0x%x, actionButton=0x%x, flags=0x%x, "
1543 "metaState=0x%x, buttonState=0x%x,"
1544 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001545 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1546 entry.action, entry.actionButton, entry.flags, entry.metaState, entry.buttonState,
1547 entry.edgeFlags, entry.xPrecision, entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001548
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001549 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001550 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001551 "x=%f, y=%f, pressure=%f, size=%f, "
1552 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1553 "orientation=%f",
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001554 i, entry.pointerProperties[i].id, entry.pointerProperties[i].toolType,
1555 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1556 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1557 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1558 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1559 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1560 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1561 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1562 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1563 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001564 }
1565#endif
1566}
1567
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001568void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
1569 std::shared_ptr<EventEntry> eventEntry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001570 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001571 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001572#if DEBUG_DISPATCH_CYCLE
1573 ALOGD("dispatchEventToCurrentInputTargets");
1574#endif
1575
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001576 updateInteractionTokensLocked(*eventEntry, inputTargets);
1577
Michael Wrightd02c5b62014-02-10 15:10:22 -08001578 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1579
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001580 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001581
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001582 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001583 sp<Connection> connection =
1584 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001585 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08001586 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001587 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001588 if (DEBUG_FOCUS) {
1589 ALOGD("Dropping event delivery to target with channel '%s' because it "
1590 "is no longer registered with the input dispatcher.",
1591 inputTarget.inputChannel->getName().c_str());
1592 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001593 }
1594 }
1595}
1596
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001597void InputDispatcher::cancelEventsForAnrLocked(const sp<Connection>& connection) {
1598 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
1599 // If the policy decides to close the app, we will get a channel removal event via
1600 // unregisterInputChannel, and will clean up the connection that way. We are already not
1601 // sending new pointers to the connection when it blocked, but focused events will continue to
1602 // pile up.
1603 ALOGW("Canceling events for %s because it is unresponsive",
1604 connection->inputChannel->getName().c_str());
1605 if (connection->status == Connection::STATUS_NORMAL) {
1606 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1607 "application not responding");
1608 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001609 }
1610}
1611
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001612void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001613 if (DEBUG_FOCUS) {
1614 ALOGD("Resetting ANR timeouts.");
1615 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001616
1617 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001618 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07001619 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001620}
1621
Tiger Huang721e26f2018-07-24 22:26:19 +08001622/**
1623 * Get the display id that the given event should go to. If this event specifies a valid display id,
1624 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1625 * Focused display is the display that the user most recently interacted with.
1626 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001627int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001628 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001629 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001630 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001631 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1632 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001633 break;
1634 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001635 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001636 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1637 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001638 break;
1639 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001640 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001641 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001642 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07001643 case EventEntry::Type::DEVICE_RESET:
1644 case EventEntry::Type::SENSOR: {
1645 ALOGE("%s events do not have a target display", NamedEnum::string(entry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001646 return ADISPLAY_ID_NONE;
1647 }
Tiger Huang721e26f2018-07-24 22:26:19 +08001648 }
1649 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1650}
1651
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001652bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
1653 const char* focusedWindowName) {
1654 if (mAnrTracker.empty()) {
1655 // already processed all events that we waited for
1656 mKeyIsWaitingForEventsTimeout = std::nullopt;
1657 return false;
1658 }
1659
1660 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
1661 // Start the timer
1662 ALOGD("Waiting to send key to %s because there are unprocessed events that may cause "
1663 "focus to change",
1664 focusedWindowName);
Siarhei Vishniakou70622952020-07-30 11:17:23 -05001665 mKeyIsWaitingForEventsTimeout = currentTime +
1666 std::chrono::duration_cast<std::chrono::nanoseconds>(KEY_WAITING_FOR_EVENTS_TIMEOUT)
1667 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001668 return true;
1669 }
1670
1671 // We still have pending events, and already started the timer
1672 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
1673 return true; // Still waiting
1674 }
1675
1676 // Waited too long, and some connection still hasn't processed all motions
1677 // Just send the key to the focused window
1678 ALOGW("Dispatching key to %s even though there are other unprocessed events",
1679 focusedWindowName);
1680 mKeyIsWaitingForEventsTimeout = std::nullopt;
1681 return false;
1682}
1683
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001684InputEventInjectionResult InputDispatcher::findFocusedWindowTargetsLocked(
1685 nsecs_t currentTime, const EventEntry& entry, std::vector<InputTarget>& inputTargets,
1686 nsecs_t* nextWakeupTime) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001687 std::string reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001688
Tiger Huang721e26f2018-07-24 22:26:19 +08001689 int32_t displayId = getTargetDisplayId(entry);
Vishnu Nairad321cd2020-08-20 16:40:21 -07001690 sp<InputWindowHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07001691 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08001692 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1693
Michael Wrightd02c5b62014-02-10 15:10:22 -08001694 // If there is no currently focused window and no focused application
1695 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001696 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
1697 ALOGI("Dropping %s event because there is no focused window or focused application in "
1698 "display %" PRId32 ".",
Chris Yef59a2f42020-10-16 12:55:26 -07001699 NamedEnum::string(entry.type).c_str(), displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001700 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001701 }
1702
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001703 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
1704 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
1705 // start interacting with another application via touch (app switch). This code can be removed
1706 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
1707 // an app is expected to have a focused window.
1708 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
1709 if (!mNoFocusedWindowTimeoutTime.has_value()) {
1710 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001711 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
1712 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
1713 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001714 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05001715 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001716 ALOGW("Waiting because no window has focus but %s may eventually add a "
1717 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001718 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001719 *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001720 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001721 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
1722 // Already raised ANR. Drop the event
1723 ALOGE("Dropping %s event because there is no focused window",
Chris Yef59a2f42020-10-16 12:55:26 -07001724 NamedEnum::string(entry.type).c_str());
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001725 return InputEventInjectionResult::FAILED;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001726 } else {
1727 // Still waiting for the focused window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001728 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001729 }
1730 }
1731
1732 // we have a valid, non-null focused window
1733 resetNoFocusedWindowTimeoutLocked();
1734
Michael Wrightd02c5b62014-02-10 15:10:22 -08001735 // Check permissions.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001736 if (!checkInjectionPermission(focusedWindowHandle, entry.injectionState)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001737 return InputEventInjectionResult::PERMISSION_DENIED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001738 }
1739
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001740 if (focusedWindowHandle->getInfo()->paused) {
1741 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001742 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001743 }
1744
1745 // If the event is a key event, then we must wait for all previous events to
1746 // complete before delivering it because previous events may have the
1747 // side-effect of transferring focus to a different window and we want to
1748 // ensure that the following keys are sent to the new window.
1749 //
1750 // Suppose the user touches a button in a window then immediately presses "A".
1751 // If the button causes a pop-up window to appear then we want to ensure that
1752 // the "A" key is delivered to the new pop-up window. This is because users
1753 // often anticipate pending UI changes when typing on a keyboard.
1754 // To obtain this behavior, we must serialize key events with respect to all
1755 // prior input events.
1756 if (entry.type == EventEntry::Type::KEY) {
1757 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
1758 *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001759 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001760 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001761 }
1762
1763 // Success! Output targets.
Tiger Huang721e26f2018-07-24 22:26:19 +08001764 addWindowTargetLocked(focusedWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001765 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS,
1766 BitSet32(0), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001767
1768 // Done.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001769 return InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001770}
1771
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001772/**
1773 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
1774 * that are currently unresponsive.
1775 */
1776std::vector<TouchedMonitor> InputDispatcher::selectResponsiveMonitorsLocked(
1777 const std::vector<TouchedMonitor>& monitors) const {
1778 std::vector<TouchedMonitor> responsiveMonitors;
1779 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
1780 [this](const TouchedMonitor& monitor) REQUIRES(mLock) {
1781 sp<Connection> connection = getConnectionLocked(
1782 monitor.monitor.inputChannel->getConnectionToken());
1783 if (connection == nullptr) {
1784 ALOGE("Could not find connection for monitor %s",
1785 monitor.monitor.inputChannel->getName().c_str());
1786 return false;
1787 }
1788 if (!connection->responsive) {
1789 ALOGW("Unresponsive monitor %s will not get the new gesture",
1790 connection->inputChannel->getName().c_str());
1791 return false;
1792 }
1793 return true;
1794 });
1795 return responsiveMonitors;
1796}
1797
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001798InputEventInjectionResult InputDispatcher::findTouchedWindowTargetsLocked(
1799 nsecs_t currentTime, const MotionEntry& entry, std::vector<InputTarget>& inputTargets,
1800 nsecs_t* nextWakeupTime, bool* outConflictingPointerActions) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001801 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001802 enum InjectionPermission {
1803 INJECTION_PERMISSION_UNKNOWN,
1804 INJECTION_PERMISSION_GRANTED,
1805 INJECTION_PERMISSION_DENIED
1806 };
1807
Michael Wrightd02c5b62014-02-10 15:10:22 -08001808 // For security reasons, we defer updating the touch state until we are sure that
1809 // event injection will be allowed.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001810 int32_t displayId = entry.displayId;
1811 int32_t action = entry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001812 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
1813
1814 // Update the touch state as needed based on the properties of the touch event.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001815 InputEventInjectionResult injectionResult = InputEventInjectionResult::PENDING;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001816 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
Garfield Tandf26e862020-07-01 20:18:19 -07001817 sp<InputWindowHandle> newHoverWindowHandle(mLastHoverWindowHandle);
1818 sp<InputWindowHandle> newTouchedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001819
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001820 // Copy current touch state into tempTouchState.
1821 // This state will be used to update mTouchStatesByDisplay at the end of this function.
1822 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07001823 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001824 TouchState tempTouchState;
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07001825 std::unordered_map<int32_t, TouchState>::iterator oldStateIt =
1826 mTouchStatesByDisplay.find(displayId);
1827 if (oldStateIt != mTouchStatesByDisplay.end()) {
1828 oldState = &(oldStateIt->second);
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001829 tempTouchState.copyFrom(*oldState);
Jeff Brownf086ddb2014-02-11 14:28:48 -08001830 }
1831
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001832 bool isSplit = tempTouchState.split;
1833 bool switchedDevice = tempTouchState.deviceId >= 0 && tempTouchState.displayId >= 0 &&
1834 (tempTouchState.deviceId != entry.deviceId || tempTouchState.source != entry.source ||
1835 tempTouchState.displayId != displayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001836 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
1837 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
1838 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
1839 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN ||
1840 maskedAction == AMOTION_EVENT_ACTION_SCROLL || isHoverAction);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001841 const bool isFromMouse = entry.source == AINPUT_SOURCE_MOUSE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001842 bool wrongDevice = false;
1843 if (newGesture) {
1844 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001845 if (switchedDevice && tempTouchState.down && !down && !isHoverAction) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001846 ALOGI("Dropping event because a pointer for a different device is already down "
1847 "in display %" PRId32,
1848 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001849 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001850 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001851 switchedDevice = false;
1852 wrongDevice = true;
1853 goto Failed;
1854 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001855 tempTouchState.reset();
1856 tempTouchState.down = down;
1857 tempTouchState.deviceId = entry.deviceId;
1858 tempTouchState.source = entry.source;
1859 tempTouchState.displayId = displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001860 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001861 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001862 ALOGI("Dropping move event because a pointer for a different device is already active "
1863 "in display %" PRId32,
1864 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001865 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001866 injectionResult = InputEventInjectionResult::PERMISSION_DENIED;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001867 switchedDevice = false;
1868 wrongDevice = true;
1869 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001870 }
1871
1872 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
1873 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
1874
Garfield Tan00f511d2019-06-12 16:55:40 -07001875 int32_t x;
1876 int32_t y;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001877 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Garfield Tan00f511d2019-06-12 16:55:40 -07001878 // Always dispatch mouse events to cursor position.
1879 if (isFromMouse) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001880 x = int32_t(entry.xCursorPosition);
1881 y = int32_t(entry.yCursorPosition);
Garfield Tan00f511d2019-06-12 16:55:40 -07001882 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001883 x = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X));
1884 y = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y));
Garfield Tan00f511d2019-06-12 16:55:40 -07001885 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001886 bool isDown = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Garfield Tandf26e862020-07-01 20:18:19 -07001887 newTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001888 findTouchedWindowAtLocked(displayId, x, y, &tempTouchState,
1889 isDown /*addOutsideTargets*/, true /*addPortalWindows*/);
Michael Wright3dd60e22019-03-27 22:06:44 +00001890
1891 std::vector<TouchedMonitor> newGestureMonitors = isDown
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001892 ? findTouchedGestureMonitorsLocked(displayId, tempTouchState.portalWindows)
Michael Wright3dd60e22019-03-27 22:06:44 +00001893 : std::vector<TouchedMonitor>{};
Michael Wrightd02c5b62014-02-10 15:10:22 -08001894
Michael Wrightd02c5b62014-02-10 15:10:22 -08001895 // Figure out whether splitting will be allowed for this window.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001896 if (newTouchedWindowHandle != nullptr &&
1897 newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Garfield Tanaddb02b2019-06-25 16:36:13 -07001898 // New window supports splitting, but we should never split mouse events.
1899 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001900 } else if (isSplit) {
1901 // New window does not support splitting but we have already split events.
1902 // Ignore the new window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001903 newTouchedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001904 }
1905
1906 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001907 if (newTouchedWindowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001908 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001909 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001910 }
1911
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001912 if (newTouchedWindowHandle != nullptr && newTouchedWindowHandle->getInfo()->paused) {
1913 ALOGI("Not sending touch event to %s because it is paused",
1914 newTouchedWindowHandle->getName().c_str());
1915 newTouchedWindowHandle = nullptr;
1916 }
1917
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001918 // Ensure the window has a connection and the connection is responsive
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001919 if (newTouchedWindowHandle != nullptr) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001920 const bool isResponsive = hasResponsiveConnectionLocked(*newTouchedWindowHandle);
1921 if (!isResponsive) {
1922 ALOGW("%s will not receive the new gesture at %" PRIu64,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001923 newTouchedWindowHandle->getName().c_str(), entry.eventTime);
1924 newTouchedWindowHandle = nullptr;
1925 }
1926 }
1927
Bernardo Rufinoea97d182020-08-19 14:43:14 +01001928 // Drop events that can't be trusted due to occlusion
1929 if (newTouchedWindowHandle != nullptr &&
1930 mBlockUntrustedTouchesMode != BlockUntrustedTouchesMode::DISABLED) {
1931 TouchOcclusionInfo occlusionInfo =
1932 computeTouchOcclusionInfoLocked(newTouchedWindowHandle, x, y);
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00001933 if (!isTouchTrustedLocked(occlusionInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00001934 if (DEBUG_TOUCH_OCCLUSION) {
1935 ALOGD("Stack of obscuring windows during untrusted touch (%d, %d):", x, y);
1936 for (const auto& log : occlusionInfo.debugInfo) {
1937 ALOGD("%s", log.c_str());
1938 }
1939 }
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00001940 onUntrustedTouchLocked(occlusionInfo.obscuringPackage);
1941 if (mBlockUntrustedTouchesMode == BlockUntrustedTouchesMode::BLOCK) {
1942 ALOGW("Dropping untrusted touch event due to %s/%d",
1943 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid);
1944 newTouchedWindowHandle = nullptr;
1945 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01001946 }
1947 }
1948
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001949 // Also don't send the new touch event to unresponsive gesture monitors
1950 newGestureMonitors = selectResponsiveMonitorsLocked(newGestureMonitors);
1951
Michael Wright3dd60e22019-03-27 22:06:44 +00001952 if (newTouchedWindowHandle == nullptr && newGestureMonitors.empty()) {
1953 ALOGI("Dropping event because there is no touchable window or gesture monitor at "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001954 "(%d, %d) in display %" PRId32 ".",
1955 x, y, displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001956 injectionResult = InputEventInjectionResult::FAILED;
Michael Wright3dd60e22019-03-27 22:06:44 +00001957 goto Failed;
1958 }
1959
1960 if (newTouchedWindowHandle != nullptr) {
1961 // Set target flags.
1962 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
1963 if (isSplit) {
1964 targetFlags |= InputTarget::FLAG_SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001965 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001966 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1967 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1968 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
1969 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1970 }
1971
1972 // Update hover state.
Garfield Tandf26e862020-07-01 20:18:19 -07001973 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
1974 newHoverWindowHandle = nullptr;
1975 } else if (isHoverAction) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001976 newHoverWindowHandle = newTouchedWindowHandle;
Michael Wright3dd60e22019-03-27 22:06:44 +00001977 }
1978
1979 // Update the temporary touch state.
1980 BitSet32 pointerIds;
1981 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001982 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wright3dd60e22019-03-27 22:06:44 +00001983 pointerIds.markBit(pointerId);
1984 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001985 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001986 }
1987
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001988 tempTouchState.addGestureMonitors(newGestureMonitors);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001989 } else {
1990 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
1991
1992 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001993 if (!tempTouchState.down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001994 if (DEBUG_FOCUS) {
1995 ALOGD("Dropping event because the pointer is not down or we previously "
1996 "dropped the pointer down event in display %" PRId32,
1997 displayId);
1998 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001999 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002000 goto Failed;
2001 }
2002
2003 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002004 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002005 tempTouchState.isSlippery()) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002006 int32_t x = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
2007 int32_t y = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002008
2009 sp<InputWindowHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002010 tempTouchState.getFirstForegroundWindowHandle();
Garfield Tandf26e862020-07-01 20:18:19 -07002011 newTouchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y, &tempTouchState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002012 if (oldTouchedWindowHandle != newTouchedWindowHandle &&
2013 oldTouchedWindowHandle != nullptr && newTouchedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002014 if (DEBUG_FOCUS) {
2015 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
2016 oldTouchedWindowHandle->getName().c_str(),
2017 newTouchedWindowHandle->getName().c_str(), displayId);
2018 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002019 // Make a slippery exit from the old window.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002020 tempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
2021 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT,
2022 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002023
2024 // Make a slippery entrance into the new window.
2025 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
2026 isSplit = true;
2027 }
2028
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002029 int32_t targetFlags =
2030 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002031 if (isSplit) {
2032 targetFlags |= InputTarget::FLAG_SPLIT;
2033 }
2034 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
2035 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002036 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
2037 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002038 }
2039
2040 BitSet32 pointerIds;
2041 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002042 pointerIds.markBit(entry.pointerProperties[0].id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002043 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002044 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002045 }
2046 }
2047 }
2048
2049 if (newHoverWindowHandle != mLastHoverWindowHandle) {
Garfield Tandf26e862020-07-01 20:18:19 -07002050 // Let the previous window know that the hover sequence is over, unless we already did it
2051 // when dispatching it as is to newTouchedWindowHandle.
2052 if (mLastHoverWindowHandle != nullptr &&
2053 (maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT ||
2054 mLastHoverWindowHandle != newTouchedWindowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002055#if DEBUG_HOVER
2056 ALOGD("Sending hover exit event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002057 mLastHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002058#endif
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002059 tempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
2060 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002061 }
2062
Garfield Tandf26e862020-07-01 20:18:19 -07002063 // Let the new window know that the hover sequence is starting, unless we already did it
2064 // when dispatching it as is to newTouchedWindowHandle.
2065 if (newHoverWindowHandle != nullptr &&
2066 (maskedAction != AMOTION_EVENT_ACTION_HOVER_ENTER ||
2067 newHoverWindowHandle != newTouchedWindowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002068#if DEBUG_HOVER
2069 ALOGD("Sending hover enter event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002070 newHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002071#endif
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002072 tempTouchState.addOrUpdateWindow(newHoverWindowHandle,
2073 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER,
2074 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002075 }
2076 }
2077
2078 // Check permission to inject into all touched foreground windows and ensure there
2079 // is at least one touched foreground window.
2080 {
2081 bool haveForegroundWindow = false;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002082 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002083 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
2084 haveForegroundWindow = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002085 if (!checkInjectionPermission(touchedWindow.windowHandle, entry.injectionState)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002086 injectionResult = InputEventInjectionResult::PERMISSION_DENIED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002087 injectionPermission = INJECTION_PERMISSION_DENIED;
2088 goto Failed;
2089 }
2090 }
2091 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002092 bool hasGestureMonitor = !tempTouchState.gestureMonitors.empty();
Michael Wright3dd60e22019-03-27 22:06:44 +00002093 if (!haveForegroundWindow && !hasGestureMonitor) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002094 ALOGI("Dropping event because there is no touched foreground window in display "
2095 "%" PRId32 " or gesture monitor to receive it.",
2096 displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002097 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002098 goto Failed;
2099 }
2100
2101 // Permission granted to injection into all touched foreground windows.
2102 injectionPermission = INJECTION_PERMISSION_GRANTED;
2103 }
2104
2105 // Check whether windows listening for outside touches are owned by the same UID. If it is
2106 // set the policy flag that we will not reveal coordinate information to this window.
2107 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2108 sp<InputWindowHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002109 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002110 if (foregroundWindowHandle) {
2111 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002112 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002113 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2114 sp<InputWindowHandle> inputWindowHandle = touchedWindow.windowHandle;
2115 if (inputWindowHandle->getInfo()->ownerUid != foregroundWindowUid) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002116 tempTouchState.addOrUpdateWindow(inputWindowHandle,
2117 InputTarget::FLAG_ZERO_COORDS,
2118 BitSet32(0));
Michael Wright3dd60e22019-03-27 22:06:44 +00002119 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002120 }
2121 }
2122 }
2123 }
2124
Michael Wrightd02c5b62014-02-10 15:10:22 -08002125 // If this is the first pointer going down and the touched window has a wallpaper
2126 // then also add the touched wallpaper windows so they are locked in for the duration
2127 // of the touch gesture.
2128 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
2129 // engine only supports touch events. We would need to add a mechanism similar
2130 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
2131 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2132 sp<InputWindowHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002133 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002134 if (foregroundWindowHandle && foregroundWindowHandle->getInfo()->hasWallpaper) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07002135 const std::vector<sp<InputWindowHandle>>& windowHandles =
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002136 getWindowHandlesLocked(displayId);
2137 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002138 const InputWindowInfo* info = windowHandle->getInfo();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002139 if (info->displayId == displayId &&
Michael Wright44753b12020-07-08 13:48:11 +01002140 windowHandle->getInfo()->type == InputWindowInfo::Type::WALLPAPER) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002141 tempTouchState
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002142 .addOrUpdateWindow(windowHandle,
2143 InputTarget::FLAG_WINDOW_IS_OBSCURED |
2144 InputTarget::
2145 FLAG_WINDOW_IS_PARTIALLY_OBSCURED |
2146 InputTarget::FLAG_DISPATCH_AS_IS,
2147 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002148 }
2149 }
2150 }
2151 }
2152
2153 // Success! Output targets.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002154 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002155
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002156 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002157 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002158 touchedWindow.pointerIds, inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002159 }
2160
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002161 for (const TouchedMonitor& touchedMonitor : tempTouchState.gestureMonitors) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002162 addMonitoringTargetLocked(touchedMonitor.monitor, touchedMonitor.xOffset,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002163 touchedMonitor.yOffset, inputTargets);
Michael Wright3dd60e22019-03-27 22:06:44 +00002164 }
2165
Michael Wrightd02c5b62014-02-10 15:10:22 -08002166 // Drop the outside or hover touch windows since we will not care about them
2167 // in the next iteration.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002168 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002169
2170Failed:
2171 // Check injection permission once and for all.
2172 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002173 if (checkInjectionPermission(nullptr, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002174 injectionPermission = INJECTION_PERMISSION_GRANTED;
2175 } else {
2176 injectionPermission = INJECTION_PERMISSION_DENIED;
2177 }
2178 }
2179
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002180 if (injectionPermission != INJECTION_PERMISSION_GRANTED) {
2181 return injectionResult;
2182 }
2183
Michael Wrightd02c5b62014-02-10 15:10:22 -08002184 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002185 if (!wrongDevice) {
2186 if (switchedDevice) {
2187 if (DEBUG_FOCUS) {
2188 ALOGD("Conflicting pointer actions: Switched to a different device.");
2189 }
2190 *outConflictingPointerActions = true;
2191 }
2192
2193 if (isHoverAction) {
2194 // Started hovering, therefore no longer down.
2195 if (oldState && oldState->down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002196 if (DEBUG_FOCUS) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002197 ALOGD("Conflicting pointer actions: Hover received while pointer was "
2198 "down.");
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002199 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002200 *outConflictingPointerActions = true;
2201 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002202 tempTouchState.reset();
2203 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2204 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
2205 tempTouchState.deviceId = entry.deviceId;
2206 tempTouchState.source = entry.source;
2207 tempTouchState.displayId = displayId;
2208 }
2209 } else if (maskedAction == AMOTION_EVENT_ACTION_UP ||
2210 maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
2211 // All pointers up or canceled.
2212 tempTouchState.reset();
2213 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2214 // First pointer went down.
2215 if (oldState && oldState->down) {
2216 if (DEBUG_FOCUS) {
2217 ALOGD("Conflicting pointer actions: Down received while already down.");
2218 }
2219 *outConflictingPointerActions = true;
2220 }
2221 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2222 // One pointer went up.
2223 if (isSplit) {
2224 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2225 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002226
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002227 for (size_t i = 0; i < tempTouchState.windows.size();) {
2228 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2229 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
2230 touchedWindow.pointerIds.clearBit(pointerId);
2231 if (touchedWindow.pointerIds.isEmpty()) {
2232 tempTouchState.windows.erase(tempTouchState.windows.begin() + i);
2233 continue;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002234 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002235 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002236 i += 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002237 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002238 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002239 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002240
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002241 // Save changes unless the action was scroll in which case the temporary touch
2242 // state was only valid for this one action.
2243 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
2244 if (tempTouchState.displayId >= 0) {
2245 mTouchStatesByDisplay[displayId] = tempTouchState;
2246 } else {
2247 mTouchStatesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002248 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002249 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002250
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002251 // Update hover state.
2252 mLastHoverWindowHandle = newHoverWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002253 }
2254
Michael Wrightd02c5b62014-02-10 15:10:22 -08002255 return injectionResult;
2256}
2257
2258void InputDispatcher::addWindowTargetLocked(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002259 int32_t targetFlags, BitSet32 pointerIds,
2260 std::vector<InputTarget>& inputTargets) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002261 std::vector<InputTarget>::iterator it =
2262 std::find_if(inputTargets.begin(), inputTargets.end(),
2263 [&windowHandle](const InputTarget& inputTarget) {
2264 return inputTarget.inputChannel->getConnectionToken() ==
2265 windowHandle->getToken();
2266 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002267
Chavi Weingarten114b77f2020-01-15 22:35:10 +00002268 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002269
2270 if (it == inputTargets.end()) {
2271 InputTarget inputTarget;
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05002272 std::shared_ptr<InputChannel> inputChannel =
2273 getInputChannelLocked(windowHandle->getToken());
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002274 if (inputChannel == nullptr) {
2275 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
2276 return;
2277 }
2278 inputTarget.inputChannel = inputChannel;
2279 inputTarget.flags = targetFlags;
2280 inputTarget.globalScaleFactor = windowInfo->globalScaleFactor;
2281 inputTargets.push_back(inputTarget);
2282 it = inputTargets.end() - 1;
2283 }
2284
2285 ALOG_ASSERT(it->flags == targetFlags);
2286 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
2287
chaviw1ff3d1e2020-07-01 15:53:47 -07002288 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002289}
2290
Michael Wright3dd60e22019-03-27 22:06:44 +00002291void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002292 int32_t displayId, float xOffset,
2293 float yOffset) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002294 std::unordered_map<int32_t, std::vector<Monitor>>::const_iterator it =
2295 mGlobalMonitorsByDisplay.find(displayId);
2296
2297 if (it != mGlobalMonitorsByDisplay.end()) {
2298 const std::vector<Monitor>& monitors = it->second;
2299 for (const Monitor& monitor : monitors) {
2300 addMonitoringTargetLocked(monitor, xOffset, yOffset, inputTargets);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002301 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002302 }
2303}
2304
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002305void InputDispatcher::addMonitoringTargetLocked(const Monitor& monitor, float xOffset,
2306 float yOffset,
2307 std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002308 InputTarget target;
2309 target.inputChannel = monitor.inputChannel;
2310 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
chaviw1ff3d1e2020-07-01 15:53:47 -07002311 ui::Transform t;
2312 t.set(xOffset, yOffset);
2313 target.setDefaultPointerTransform(t);
Michael Wright3dd60e22019-03-27 22:06:44 +00002314 inputTargets.push_back(target);
2315}
2316
Michael Wrightd02c5b62014-02-10 15:10:22 -08002317bool InputDispatcher::checkInjectionPermission(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002318 const InjectionState* injectionState) {
2319 if (injectionState &&
2320 (windowHandle == nullptr ||
2321 windowHandle->getInfo()->ownerUid != injectionState->injectorUid) &&
2322 !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002323 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002324 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002325 "owned by uid %d",
2326 injectionState->injectorPid, injectionState->injectorUid,
2327 windowHandle->getName().c_str(), windowHandle->getInfo()->ownerUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002328 } else {
2329 ALOGW("Permission denied: injecting event from pid %d uid %d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002330 injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002331 }
2332 return false;
2333 }
2334 return true;
2335}
2336
Robert Carrc9bf1d32020-04-13 17:21:08 -07002337/**
2338 * Indicate whether one window handle should be considered as obscuring
2339 * another window handle. We only check a few preconditions. Actually
2340 * checking the bounds is left to the caller.
2341 */
2342static bool canBeObscuredBy(const sp<InputWindowHandle>& windowHandle,
2343 const sp<InputWindowHandle>& otherHandle) {
2344 // Compare by token so cloned layers aren't counted
2345 if (haveSameToken(windowHandle, otherHandle)) {
2346 return false;
2347 }
2348 auto info = windowHandle->getInfo();
2349 auto otherInfo = otherHandle->getInfo();
2350 if (!otherInfo->visible) {
2351 return false;
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002352 } else if (otherInfo->alpha == 0 &&
2353 otherInfo->flags.test(InputWindowInfo::Flag::NOT_TOUCHABLE)) {
2354 // Those act as if they were invisible, so we don't need to flag them.
2355 // We do want to potentially flag touchable windows even if they have 0
2356 // opacity, since they can consume touches and alter the effects of the
2357 // user interaction (eg. apps that rely on
2358 // FLAG_WINDOW_IS_PARTIALLY_OBSCURED should still be told about those
2359 // windows), hence we also check for FLAG_NOT_TOUCHABLE.
2360 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00002361 } else if (info->ownerUid == otherInfo->ownerUid) {
2362 // If ownerUid is the same we don't generate occlusion events as there
2363 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002364 return false;
Chris Yefcdff3e2020-05-10 15:16:04 -07002365 } else if (otherInfo->trustedOverlay) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002366 return false;
2367 } else if (otherInfo->displayId != info->displayId) {
2368 return false;
2369 }
2370 return true;
2371}
2372
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002373/**
2374 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
2375 * untrusted, one should check:
2376 *
2377 * 1. If result.hasBlockingOcclusion is true.
2378 * If it's, it means the touch should be blocked due to a window with occlusion mode of
2379 * BLOCK_UNTRUSTED.
2380 *
2381 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
2382 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
2383 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
2384 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
2385 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
2386 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
2387 *
2388 * If neither of those is true, then it means the touch can be allowed.
2389 */
2390InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
2391 const sp<InputWindowHandle>& windowHandle, int32_t x, int32_t y) const {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002392 const InputWindowInfo* windowInfo = windowHandle->getInfo();
2393 int32_t displayId = windowInfo->displayId;
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002394 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2395 TouchOcclusionInfo info;
2396 info.hasBlockingOcclusion = false;
2397 info.obscuringOpacity = 0;
2398 info.obscuringUid = -1;
2399 std::map<int32_t, float> opacityByUid;
2400 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
2401 if (windowHandle == otherHandle) {
2402 break; // All future windows are below us. Exit early.
2403 }
2404 const InputWindowInfo* otherInfo = otherHandle->getInfo();
2405 if (canBeObscuredBy(windowHandle, otherHandle) &&
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002406 windowInfo->ownerUid != otherInfo->ownerUid && otherInfo->frameContainsPoint(x, y)) {
2407 if (DEBUG_TOUCH_OCCLUSION) {
2408 info.debugInfo.push_back(
2409 dumpWindowForTouchOcclusion(otherInfo, /* isTouchedWindow */ false));
2410 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002411 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
2412 // we perform the checks below to see if the touch can be propagated or not based on the
2413 // window's touch occlusion mode
2414 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
2415 info.hasBlockingOcclusion = true;
2416 info.obscuringUid = otherInfo->ownerUid;
2417 info.obscuringPackage = otherInfo->packageName;
2418 break;
2419 }
2420 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
2421 uint32_t uid = otherInfo->ownerUid;
2422 float opacity =
2423 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
2424 // Given windows A and B:
2425 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
2426 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
2427 opacityByUid[uid] = opacity;
2428 if (opacity > info.obscuringOpacity) {
2429 info.obscuringOpacity = opacity;
2430 info.obscuringUid = uid;
2431 info.obscuringPackage = otherInfo->packageName;
2432 }
2433 }
2434 }
2435 }
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002436 if (DEBUG_TOUCH_OCCLUSION) {
2437 info.debugInfo.push_back(
2438 dumpWindowForTouchOcclusion(windowInfo, /* isTouchedWindow */ true));
2439 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002440 return info;
2441}
2442
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002443std::string InputDispatcher::dumpWindowForTouchOcclusion(const InputWindowInfo* info,
2444 bool isTouchedWindow) const {
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00002445 return StringPrintf(INDENT2 "* %stype=%s, package=%s/%" PRId32 ", id=%" PRId32
2446 ", mode=%s, alpha=%.2f, "
Bernardo Rufinoc2f1fad2020-11-04 17:30:57 +00002447 "frame=[%" PRId32 ",%" PRId32 "][%" PRId32 ",%" PRId32
2448 "], touchableRegion=%s, window={%s}, applicationInfo=%s, "
2449 "flags={%s}, inputFeatures={%s}, hasToken=%s\n",
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002450 (isTouchedWindow) ? "[TOUCHED] " : "",
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00002451 NamedEnum::string(info->type, "%" PRId32).c_str(),
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00002452 info->packageName.c_str(), info->ownerUid, info->id,
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00002453 toString(info->touchOcclusionMode).c_str(), info->alpha, info->frameLeft,
2454 info->frameTop, info->frameRight, info->frameBottom,
2455 dumpRegion(info->touchableRegion).c_str(), info->name.c_str(),
Bernardo Rufinoc2f1fad2020-11-04 17:30:57 +00002456 info->applicationInfo.name.c_str(), info->flags.string().c_str(),
2457 info->inputFeatures.string().c_str(), toString(info->token != nullptr));
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002458}
2459
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002460bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
2461 if (occlusionInfo.hasBlockingOcclusion) {
2462 ALOGW("Untrusted touch due to occlusion by %s/%d", occlusionInfo.obscuringPackage.c_str(),
2463 occlusionInfo.obscuringUid);
2464 return false;
2465 }
2466 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
2467 ALOGW("Untrusted touch due to occlusion by %s/%d (obscuring opacity = "
2468 "%.2f, maximum allowed = %.2f)",
2469 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid,
2470 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
2471 return false;
2472 }
2473 return true;
2474}
2475
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002476bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<InputWindowHandle>& windowHandle,
2477 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002478 int32_t displayId = windowHandle->getInfo()->displayId;
Vishnu Nairad321cd2020-08-20 16:40:21 -07002479 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002480 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002481 if (windowHandle == otherHandle) {
2482 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002483 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002484 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002485 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002486 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002487 return true;
2488 }
2489 }
2490 return false;
2491}
2492
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002493bool InputDispatcher::isWindowObscuredLocked(const sp<InputWindowHandle>& windowHandle) const {
2494 int32_t displayId = windowHandle->getInfo()->displayId;
Vishnu Nairad321cd2020-08-20 16:40:21 -07002495 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002496 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002497 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002498 if (windowHandle == otherHandle) {
2499 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002500 }
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002501 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002502 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002503 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002504 return true;
2505 }
2506 }
2507 return false;
2508}
2509
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002510std::string InputDispatcher::getApplicationWindowLabel(
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05002511 const InputApplicationHandle* applicationHandle,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002512 const sp<InputWindowHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002513 if (applicationHandle != nullptr) {
2514 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002515 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002516 } else {
2517 return applicationHandle->getName();
2518 }
Yi Kong9b14ac62018-07-17 13:48:38 -07002519 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002520 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002521 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002522 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002523 }
2524}
2525
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002526void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Prabir Pradhan99987712020-11-10 18:43:05 -08002527 if (eventEntry.type == EventEntry::Type::FOCUS ||
2528 eventEntry.type == EventEntry::Type::POINTER_CAPTURE_CHANGED) {
2529 // Focus or pointer capture changed events are passed to apps, but do not represent user
2530 // activity.
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002531 return;
2532 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002533 int32_t displayId = getTargetDisplayId(eventEntry);
Vishnu Nairad321cd2020-08-20 16:40:21 -07002534 sp<InputWindowHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Tiger Huang721e26f2018-07-24 22:26:19 +08002535 if (focusedWindowHandle != nullptr) {
2536 const InputWindowInfo* info = focusedWindowHandle->getInfo();
Michael Wright44753b12020-07-08 13:48:11 +01002537 if (info->inputFeatures.test(InputWindowInfo::Feature::DISABLE_USER_ACTIVITY)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002538#if DEBUG_DISPATCH_CYCLE
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002539 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002540#endif
2541 return;
2542 }
2543 }
2544
2545 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002546 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002547 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002548 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
2549 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002550 return;
2551 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002552
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002553 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002554 eventType = USER_ACTIVITY_EVENT_TOUCH;
2555 }
2556 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002557 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002558 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002559 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
2560 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002561 return;
2562 }
2563 eventType = USER_ACTIVITY_EVENT_BUTTON;
2564 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002565 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002566 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002567 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08002568 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07002569 case EventEntry::Type::SENSOR:
Prabir Pradhan99987712020-11-10 18:43:05 -08002570 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002571 LOG_ALWAYS_FATAL("%s events are not user activity",
Chris Yef59a2f42020-10-16 12:55:26 -07002572 NamedEnum::string(eventEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002573 break;
2574 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002575 }
2576
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002577 std::unique_ptr<CommandEntry> commandEntry =
2578 std::make_unique<CommandEntry>(&InputDispatcher::doPokeUserActivityLockedInterruptible);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002579 commandEntry->eventTime = eventEntry.eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002580 commandEntry->userActivityEventType = eventType;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002581 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002582}
2583
2584void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002585 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002586 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002587 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002588 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002589 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002590 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002591 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002592 ATRACE_NAME(message.c_str());
2593 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002594#if DEBUG_DISPATCH_CYCLE
2595 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002596 "globalScaleFactor=%f, pointerIds=0x%x %s",
2597 connection->getInputChannelName().c_str(), inputTarget.flags,
2598 inputTarget.globalScaleFactor, inputTarget.pointerIds.value,
2599 inputTarget.getPointerInfoString().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002600#endif
2601
2602 // Skip this event if the connection status is not normal.
2603 // We don't want to enqueue additional outbound events if the connection is broken.
2604 if (connection->status != Connection::STATUS_NORMAL) {
2605#if DEBUG_DISPATCH_CYCLE
2606 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002607 connection->getInputChannelName().c_str(), connection->getStatusLabel());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002608#endif
2609 return;
2610 }
2611
2612 // Split a motion event if needed.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002613 if (inputTarget.flags & InputTarget::FLAG_SPLIT) {
2614 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
2615 "Entry type %s should not have FLAG_SPLIT",
Chris Yef59a2f42020-10-16 12:55:26 -07002616 NamedEnum::string(eventEntry->type).c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002617
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002618 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002619 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002620 std::unique_ptr<MotionEntry> splitMotionEntry =
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002621 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002622 if (!splitMotionEntry) {
2623 return; // split event was dropped
2624 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002625 if (DEBUG_FOCUS) {
2626 ALOGD("channel '%s' ~ Split motion event.",
2627 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002628 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002629 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002630 enqueueDispatchEntriesLocked(currentTime, connection, std::move(splitMotionEntry),
2631 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002632 return;
2633 }
2634 }
2635
2636 // Not splitting. Enqueue dispatch entries for the event as is.
2637 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
2638}
2639
2640void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002641 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002642 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002643 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002644 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002645 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002646 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002647 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002648 ATRACE_NAME(message.c_str());
2649 }
2650
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002651 bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002652
2653 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07002654 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002655 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002656 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002657 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07002658 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002659 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07002660 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002661 InputTarget::FLAG_DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07002662 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002663 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002664 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002665 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002666
2667 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002668 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002669 startDispatchCycleLocked(currentTime, connection);
2670 }
2671}
2672
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002673void InputDispatcher::enqueueDispatchEntryLocked(const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002674 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002675 const InputTarget& inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002676 int32_t dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002677 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002678 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
2679 connection->getInputChannelName().c_str(),
2680 dispatchModeToString(dispatchMode).c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002681 ATRACE_NAME(message.c_str());
2682 }
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002683 int32_t inputTargetFlags = inputTarget.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002684 if (!(inputTargetFlags & dispatchMode)) {
2685 return;
2686 }
2687 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
2688
2689 // This is a new event.
2690 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002691 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002692 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002693
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002694 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
2695 // different EventEntry than what was passed in.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002696 EventEntry& newEntry = *(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002697 // Apply target flags and update the connection's input state.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002698 switch (newEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002699 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002700 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002701 dispatchEntry->resolvedEventId = keyEntry.id;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002702 dispatchEntry->resolvedAction = keyEntry.action;
2703 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002704
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002705 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
2706 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002707#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002708 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key event",
2709 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002710#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002711 return; // skip the inconsistent event
2712 }
2713 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002714 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002715
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002716 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002717 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002718 // Assign a default value to dispatchEntry that will never be generated by InputReader,
2719 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
2720 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
2721 static_cast<int32_t>(IdGenerator::Source::OTHER);
2722 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002723 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2724 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
2725 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
2726 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
2727 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
2728 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2729 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
2730 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
2731 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
2732 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
2733 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002734 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002735 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002736 }
2737 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002738 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
2739 motionEntry.displayId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002740#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002741 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover enter "
2742 "event",
2743 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002744#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002745 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2746 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002747
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002748 dispatchEntry->resolvedFlags = motionEntry.flags;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002749 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
2750 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
2751 }
2752 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
2753 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2754 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002755
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002756 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
2757 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002758#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002759 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
2760 "event",
2761 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002762#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002763 return; // skip the inconsistent event
2764 }
2765
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002766 dispatchEntry->resolvedEventId =
2767 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
2768 ? mIdGenerator.nextId()
2769 : motionEntry.id;
2770 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
2771 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
2772 ") to MotionEvent(id=0x%" PRIx32 ").",
2773 motionEntry.id, dispatchEntry->resolvedEventId);
2774 ATRACE_NAME(message.c_str());
2775 }
2776
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002777 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002778 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002779
2780 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002781 }
Prabir Pradhan99987712020-11-10 18:43:05 -08002782 case EventEntry::Type::FOCUS:
2783 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002784 break;
2785 }
Chris Yef59a2f42020-10-16 12:55:26 -07002786 case EventEntry::Type::SENSOR: {
2787 LOG_ALWAYS_FATAL("SENSOR events should not go to apps via input channel");
2788 break;
2789 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002790 case EventEntry::Type::CONFIGURATION_CHANGED:
2791 case EventEntry::Type::DEVICE_RESET: {
2792 LOG_ALWAYS_FATAL("%s events should not go to apps",
Chris Yef59a2f42020-10-16 12:55:26 -07002793 NamedEnum::string(newEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002794 break;
2795 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002796 }
2797
2798 // Remember that we are waiting for this dispatch to complete.
2799 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002800 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002801 }
2802
2803 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002804 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002805 traceOutboundQueueLength(connection);
chaviw8c9cf542019-03-25 13:02:48 -07002806}
2807
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00002808/**
2809 * This function is purely for debugging. It helps us understand where the user interaction
2810 * was taking place. For example, if user is touching launcher, we will see a log that user
2811 * started interacting with launcher. In that example, the event would go to the wallpaper as well.
2812 * We will see both launcher and wallpaper in that list.
2813 * Once the interaction with a particular set of connections starts, no new logs will be printed
2814 * until the set of interacted connections changes.
2815 *
2816 * The following items are skipped, to reduce the logspam:
2817 * ACTION_OUTSIDE: any windows that are receiving ACTION_OUTSIDE are not logged
2818 * ACTION_UP: any windows that receive ACTION_UP are not logged (for both keys and motions).
2819 * This includes situations like the soft BACK button key. When the user releases (lifts up the
2820 * finger) the back button, then navigation bar will inject KEYCODE_BACK with ACTION_UP.
2821 * Both of those ACTION_UP events would not be logged
2822 * Monitors (both gesture and global): any gesture monitors or global monitors receiving events
2823 * will not be logged. This is omitted to reduce the amount of data printed.
2824 * If you see <none>, it's likely that one of the gesture monitors pilfered the event, and therefore
2825 * gesture monitor is the only connection receiving the remainder of the gesture.
2826 */
2827void InputDispatcher::updateInteractionTokensLocked(const EventEntry& entry,
2828 const std::vector<InputTarget>& targets) {
2829 // Skip ACTION_UP events, and all events other than keys and motions
2830 if (entry.type == EventEntry::Type::KEY) {
2831 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
2832 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
2833 return;
2834 }
2835 } else if (entry.type == EventEntry::Type::MOTION) {
2836 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
2837 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
2838 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
2839 return;
2840 }
2841 } else {
2842 return; // Not a key or a motion
2843 }
2844
2845 std::unordered_set<sp<IBinder>, IBinderHash> newConnectionTokens;
2846 std::vector<sp<Connection>> newConnections;
2847 for (const InputTarget& target : targets) {
2848 if ((target.flags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) ==
2849 InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2850 continue; // Skip windows that receive ACTION_OUTSIDE
2851 }
2852
2853 sp<IBinder> token = target.inputChannel->getConnectionToken();
2854 sp<Connection> connection = getConnectionLocked(token);
2855 if (connection == nullptr || connection->monitor) {
2856 continue; // We only need to keep track of the non-monitor connections.
2857 }
2858 newConnectionTokens.insert(std::move(token));
2859 newConnections.emplace_back(connection);
2860 }
2861 if (newConnectionTokens == mInteractionConnectionTokens) {
2862 return; // no change
2863 }
2864 mInteractionConnectionTokens = newConnectionTokens;
2865
2866 std::string windowList;
2867 for (const sp<Connection>& connection : newConnections) {
2868 windowList += connection->getWindowName() + ", ";
2869 }
2870 std::string message = "Interaction with windows: " + windowList;
2871 if (windowList.empty()) {
2872 message += "<none>";
2873 }
2874 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
2875}
2876
chaviwfd6d3512019-03-25 13:23:49 -07002877void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07002878 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07002879 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07002880 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
2881 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07002882 return;
2883 }
2884
Vishnu Nairad321cd2020-08-20 16:40:21 -07002885 sp<IBinder> focusedToken = getValueByKey(mFocusedWindowTokenByDisplay, mFocusedDisplayId);
2886 if (focusedToken == token) {
2887 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07002888 return;
2889 }
2890
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002891 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
2892 &InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible);
Vishnu Nairad321cd2020-08-20 16:40:21 -07002893 commandEntry->newToken = token;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002894 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002895}
2896
2897void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002898 const sp<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002899 if (ATRACE_ENABLED()) {
2900 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002901 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002902 ATRACE_NAME(message.c_str());
2903 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002904#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002905 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002906#endif
2907
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002908 while (connection->status == Connection::STATUS_NORMAL && !connection->outboundQueue.empty()) {
2909 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002910 dispatchEntry->deliveryTime = currentTime;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05002911 const std::chrono::nanoseconds timeout =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002912 getDispatchingTimeoutLocked(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou70622952020-07-30 11:17:23 -05002913 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002914
2915 // Publish the event.
2916 status_t status;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002917 const EventEntry& eventEntry = *(dispatchEntry->eventEntry);
2918 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002919 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002920 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
2921 std::array<uint8_t, 32> hmac = getSignature(keyEntry, *dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002922
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002923 // Publish the key event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002924 status = connection->inputPublisher
2925 .publishKeyEvent(dispatchEntry->seq,
2926 dispatchEntry->resolvedEventId, keyEntry.deviceId,
2927 keyEntry.source, keyEntry.displayId,
2928 std::move(hmac), dispatchEntry->resolvedAction,
2929 dispatchEntry->resolvedFlags, keyEntry.keyCode,
2930 keyEntry.scanCode, keyEntry.metaState,
2931 keyEntry.repeatCount, keyEntry.downTime,
2932 keyEntry.eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002933 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002934 }
2935
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002936 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002937 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002938
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002939 PointerCoords scaledCoords[MAX_POINTERS];
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002940 const PointerCoords* usingCoords = motionEntry.pointerCoords;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002941
chaviw82357092020-01-28 13:13:06 -08002942 // Set the X and Y offset and X and Y scale depending on the input source.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002943 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) &&
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002944 !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
2945 float globalScaleFactor = dispatchEntry->globalScaleFactor;
chaviw82357092020-01-28 13:13:06 -08002946 if (globalScaleFactor != 1.0f) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002947 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
2948 scaledCoords[i] = motionEntry.pointerCoords[i];
chaviw82357092020-01-28 13:13:06 -08002949 // Don't apply window scale here since we don't want scale to affect raw
2950 // coordinates. The scale will be sent back to the client and applied
2951 // later when requesting relative coordinates.
2952 scaledCoords[i].scale(globalScaleFactor, 1 /* windowXScale */,
2953 1 /* windowYScale */);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002954 }
2955 usingCoords = scaledCoords;
2956 }
2957 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002958 // We don't want the dispatch target to know.
2959 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002960 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002961 scaledCoords[i].clear();
2962 }
2963 usingCoords = scaledCoords;
2964 }
2965 }
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07002966
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002967 std::array<uint8_t, 32> hmac = getSignature(motionEntry, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002968
2969 // Publish the motion event.
2970 status = connection->inputPublisher
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002971 .publishMotionEvent(dispatchEntry->seq,
2972 dispatchEntry->resolvedEventId,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002973 motionEntry.deviceId, motionEntry.source,
2974 motionEntry.displayId, std::move(hmac),
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002975 dispatchEntry->resolvedAction,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002976 motionEntry.actionButton,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002977 dispatchEntry->resolvedFlags,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002978 motionEntry.edgeFlags, motionEntry.metaState,
2979 motionEntry.buttonState,
2980 motionEntry.classification,
chaviw9eaa22c2020-07-01 16:21:27 -07002981 dispatchEntry->transform,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002982 motionEntry.xPrecision, motionEntry.yPrecision,
2983 motionEntry.xCursorPosition,
2984 motionEntry.yCursorPosition,
2985 motionEntry.downTime, motionEntry.eventTime,
2986 motionEntry.pointerCount,
2987 motionEntry.pointerProperties, usingCoords);
2988 reportTouchEventForStatistics(motionEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002989 break;
2990 }
Prabir Pradhan99987712020-11-10 18:43:05 -08002991
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002992 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002993 const FocusEntry& focusEntry = static_cast<const FocusEntry&>(eventEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002994 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002995 focusEntry.id,
2996 focusEntry.hasFocus,
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002997 mInTouchMode);
2998 break;
2999 }
3000
Prabir Pradhan99987712020-11-10 18:43:05 -08003001 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3002 const auto& captureEntry =
3003 static_cast<const PointerCaptureChangedEntry&>(eventEntry);
3004 status = connection->inputPublisher
3005 .publishCaptureEvent(dispatchEntry->seq, captureEntry.id,
3006 captureEntry.pointerCaptureEnabled);
3007 break;
3008 }
3009
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003010 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003011 case EventEntry::Type::DEVICE_RESET:
3012 case EventEntry::Type::SENSOR: {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003013 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
Chris Yef59a2f42020-10-16 12:55:26 -07003014 NamedEnum::string(eventEntry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003015 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003016 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003017 }
3018
3019 // Check the result.
3020 if (status) {
3021 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003022 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003023 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003024 "This is unexpected because the wait queue is empty, so the pipe "
3025 "should be empty and we shouldn't have any problems writing an "
3026 "event to it, status=%d",
3027 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003028 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3029 } else {
3030 // Pipe is full and we are waiting for the app to finish process some events
3031 // before sending more events to it.
3032#if DEBUG_DISPATCH_CYCLE
3033 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003034 "waiting for the application to catch up",
3035 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003036#endif
Michael Wrightd02c5b62014-02-10 15:10:22 -08003037 }
3038 } else {
3039 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003040 "status=%d",
3041 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003042 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3043 }
3044 return;
3045 }
3046
3047 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003048 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
3049 connection->outboundQueue.end(),
3050 dispatchEntry));
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003051 traceOutboundQueueLength(connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003052 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003053 if (connection->responsive) {
3054 mAnrTracker.insert(dispatchEntry->timeoutTime,
3055 connection->inputChannel->getConnectionToken());
3056 }
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003057 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003058 }
3059}
3060
chaviw09c8d2d2020-08-24 15:48:26 -07003061std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
3062 size_t size;
3063 switch (event.type) {
3064 case VerifiedInputEvent::Type::KEY: {
3065 size = sizeof(VerifiedKeyEvent);
3066 break;
3067 }
3068 case VerifiedInputEvent::Type::MOTION: {
3069 size = sizeof(VerifiedMotionEvent);
3070 break;
3071 }
3072 }
3073 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
3074 return mHmacKeyManager.sign(start, size);
3075}
3076
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003077const std::array<uint8_t, 32> InputDispatcher::getSignature(
3078 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
3079 int32_t actionMasked = dispatchEntry.resolvedAction & AMOTION_EVENT_ACTION_MASK;
3080 if ((actionMasked == AMOTION_EVENT_ACTION_UP) || (actionMasked == AMOTION_EVENT_ACTION_DOWN)) {
3081 // Only sign events up and down events as the purely move events
3082 // are tied to their up/down counterparts so signing would be redundant.
3083 VerifiedMotionEvent verifiedEvent = verifiedMotionEventFromMotionEntry(motionEntry);
3084 verifiedEvent.actionMasked = actionMasked;
3085 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
chaviw09c8d2d2020-08-24 15:48:26 -07003086 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003087 }
3088 return INVALID_HMAC;
3089}
3090
3091const std::array<uint8_t, 32> InputDispatcher::getSignature(
3092 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
3093 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
3094 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
3095 verifiedEvent.action = dispatchEntry.resolvedAction;
chaviw09c8d2d2020-08-24 15:48:26 -07003096 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003097}
3098
Michael Wrightd02c5b62014-02-10 15:10:22 -08003099void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003100 const sp<Connection>& connection, uint32_t seq,
3101 bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003102#if DEBUG_DISPATCH_CYCLE
3103 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003104 connection->getInputChannelName().c_str(), seq, toString(handled));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003105#endif
3106
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003107 if (connection->status == Connection::STATUS_BROKEN ||
3108 connection->status == Connection::STATUS_ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003109 return;
3110 }
3111
3112 // Notify other system components and prepare to start the next dispatch cycle.
3113 onDispatchCycleFinishedLocked(currentTime, connection, seq, handled);
3114}
3115
3116void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003117 const sp<Connection>& connection,
3118 bool notify) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003119#if DEBUG_DISPATCH_CYCLE
3120 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003121 connection->getInputChannelName().c_str(), toString(notify));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003122#endif
3123
3124 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003125 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003126 traceOutboundQueueLength(connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003127 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003128 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003129
3130 // The connection appears to be unrecoverably broken.
3131 // Ignore already broken or zombie connections.
3132 if (connection->status == Connection::STATUS_NORMAL) {
3133 connection->status = Connection::STATUS_BROKEN;
3134
3135 if (notify) {
3136 // Notify other system components.
3137 onDispatchCycleBrokenLocked(currentTime, connection);
3138 }
3139 }
3140}
3141
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003142void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
3143 while (!queue.empty()) {
3144 DispatchEntry* dispatchEntry = queue.front();
3145 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003146 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003147 }
3148}
3149
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003150void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003151 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003152 decrementPendingForegroundDispatches(*(dispatchEntry->eventEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003153 }
3154 delete dispatchEntry;
3155}
3156
3157int InputDispatcher::handleReceiveCallback(int fd, int events, void* data) {
3158 InputDispatcher* d = static_cast<InputDispatcher*>(data);
3159
3160 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003161 std::scoped_lock _l(d->mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003162
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003163 if (d->mConnectionsByFd.find(fd) == d->mConnectionsByFd.end()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003164 ALOGE("Received spurious receive callback for unknown input channel. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003165 "fd=%d, events=0x%x",
3166 fd, events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003167 return 0; // remove the callback
3168 }
3169
3170 bool notify;
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003171 sp<Connection> connection = d->mConnectionsByFd[fd];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003172 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
3173 if (!(events & ALOOPER_EVENT_INPUT)) {
3174 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003175 "events=0x%x",
3176 connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003177 return 1;
3178 }
3179
3180 nsecs_t currentTime = now();
3181 bool gotOne = false;
3182 status_t status;
3183 for (;;) {
3184 uint32_t seq;
3185 bool handled;
3186 status = connection->inputPublisher.receiveFinishedSignal(&seq, &handled);
3187 if (status) {
3188 break;
3189 }
3190 d->finishDispatchCycleLocked(currentTime, connection, seq, handled);
3191 gotOne = true;
3192 }
3193 if (gotOne) {
3194 d->runCommandsLockedInterruptible();
3195 if (status == WOULD_BLOCK) {
3196 return 1;
3197 }
3198 }
3199
3200 notify = status != DEAD_OBJECT || !connection->monitor;
3201 if (notify) {
3202 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003203 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003204 }
3205 } else {
3206 // Monitor channels are never explicitly unregistered.
3207 // We do it automatically when the remote endpoint is closed so don't warn
3208 // about them.
arthurhungd352cb32020-04-28 17:09:28 +08003209 const bool stillHaveWindowHandle =
3210 d->getWindowHandleLocked(connection->inputChannel->getConnectionToken()) !=
3211 nullptr;
3212 notify = !connection->monitor && stillHaveWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003213 if (notify) {
3214 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003215 "events=0x%x",
3216 connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003217 }
3218 }
3219
Garfield Tan15601662020-09-22 15:32:38 -07003220 // Remove the channel.
3221 d->removeInputChannelLocked(connection->inputChannel->getConnectionToken(), notify);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003222 return 0; // remove the callback
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003223 } // release lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08003224}
3225
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003226void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08003227 const CancelationOptions& options) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +00003228 for (const auto& [fd, connection] : mConnectionsByFd) {
3229 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003230 }
3231}
3232
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003233void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003234 const CancelationOptions& options) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003235 synthesizeCancelationEventsForMonitorsLocked(options, mGlobalMonitorsByDisplay);
3236 synthesizeCancelationEventsForMonitorsLocked(options, mGestureMonitorsByDisplay);
3237}
3238
3239void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
3240 const CancelationOptions& options,
3241 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
3242 for (const auto& it : monitorsByDisplay) {
3243 const std::vector<Monitor>& monitors = it.second;
3244 for (const Monitor& monitor : monitors) {
3245 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003246 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003247 }
3248}
3249
Michael Wrightd02c5b62014-02-10 15:10:22 -08003250void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003251 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07003252 sp<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003253 if (connection == nullptr) {
3254 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003255 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003256
3257 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003258}
3259
3260void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
3261 const sp<Connection>& connection, const CancelationOptions& options) {
3262 if (connection->status == Connection::STATUS_BROKEN) {
3263 return;
3264 }
3265
3266 nsecs_t currentTime = now();
3267
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003268 std::vector<std::unique_ptr<EventEntry>> cancelationEvents =
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07003269 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003270
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003271 if (cancelationEvents.empty()) {
3272 return;
3273 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003274#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003275 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
3276 "with reality: %s, mode=%d.",
3277 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
3278 options.mode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003279#endif
Svet Ganov5d3bc372020-01-26 23:11:07 -08003280
3281 InputTarget target;
3282 sp<InputWindowHandle> windowHandle =
3283 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3284 if (windowHandle != nullptr) {
3285 const InputWindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003286 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003287 target.globalScaleFactor = windowInfo->globalScaleFactor;
3288 }
3289 target.inputChannel = connection->inputChannel;
3290 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3291
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003292 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003293 std::unique_ptr<EventEntry> cancelationEventEntry = std::move(cancelationEvents[i]);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003294 switch (cancelationEventEntry->type) {
3295 case EventEntry::Type::KEY: {
3296 logOutboundKeyDetails("cancel - ",
3297 static_cast<const KeyEntry&>(*cancelationEventEntry));
3298 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003299 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003300 case EventEntry::Type::MOTION: {
3301 logOutboundMotionDetails("cancel - ",
3302 static_cast<const MotionEntry&>(*cancelationEventEntry));
3303 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003304 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003305 case EventEntry::Type::FOCUS:
3306 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3307 LOG_ALWAYS_FATAL("Canceling %s events is not supported",
Chris Yef59a2f42020-10-16 12:55:26 -07003308 NamedEnum::string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003309 break;
3310 }
3311 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003312 case EventEntry::Type::DEVICE_RESET:
3313 case EventEntry::Type::SENSOR: {
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003314 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Chris Yef59a2f42020-10-16 12:55:26 -07003315 NamedEnum::string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003316 break;
3317 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003318 }
3319
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003320 enqueueDispatchEntryLocked(connection, std::move(cancelationEventEntry), target,
3321 InputTarget::FLAG_DISPATCH_AS_IS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003322 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003323
3324 startDispatchCycleLocked(currentTime, connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003325}
3326
Svet Ganov5d3bc372020-01-26 23:11:07 -08003327void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
3328 const sp<Connection>& connection) {
3329 if (connection->status == Connection::STATUS_BROKEN) {
3330 return;
3331 }
3332
3333 nsecs_t currentTime = now();
3334
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003335 std::vector<std::unique_ptr<EventEntry>> downEvents =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003336 connection->inputState.synthesizePointerDownEvents(currentTime);
3337
3338 if (downEvents.empty()) {
3339 return;
3340 }
3341
3342#if DEBUG_OUTBOUND_EVENT_DETAILS
3343 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
3344 connection->getInputChannelName().c_str(), downEvents.size());
3345#endif
3346
3347 InputTarget target;
3348 sp<InputWindowHandle> windowHandle =
3349 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3350 if (windowHandle != nullptr) {
3351 const InputWindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003352 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003353 target.globalScaleFactor = windowInfo->globalScaleFactor;
3354 }
3355 target.inputChannel = connection->inputChannel;
3356 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3357
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003358 for (std::unique_ptr<EventEntry>& downEventEntry : downEvents) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003359 switch (downEventEntry->type) {
3360 case EventEntry::Type::MOTION: {
3361 logOutboundMotionDetails("down - ",
3362 static_cast<const MotionEntry&>(*downEventEntry));
3363 break;
3364 }
3365
3366 case EventEntry::Type::KEY:
3367 case EventEntry::Type::FOCUS:
3368 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08003369 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07003370 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3371 case EventEntry::Type::SENSOR: {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003372 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Chris Yef59a2f42020-10-16 12:55:26 -07003373 NamedEnum::string(downEventEntry->type).c_str());
Svet Ganov5d3bc372020-01-26 23:11:07 -08003374 break;
3375 }
3376 }
3377
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003378 enqueueDispatchEntryLocked(connection, std::move(downEventEntry), target,
3379 InputTarget::FLAG_DISPATCH_AS_IS);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003380 }
3381
3382 startDispatchCycleLocked(currentTime, connection);
3383}
3384
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003385std::unique_ptr<MotionEntry> InputDispatcher::splitMotionEvent(
3386 const MotionEntry& originalMotionEntry, BitSet32 pointerIds) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003387 ALOG_ASSERT(pointerIds.value != 0);
3388
3389 uint32_t splitPointerIndexMap[MAX_POINTERS];
3390 PointerProperties splitPointerProperties[MAX_POINTERS];
3391 PointerCoords splitPointerCoords[MAX_POINTERS];
3392
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003393 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003394 uint32_t splitPointerCount = 0;
3395
3396 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003397 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003398 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003399 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003400 uint32_t pointerId = uint32_t(pointerProperties.id);
3401 if (pointerIds.hasBit(pointerId)) {
3402 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
3403 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
3404 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003405 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003406 splitPointerCount += 1;
3407 }
3408 }
3409
3410 if (splitPointerCount != pointerIds.count()) {
3411 // This is bad. We are missing some of the pointers that we expected to deliver.
3412 // Most likely this indicates that we received an ACTION_MOVE events that has
3413 // different pointer ids than we expected based on the previous ACTION_DOWN
3414 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
3415 // in this way.
3416 ALOGW("Dropping split motion event because the pointer count is %d but "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003417 "we expected there to be %d pointers. This probably means we received "
3418 "a broken sequence of pointer ids from the input device.",
3419 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07003420 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003421 }
3422
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003423 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003424 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003425 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
3426 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003427 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
3428 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003429 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003430 uint32_t pointerId = uint32_t(pointerProperties.id);
3431 if (pointerIds.hasBit(pointerId)) {
3432 if (pointerIds.count() == 1) {
3433 // The first/last pointer went down/up.
3434 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003435 ? AMOTION_EVENT_ACTION_DOWN
arthurhungea3f4fc2020-12-21 23:18:53 +08003436 : (originalMotionEntry.flags & AMOTION_EVENT_FLAG_CANCELED) != 0
3437 ? AMOTION_EVENT_ACTION_CANCEL
3438 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003439 } else {
3440 // A secondary pointer went down/up.
3441 uint32_t splitPointerIndex = 0;
3442 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
3443 splitPointerIndex += 1;
3444 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003445 action = maskedAction |
3446 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003447 }
3448 } else {
3449 // An unrelated pointer changed.
3450 action = AMOTION_EVENT_ACTION_MOVE;
3451 }
3452 }
3453
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003454 int32_t newId = mIdGenerator.nextId();
3455 if (ATRACE_ENABLED()) {
3456 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
3457 ") to MotionEvent(id=0x%" PRIx32 ").",
3458 originalMotionEntry.id, newId);
3459 ATRACE_NAME(message.c_str());
3460 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003461 std::unique_ptr<MotionEntry> splitMotionEntry =
3462 std::make_unique<MotionEntry>(newId, originalMotionEntry.eventTime,
3463 originalMotionEntry.deviceId, originalMotionEntry.source,
3464 originalMotionEntry.displayId,
3465 originalMotionEntry.policyFlags, action,
3466 originalMotionEntry.actionButton,
3467 originalMotionEntry.flags, originalMotionEntry.metaState,
3468 originalMotionEntry.buttonState,
3469 originalMotionEntry.classification,
3470 originalMotionEntry.edgeFlags,
3471 originalMotionEntry.xPrecision,
3472 originalMotionEntry.yPrecision,
3473 originalMotionEntry.xCursorPosition,
3474 originalMotionEntry.yCursorPosition,
3475 originalMotionEntry.downTime, splitPointerCount,
3476 splitPointerProperties, splitPointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003477
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003478 if (originalMotionEntry.injectionState) {
3479 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003480 splitMotionEntry->injectionState->refCount += 1;
3481 }
3482
3483 return splitMotionEntry;
3484}
3485
3486void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
3487#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003488 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003489#endif
3490
3491 bool needWake;
3492 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003493 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003494
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003495 std::unique_ptr<ConfigurationChangedEntry> newEntry =
3496 std::make_unique<ConfigurationChangedEntry>(args->id, args->eventTime);
3497 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003498 } // release lock
3499
3500 if (needWake) {
3501 mLooper->wake();
3502 }
3503}
3504
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003505/**
3506 * If one of the meta shortcuts is detected, process them here:
3507 * Meta + Backspace -> generate BACK
3508 * Meta + Enter -> generate HOME
3509 * This will potentially overwrite keyCode and metaState.
3510 */
3511void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003512 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003513 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
3514 int32_t newKeyCode = AKEYCODE_UNKNOWN;
3515 if (keyCode == AKEYCODE_DEL) {
3516 newKeyCode = AKEYCODE_BACK;
3517 } else if (keyCode == AKEYCODE_ENTER) {
3518 newKeyCode = AKEYCODE_HOME;
3519 }
3520 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003521 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003522 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003523 mReplacedKeys[replacement] = newKeyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003524 keyCode = newKeyCode;
3525 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3526 }
3527 } else if (action == AKEY_EVENT_ACTION_UP) {
3528 // In order to maintain a consistent stream of up and down events, check to see if the key
3529 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
3530 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003531 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003532 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003533 auto replacementIt = mReplacedKeys.find(replacement);
3534 if (replacementIt != mReplacedKeys.end()) {
3535 keyCode = replacementIt->second;
3536 mReplacedKeys.erase(replacementIt);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003537 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3538 }
3539 }
3540}
3541
Michael Wrightd02c5b62014-02-10 15:10:22 -08003542void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
3543#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003544 ALOGD("notifyKey - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
3545 "policyFlags=0x%x, action=0x%x, "
3546 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
3547 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
3548 args->action, args->flags, args->keyCode, args->scanCode, args->metaState,
3549 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003550#endif
3551 if (!validateKeyEvent(args->action)) {
3552 return;
3553 }
3554
3555 uint32_t policyFlags = args->policyFlags;
3556 int32_t flags = args->flags;
3557 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07003558 // InputDispatcher tracks and generates key repeats on behalf of
3559 // whatever notifies it, so repeatCount should always be set to 0
3560 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003561 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
3562 policyFlags |= POLICY_FLAG_VIRTUAL;
3563 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
3564 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003565 if (policyFlags & POLICY_FLAG_FUNCTION) {
3566 metaState |= AMETA_FUNCTION_ON;
3567 }
3568
3569 policyFlags |= POLICY_FLAG_TRUSTED;
3570
Michael Wright78f24442014-08-06 15:55:28 -07003571 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003572 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07003573
Michael Wrightd02c5b62014-02-10 15:10:22 -08003574 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003575 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08003576 args->action, flags, keyCode, args->scanCode, metaState, repeatCount,
3577 args->downTime, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003578
Michael Wright2b3c3302018-03-02 17:19:13 +00003579 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003580 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003581 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3582 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003583 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003584 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003585
Michael Wrightd02c5b62014-02-10 15:10:22 -08003586 bool needWake;
3587 { // acquire lock
3588 mLock.lock();
3589
3590 if (shouldSendKeyToInputFilterLocked(args)) {
3591 mLock.unlock();
3592
3593 policyFlags |= POLICY_FLAG_FILTERED;
3594 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3595 return; // event was consumed by the filter
3596 }
3597
3598 mLock.lock();
3599 }
3600
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003601 std::unique_ptr<KeyEntry> newEntry =
3602 std::make_unique<KeyEntry>(args->id, args->eventTime, args->deviceId, args->source,
3603 args->displayId, policyFlags, args->action, flags,
3604 keyCode, args->scanCode, metaState, repeatCount,
3605 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003606
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003607 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003608 mLock.unlock();
3609 } // release lock
3610
3611 if (needWake) {
3612 mLooper->wake();
3613 }
3614}
3615
3616bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
3617 return mInputFilterEnabled;
3618}
3619
3620void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
3621#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003622 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
3623 "displayId=%" PRId32 ", policyFlags=0x%x, "
Garfield Tan00f511d2019-06-12 16:55:40 -07003624 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
3625 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
Garfield Tanab0ab9c2019-07-10 18:58:28 -07003626 "yCursorPosition=%f, downTime=%" PRId64,
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003627 args->id, args->eventTime, args->deviceId, args->source, args->displayId,
3628 args->policyFlags, args->action, args->actionButton, args->flags, args->metaState,
3629 args->buttonState, args->edgeFlags, args->xPrecision, args->yPrecision,
3630 args->xCursorPosition, args->yCursorPosition, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003631 for (uint32_t i = 0; i < args->pointerCount; i++) {
3632 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003633 "x=%f, y=%f, pressure=%f, size=%f, "
3634 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
3635 "orientation=%f",
3636 i, args->pointerProperties[i].id, args->pointerProperties[i].toolType,
3637 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
3638 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
3639 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
3640 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
3641 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
3642 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
3643 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
3644 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
3645 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003646 }
3647#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003648 if (!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
3649 args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003650 return;
3651 }
3652
3653 uint32_t policyFlags = args->policyFlags;
3654 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003655
3656 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08003657 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003658 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3659 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003660 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003661 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003662
3663 bool needWake;
3664 { // acquire lock
3665 mLock.lock();
3666
3667 if (shouldSendMotionToInputFilterLocked(args)) {
3668 mLock.unlock();
3669
3670 MotionEvent event;
chaviw9eaa22c2020-07-01 16:21:27 -07003671 ui::Transform transform;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003672 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
3673 args->action, args->actionButton, args->flags, args->edgeFlags,
chaviw9eaa22c2020-07-01 16:21:27 -07003674 args->metaState, args->buttonState, args->classification, transform,
3675 args->xPrecision, args->yPrecision, args->xCursorPosition,
3676 args->yCursorPosition, args->downTime, args->eventTime,
3677 args->pointerCount, args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003678
3679 policyFlags |= POLICY_FLAG_FILTERED;
3680 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3681 return; // event was consumed by the filter
3682 }
3683
3684 mLock.lock();
3685 }
3686
3687 // Just enqueue a new motion event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003688 std::unique_ptr<MotionEntry> newEntry =
3689 std::make_unique<MotionEntry>(args->id, args->eventTime, args->deviceId,
3690 args->source, args->displayId, policyFlags,
3691 args->action, args->actionButton, args->flags,
3692 args->metaState, args->buttonState,
3693 args->classification, args->edgeFlags,
3694 args->xPrecision, args->yPrecision,
3695 args->xCursorPosition, args->yCursorPosition,
3696 args->downTime, args->pointerCount,
3697 args->pointerProperties, args->pointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003698
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003699 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003700 mLock.unlock();
3701 } // release lock
3702
3703 if (needWake) {
3704 mLooper->wake();
3705 }
3706}
3707
Chris Yef59a2f42020-10-16 12:55:26 -07003708void InputDispatcher::notifySensor(const NotifySensorArgs* args) {
3709#if DEBUG_INBOUND_EVENT_DETAILS
3710 ALOGD("notifySensor - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
3711 " sensorType=%s",
3712 args->id, args->eventTime, args->deviceId, args->source,
3713 NamedEnum::string(args->sensorType).c_str());
3714#endif
3715
3716 bool needWake;
3717 { // acquire lock
3718 mLock.lock();
3719
3720 // Just enqueue a new sensor event.
3721 std::unique_ptr<SensorEntry> newEntry =
3722 std::make_unique<SensorEntry>(args->id, args->eventTime, args->deviceId,
3723 args->source, 0 /* policyFlags*/, args->hwTimestamp,
3724 args->sensorType, args->accuracy,
3725 args->accuracyChanged, args->values);
3726
3727 needWake = enqueueInboundEventLocked(std::move(newEntry));
3728 mLock.unlock();
3729 } // release lock
3730
3731 if (needWake) {
3732 mLooper->wake();
3733 }
3734}
3735
Michael Wrightd02c5b62014-02-10 15:10:22 -08003736bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08003737 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003738}
3739
3740void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
3741#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003742 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003743 "switchMask=0x%08x",
3744 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003745#endif
3746
3747 uint32_t policyFlags = args->policyFlags;
3748 policyFlags |= POLICY_FLAG_TRUSTED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003749 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003750}
3751
3752void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
3753#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003754 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
3755 args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003756#endif
3757
3758 bool needWake;
3759 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003760 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003761
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003762 std::unique_ptr<DeviceResetEntry> newEntry =
3763 std::make_unique<DeviceResetEntry>(args->id, args->eventTime, args->deviceId);
3764 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003765 } // release lock
3766
3767 if (needWake) {
3768 mLooper->wake();
3769 }
3770}
3771
Prabir Pradhan7e186182020-11-10 13:56:45 -08003772void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs* args) {
3773#if DEBUG_INBOUND_EVENT_DETAILS
3774 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args->eventTime,
3775 args->enabled ? "true" : "false");
3776#endif
3777
Prabir Pradhan99987712020-11-10 18:43:05 -08003778 bool needWake;
3779 { // acquire lock
3780 std::scoped_lock _l(mLock);
3781 auto entry = std::make_unique<PointerCaptureChangedEntry>(args->id, args->eventTime,
3782 args->enabled);
3783 needWake = enqueueInboundEventLocked(std::move(entry));
3784 } // release lock
3785
3786 if (needWake) {
3787 mLooper->wake();
3788 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08003789}
3790
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003791InputEventInjectionResult InputDispatcher::injectInputEvent(
3792 const InputEvent* event, int32_t injectorPid, int32_t injectorUid,
3793 InputEventInjectionSync syncMode, std::chrono::milliseconds timeout, uint32_t policyFlags) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003794#if DEBUG_INBOUND_EVENT_DETAILS
3795 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003796 "syncMode=%d, timeout=%lld, policyFlags=0x%08x",
3797 event->getType(), injectorPid, injectorUid, syncMode, timeout.count(), policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003798#endif
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003799 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003800
3801 policyFlags |= POLICY_FLAG_INJECTED;
3802 if (hasInjectionPermission(injectorPid, injectorUid)) {
3803 policyFlags |= POLICY_FLAG_TRUSTED;
3804 }
3805
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003806 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003807 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003808 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003809 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
3810 int32_t action = incomingKey.getAction();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003811 if (!validateKeyEvent(action)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003812 return InputEventInjectionResult::FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003813 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003814
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003815 int32_t flags = incomingKey.getFlags();
3816 int32_t keyCode = incomingKey.getKeyCode();
3817 int32_t metaState = incomingKey.getMetaState();
3818 accelerateMetaShortcuts(VIRTUAL_KEYBOARD_ID, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003819 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003820 KeyEvent keyEvent;
Garfield Tan4cc839f2020-01-24 11:26:14 -08003821 keyEvent.initialize(incomingKey.getId(), VIRTUAL_KEYBOARD_ID, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003822 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
3823 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
3824 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003825
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003826 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
3827 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00003828 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003829
3830 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
3831 android::base::Timer t;
3832 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
3833 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3834 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
3835 std::to_string(t.duration().count()).c_str());
3836 }
3837 }
3838
3839 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003840 std::unique_ptr<KeyEntry> injectedEntry =
3841 std::make_unique<KeyEntry>(incomingKey.getId(), incomingKey.getEventTime(),
3842 VIRTUAL_KEYBOARD_ID, incomingKey.getSource(),
3843 incomingKey.getDisplayId(), policyFlags, action,
3844 flags, keyCode, incomingKey.getScanCode(), metaState,
3845 incomingKey.getRepeatCount(),
3846 incomingKey.getDownTime());
3847 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003848 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003849 }
3850
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003851 case AINPUT_EVENT_TYPE_MOTION: {
3852 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
3853 int32_t action = motionEvent->getAction();
3854 size_t pointerCount = motionEvent->getPointerCount();
3855 const PointerProperties* pointerProperties = motionEvent->getPointerProperties();
3856 int32_t actionButton = motionEvent->getActionButton();
3857 int32_t displayId = motionEvent->getDisplayId();
3858 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003859 return InputEventInjectionResult::FAILED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003860 }
3861
3862 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
3863 nsecs_t eventTime = motionEvent->getEventTime();
3864 android::base::Timer t;
3865 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
3866 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3867 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
3868 std::to_string(t.duration().count()).c_str());
3869 }
3870 }
3871
3872 mLock.lock();
3873 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
3874 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003875 std::unique_ptr<MotionEntry> injectedEntry =
3876 std::make_unique<MotionEntry>(motionEvent->getId(), *sampleEventTimes,
3877 VIRTUAL_KEYBOARD_ID, motionEvent->getSource(),
3878 motionEvent->getDisplayId(), policyFlags, action,
3879 actionButton, motionEvent->getFlags(),
3880 motionEvent->getMetaState(),
3881 motionEvent->getButtonState(),
3882 motionEvent->getClassification(),
3883 motionEvent->getEdgeFlags(),
3884 motionEvent->getXPrecision(),
3885 motionEvent->getYPrecision(),
3886 motionEvent->getRawXCursorPosition(),
3887 motionEvent->getRawYCursorPosition(),
3888 motionEvent->getDownTime(),
3889 uint32_t(pointerCount), pointerProperties,
3890 samplePointerCoords, motionEvent->getXOffset(),
3891 motionEvent->getYOffset());
3892 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003893 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
3894 sampleEventTimes += 1;
3895 samplePointerCoords += pointerCount;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003896 std::unique_ptr<MotionEntry> nextInjectedEntry =
3897 std::make_unique<MotionEntry>(motionEvent->getId(), *sampleEventTimes,
3898 VIRTUAL_KEYBOARD_ID, motionEvent->getSource(),
3899 motionEvent->getDisplayId(), policyFlags,
3900 action, actionButton, motionEvent->getFlags(),
3901 motionEvent->getMetaState(),
3902 motionEvent->getButtonState(),
3903 motionEvent->getClassification(),
3904 motionEvent->getEdgeFlags(),
3905 motionEvent->getXPrecision(),
3906 motionEvent->getYPrecision(),
3907 motionEvent->getRawXCursorPosition(),
3908 motionEvent->getRawYCursorPosition(),
3909 motionEvent->getDownTime(),
3910 uint32_t(pointerCount), pointerProperties,
3911 samplePointerCoords,
3912 motionEvent->getXOffset(),
3913 motionEvent->getYOffset());
3914 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003915 }
3916 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003917 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003918
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003919 default:
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08003920 ALOGW("Cannot inject %s events", inputEventTypeToString(event->getType()));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003921 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003922 }
3923
3924 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003925 if (syncMode == InputEventInjectionSync::NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003926 injectionState->injectionIsAsync = true;
3927 }
3928
3929 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003930 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003931
3932 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003933 while (!injectedEntries.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003934 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003935 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003936 }
3937
3938 mLock.unlock();
3939
3940 if (needWake) {
3941 mLooper->wake();
3942 }
3943
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003944 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003945 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003946 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003947
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003948 if (syncMode == InputEventInjectionSync::NONE) {
3949 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003950 } else {
3951 for (;;) {
3952 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003953 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003954 break;
3955 }
3956
3957 nsecs_t remainingTimeout = endTime - now();
3958 if (remainingTimeout <= 0) {
3959#if DEBUG_INJECTION
3960 ALOGD("injectInputEvent - Timed out waiting for injection result "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003961 "to become available.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003962#endif
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003963 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003964 break;
3965 }
3966
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003967 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003968 }
3969
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003970 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
3971 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003972 while (injectionState->pendingForegroundDispatches != 0) {
3973#if DEBUG_INJECTION
3974 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003975 injectionState->pendingForegroundDispatches);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003976#endif
3977 nsecs_t remainingTimeout = endTime - now();
3978 if (remainingTimeout <= 0) {
3979#if DEBUG_INJECTION
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003980 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
3981 "dispatches to finish.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003982#endif
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003983 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003984 break;
3985 }
3986
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003987 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003988 }
3989 }
3990 }
3991
3992 injectionState->release();
3993 } // release lock
3994
3995#if DEBUG_INJECTION
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003996 ALOGD("injectInputEvent - Finished with result %d. injectorPid=%d, injectorUid=%d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003997 injectionResult, injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003998#endif
3999
4000 return injectionResult;
4001}
4002
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004003std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05004004 std::array<uint8_t, 32> calculatedHmac;
4005 std::unique_ptr<VerifiedInputEvent> result;
4006 switch (event.getType()) {
4007 case AINPUT_EVENT_TYPE_KEY: {
4008 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
4009 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
4010 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004011 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05004012 break;
4013 }
4014 case AINPUT_EVENT_TYPE_MOTION: {
4015 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
4016 VerifiedMotionEvent verifiedMotionEvent =
4017 verifiedMotionEventFromMotionEvent(motionEvent);
4018 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004019 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05004020 break;
4021 }
4022 default: {
4023 ALOGE("Cannot verify events of type %" PRId32, event.getType());
4024 return nullptr;
4025 }
4026 }
4027 if (calculatedHmac == INVALID_HMAC) {
4028 return nullptr;
4029 }
4030 if (calculatedHmac != event.getHmac()) {
4031 return nullptr;
4032 }
4033 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004034}
4035
Michael Wrightd02c5b62014-02-10 15:10:22 -08004036bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004037 return injectorUid == 0 ||
4038 mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004039}
4040
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004041void InputDispatcher::setInjectionResult(EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004042 InputEventInjectionResult injectionResult) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004043 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004044 if (injectionState) {
4045#if DEBUG_INJECTION
4046 ALOGD("Setting input event injection result to %d. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004047 "injectorPid=%d, injectorUid=%d",
4048 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004049#endif
4050
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004051 if (injectionState->injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004052 // Log the outcome since the injector did not wait for the injection result.
4053 switch (injectionResult) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004054 case InputEventInjectionResult::SUCCEEDED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004055 ALOGV("Asynchronous input event injection succeeded.");
4056 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004057 case InputEventInjectionResult::FAILED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004058 ALOGW("Asynchronous input event injection failed.");
4059 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004060 case InputEventInjectionResult::PERMISSION_DENIED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004061 ALOGW("Asynchronous input event injection permission denied.");
4062 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004063 case InputEventInjectionResult::TIMED_OUT:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004064 ALOGW("Asynchronous input event injection timed out.");
4065 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004066 case InputEventInjectionResult::PENDING:
4067 ALOGE("Setting result to 'PENDING' for asynchronous injection");
4068 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004069 }
4070 }
4071
4072 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004073 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004074 }
4075}
4076
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004077void InputDispatcher::incrementPendingForegroundDispatches(EventEntry& entry) {
4078 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004079 if (injectionState) {
4080 injectionState->pendingForegroundDispatches += 1;
4081 }
4082}
4083
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004084void InputDispatcher::decrementPendingForegroundDispatches(EventEntry& entry) {
4085 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004086 if (injectionState) {
4087 injectionState->pendingForegroundDispatches -= 1;
4088
4089 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004090 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004091 }
4092 }
4093}
4094
Vishnu Nairad321cd2020-08-20 16:40:21 -07004095const std::vector<sp<InputWindowHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004096 int32_t displayId) const {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004097 static const std::vector<sp<InputWindowHandle>> EMPTY_WINDOW_HANDLES;
4098 auto it = mWindowHandlesByDisplay.find(displayId);
4099 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08004100}
4101
Michael Wrightd02c5b62014-02-10 15:10:22 -08004102sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08004103 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08004104 if (windowHandleToken == nullptr) {
4105 return nullptr;
4106 }
4107
Arthur Hungb92218b2018-08-14 12:00:21 +08004108 for (auto& it : mWindowHandlesByDisplay) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004109 const std::vector<sp<InputWindowHandle>>& windowHandles = it.second;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004110 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004111 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004112 return windowHandle;
4113 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004114 }
4115 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004116 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004117}
4118
Vishnu Nairad321cd2020-08-20 16:40:21 -07004119sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(const sp<IBinder>& windowHandleToken,
4120 int displayId) const {
4121 if (windowHandleToken == nullptr) {
4122 return nullptr;
4123 }
4124
4125 for (const sp<InputWindowHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
4126 if (windowHandle->getToken() == windowHandleToken) {
4127 return windowHandle;
4128 }
4129 }
4130 return nullptr;
4131}
4132
4133sp<InputWindowHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
4134 sp<IBinder> focusedToken = getValueByKey(mFocusedWindowTokenByDisplay, displayId);
4135 return getWindowHandleLocked(focusedToken, displayId);
4136}
4137
Mady Mellor017bcd12020-06-23 19:12:00 +00004138bool InputDispatcher::hasWindowHandleLocked(const sp<InputWindowHandle>& windowHandle) const {
4139 for (auto& it : mWindowHandlesByDisplay) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004140 const std::vector<sp<InputWindowHandle>>& windowHandles = it.second;
Mady Mellor017bcd12020-06-23 19:12:00 +00004141 for (const sp<InputWindowHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08004142 if (handle->getId() == windowHandle->getId() &&
4143 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004144 if (windowHandle->getInfo()->displayId != it.first) {
4145 ALOGE("Found window %s in display %" PRId32
4146 ", but it should belong to display %" PRId32,
4147 windowHandle->getName().c_str(), it.first,
4148 windowHandle->getInfo()->displayId);
4149 }
4150 return true;
Arthur Hungb92218b2018-08-14 12:00:21 +08004151 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004152 }
4153 }
4154 return false;
4155}
4156
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004157bool InputDispatcher::hasResponsiveConnectionLocked(InputWindowHandle& windowHandle) const {
4158 sp<Connection> connection = getConnectionLocked(windowHandle.getToken());
4159 const bool noInputChannel =
4160 windowHandle.getInfo()->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
4161 if (connection != nullptr && noInputChannel) {
4162 ALOGW("%s has feature NO_INPUT_CHANNEL, but it matched to connection %s",
4163 windowHandle.getName().c_str(), connection->inputChannel->getName().c_str());
4164 return false;
4165 }
4166
4167 if (connection == nullptr) {
4168 if (!noInputChannel) {
4169 ALOGI("Could not find connection for %s", windowHandle.getName().c_str());
4170 }
4171 return false;
4172 }
4173 if (!connection->responsive) {
4174 ALOGW("Window %s is not responsive", windowHandle.getName().c_str());
4175 return false;
4176 }
4177 return true;
4178}
4179
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004180std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
4181 const sp<IBinder>& token) const {
Robert Carr5c8a0262018-10-03 16:30:44 -07004182 size_t count = mInputChannelsByToken.count(token);
4183 if (count == 0) {
4184 return nullptr;
4185 }
4186 return mInputChannelsByToken.at(token);
4187}
4188
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004189void InputDispatcher::updateWindowHandlesForDisplayLocked(
4190 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
4191 if (inputWindowHandles.empty()) {
4192 // Remove all handles on a display if there are no windows left.
4193 mWindowHandlesByDisplay.erase(displayId);
4194 return;
4195 }
4196
4197 // Since we compare the pointer of input window handles across window updates, we need
4198 // to make sure the handle object for the same window stays unchanged across updates.
4199 const std::vector<sp<InputWindowHandle>>& oldHandles = getWindowHandlesLocked(displayId);
chaviwaf87b3e2019-10-01 16:59:28 -07004200 std::unordered_map<int32_t /*id*/, sp<InputWindowHandle>> oldHandlesById;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004201 for (const sp<InputWindowHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07004202 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004203 }
4204
4205 std::vector<sp<InputWindowHandle>> newHandles;
4206 for (const sp<InputWindowHandle>& handle : inputWindowHandles) {
4207 if (!handle->updateInfo()) {
4208 // handle no longer valid
4209 continue;
4210 }
4211
4212 const InputWindowInfo* info = handle->getInfo();
4213 if ((getInputChannelLocked(handle->getToken()) == nullptr &&
4214 info->portalToDisplayId == ADISPLAY_ID_NONE)) {
4215 const bool noInputChannel =
Michael Wright44753b12020-07-08 13:48:11 +01004216 info->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
4217 const bool canReceiveInput = !info->flags.test(InputWindowInfo::Flag::NOT_TOUCHABLE) ||
4218 !info->flags.test(InputWindowInfo::Flag::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004219 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07004220 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004221 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07004222 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004223 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004224 }
4225
4226 if (info->displayId != displayId) {
4227 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
4228 handle->getName().c_str(), displayId, info->displayId);
4229 continue;
4230 }
4231
Robert Carredd13602020-04-13 17:24:34 -07004232 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
4233 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviwaf87b3e2019-10-01 16:59:28 -07004234 const sp<InputWindowHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004235 oldHandle->updateFrom(handle);
4236 newHandles.push_back(oldHandle);
4237 } else {
4238 newHandles.push_back(handle);
4239 }
4240 }
4241
4242 // Insert or replace
4243 mWindowHandlesByDisplay[displayId] = newHandles;
4244}
4245
Arthur Hung72d8dc32020-03-28 00:48:39 +00004246void InputDispatcher::setInputWindows(
4247 const std::unordered_map<int32_t, std::vector<sp<InputWindowHandle>>>& handlesPerDisplay) {
4248 { // acquire lock
4249 std::scoped_lock _l(mLock);
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004250 for (const auto& [displayId, handles] : handlesPerDisplay) {
4251 setInputWindowsLocked(handles, displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004252 }
4253 }
4254 // Wake up poll loop since it may need to make new input dispatching choices.
4255 mLooper->wake();
4256}
4257
Arthur Hungb92218b2018-08-14 12:00:21 +08004258/**
4259 * Called from InputManagerService, update window handle list by displayId that can receive input.
4260 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
4261 * If set an empty list, remove all handles from the specific display.
4262 * For focused handle, check if need to change and send a cancel event to previous one.
4263 * For removed handle, check if need to send a cancel event if already in touch.
4264 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00004265void InputDispatcher::setInputWindowsLocked(
4266 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004267 if (DEBUG_FOCUS) {
4268 std::string windowList;
4269 for (const sp<InputWindowHandle>& iwh : inputWindowHandles) {
4270 windowList += iwh->getName() + " ";
4271 }
4272 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
4273 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004274
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004275 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
4276 for (const sp<InputWindowHandle>& window : inputWindowHandles) {
4277 const bool noInputWindow =
4278 window->getInfo()->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
4279 if (noInputWindow && window->getToken() != nullptr) {
4280 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
4281 window->getName().c_str());
4282 window->releaseChannel();
4283 }
4284 }
4285
Arthur Hung72d8dc32020-03-28 00:48:39 +00004286 // Copy old handles for release if they are no longer present.
4287 const std::vector<sp<InputWindowHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004288
Arthur Hung72d8dc32020-03-28 00:48:39 +00004289 updateWindowHandlesForDisplayLocked(inputWindowHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004290
Vishnu Nair958da932020-08-21 17:12:37 -07004291 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
4292 if (mLastHoverWindowHandle &&
4293 std::find(windowHandles.begin(), windowHandles.end(), mLastHoverWindowHandle) ==
4294 windowHandles.end()) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004295 mLastHoverWindowHandle = nullptr;
4296 }
4297
Vishnu Nair958da932020-08-21 17:12:37 -07004298 sp<IBinder> focusedToken = getValueByKey(mFocusedWindowTokenByDisplay, displayId);
4299 if (focusedToken) {
4300 FocusResult result = checkTokenFocusableLocked(focusedToken, displayId);
4301 if (result != FocusResult::OK) {
4302 onFocusChangedLocked(focusedToken, nullptr, displayId, typeToString(result));
4303 }
4304 }
4305
4306 std::optional<FocusRequest> focusRequest =
4307 getOptionalValueByKey(mPendingFocusRequests, displayId);
4308 if (focusRequest) {
4309 // If the window from the pending request is now visible, provide it focus.
4310 FocusResult result = handleFocusRequestLocked(*focusRequest);
4311 if (result != FocusResult::NOT_VISIBLE) {
4312 // Drop the request if we were able to change the focus or we cannot change
4313 // it for another reason.
4314 mPendingFocusRequests.erase(displayId);
4315 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004316 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004317
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004318 std::unordered_map<int32_t, TouchState>::iterator stateIt =
4319 mTouchStatesByDisplay.find(displayId);
4320 if (stateIt != mTouchStatesByDisplay.end()) {
4321 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00004322 for (size_t i = 0; i < state.windows.size();) {
4323 TouchedWindow& touchedWindow = state.windows[i];
Mady Mellor017bcd12020-06-23 19:12:00 +00004324 if (!hasWindowHandleLocked(touchedWindow.windowHandle)) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004325 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004326 ALOGD("Touched window was removed: %s in display %" PRId32,
4327 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004328 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004329 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00004330 getInputChannelLocked(touchedWindow.windowHandle->getToken());
4331 if (touchedInputChannel != nullptr) {
4332 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4333 "touched window was removed");
4334 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004335 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004336 state.windows.erase(state.windows.begin() + i);
4337 } else {
4338 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004339 }
4340 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004341 }
Arthur Hung25e2af12020-03-26 12:58:37 +00004342
Arthur Hung72d8dc32020-03-28 00:48:39 +00004343 // Release information for windows that are no longer present.
4344 // This ensures that unused input channels are released promptly.
4345 // Otherwise, they might stick around until the window handle is destroyed
4346 // which might not happen until the next GC.
4347 for (const sp<InputWindowHandle>& oldWindowHandle : oldWindowHandles) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004348 if (!hasWindowHandleLocked(oldWindowHandle)) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004349 if (DEBUG_FOCUS) {
4350 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00004351 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004352 oldWindowHandle->releaseChannel();
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004353 // To avoid making too many calls into the compat framework, only
4354 // check for window flags when windows are going away.
4355 // TODO(b/157929241) : delete this. This is only needed temporarily
4356 // in order to gather some data about the flag usage
4357 if (oldWindowHandle->getInfo()->flags.test(InputWindowInfo::Flag::SLIPPERY)) {
4358 ALOGW("%s has FLAG_SLIPPERY. Please report this in b/157929241",
4359 oldWindowHandle->getName().c_str());
4360 if (mCompatService != nullptr) {
4361 mCompatService->reportChangeByUid(IInputConstants::BLOCK_FLAG_SLIPPERY,
4362 oldWindowHandle->getInfo()->ownerUid);
4363 }
4364 }
Arthur Hung25e2af12020-03-26 12:58:37 +00004365 }
chaviw291d88a2019-02-14 10:33:58 -08004366 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004367}
4368
4369void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07004370 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004371 if (DEBUG_FOCUS) {
4372 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
4373 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
4374 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004375 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004376 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004377
Chris Yea209fde2020-07-22 13:54:51 -07004378 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08004379 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004380
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004381 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
4382 return; // This application is already focused. No need to wake up or change anything.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004383 }
4384
Chris Yea209fde2020-07-22 13:54:51 -07004385 // Set the new application handle.
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004386 if (inputApplicationHandle != nullptr) {
4387 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
4388 } else {
4389 mFocusedApplicationHandlesByDisplay.erase(displayId);
4390 }
4391
4392 // No matter what the old focused application was, stop waiting on it because it is
4393 // no longer focused.
4394 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004395 } // release lock
4396
4397 // Wake up poll loop since it may need to make new input dispatching choices.
4398 mLooper->wake();
4399}
4400
Tiger Huang721e26f2018-07-24 22:26:19 +08004401/**
4402 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
4403 * the display not specified.
4404 *
4405 * We track any unreleased events for each window. If a window loses the ability to receive the
4406 * released event, we will send a cancel event to it. So when the focused display is changed, we
4407 * cancel all the unreleased display-unspecified events for the focused window on the old focused
4408 * display. The display-specified events won't be affected.
4409 */
4410void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004411 if (DEBUG_FOCUS) {
4412 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
4413 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004414 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004415 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08004416
4417 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004418 sp<IBinder> oldFocusedWindowToken =
4419 getValueByKey(mFocusedWindowTokenByDisplay, mFocusedDisplayId);
4420 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004421 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07004422 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08004423 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004424 CancelationOptions
4425 options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
4426 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004427 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08004428 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
4429 }
4430 }
4431 mFocusedDisplayId = displayId;
4432
Chris Ye3c2d6f52020-08-09 10:39:48 -07004433 // Find new focused window and validate
Vishnu Nairad321cd2020-08-20 16:40:21 -07004434 sp<IBinder> newFocusedWindowToken =
4435 getValueByKey(mFocusedWindowTokenByDisplay, displayId);
4436 notifyFocusChangedLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08004437
Vishnu Nairad321cd2020-08-20 16:40:21 -07004438 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08004439 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07004440 if (!mFocusedWindowTokenByDisplay.empty()) {
4441 ALOGE("But another display has a focused window\n%s",
4442 dumpFocusedWindowsLocked().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08004443 }
4444 }
4445 }
4446
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004447 if (DEBUG_FOCUS) {
4448 logDispatchStateLocked();
4449 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004450 } // release lock
4451
4452 // Wake up poll loop since it may need to make new input dispatching choices.
4453 mLooper->wake();
4454}
4455
Michael Wrightd02c5b62014-02-10 15:10:22 -08004456void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004457 if (DEBUG_FOCUS) {
4458 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
4459 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004460
4461 bool changed;
4462 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004463 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004464
4465 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
4466 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004467 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004468 }
4469
4470 if (mDispatchEnabled && !enabled) {
4471 resetAndDropEverythingLocked("dispatcher is being disabled");
4472 }
4473
4474 mDispatchEnabled = enabled;
4475 mDispatchFrozen = frozen;
4476 changed = true;
4477 } else {
4478 changed = false;
4479 }
4480
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004481 if (DEBUG_FOCUS) {
4482 logDispatchStateLocked();
4483 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004484 } // release lock
4485
4486 if (changed) {
4487 // Wake up poll loop since it may need to make new input dispatching choices.
4488 mLooper->wake();
4489 }
4490}
4491
4492void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004493 if (DEBUG_FOCUS) {
4494 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
4495 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004496
4497 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004498 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004499
4500 if (mInputFilterEnabled == enabled) {
4501 return;
4502 }
4503
4504 mInputFilterEnabled = enabled;
4505 resetAndDropEverythingLocked("input filter is being enabled or disabled");
4506 } // release lock
4507
4508 // Wake up poll loop since there might be work to do to drop everything.
4509 mLooper->wake();
4510}
4511
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08004512void InputDispatcher::setInTouchMode(bool inTouchMode) {
4513 std::scoped_lock lock(mLock);
4514 mInTouchMode = inTouchMode;
4515}
4516
Bernardo Rufinoea97d182020-08-19 14:43:14 +01004517void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
4518 if (opacity < 0 || opacity > 1) {
4519 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
4520 return;
4521 }
4522
4523 std::scoped_lock lock(mLock);
4524 mMaximumObscuringOpacityForTouch = opacity;
4525}
4526
4527void InputDispatcher::setBlockUntrustedTouchesMode(BlockUntrustedTouchesMode mode) {
4528 std::scoped_lock lock(mLock);
4529 mBlockUntrustedTouchesMode = mode;
4530}
4531
chaviwfbe5d9c2018-12-26 12:23:37 -08004532bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken) {
4533 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004534 if (DEBUG_FOCUS) {
4535 ALOGD("Trivial transfer to same window.");
4536 }
chaviwfbe5d9c2018-12-26 12:23:37 -08004537 return true;
4538 }
4539
Michael Wrightd02c5b62014-02-10 15:10:22 -08004540 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004541 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004542
chaviwfbe5d9c2018-12-26 12:23:37 -08004543 sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromToken);
4544 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toToken);
Yi Kong9b14ac62018-07-17 13:48:38 -07004545 if (fromWindowHandle == nullptr || toWindowHandle == nullptr) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004546 ALOGW("Cannot transfer focus because from or to window not found.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004547 return false;
4548 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004549 if (DEBUG_FOCUS) {
4550 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
4551 fromWindowHandle->getName().c_str(), toWindowHandle->getName().c_str());
4552 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004553 if (fromWindowHandle->getInfo()->displayId != toWindowHandle->getInfo()->displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004554 if (DEBUG_FOCUS) {
4555 ALOGD("Cannot transfer focus because windows are on different displays.");
4556 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004557 return false;
4558 }
4559
4560 bool found = false;
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004561 for (std::pair<const int32_t, TouchState>& pair : mTouchStatesByDisplay) {
4562 TouchState& state = pair.second;
Jeff Brownf086ddb2014-02-11 14:28:48 -08004563 for (size_t i = 0; i < state.windows.size(); i++) {
4564 const TouchedWindow& touchedWindow = state.windows[i];
4565 if (touchedWindow.windowHandle == fromWindowHandle) {
4566 int32_t oldTargetFlags = touchedWindow.targetFlags;
4567 BitSet32 pointerIds = touchedWindow.pointerIds;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004568
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004569 state.windows.erase(state.windows.begin() + i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004570
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004571 int32_t newTargetFlags = oldTargetFlags &
4572 (InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_SPLIT |
4573 InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004574 state.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004575
Jeff Brownf086ddb2014-02-11 14:28:48 -08004576 found = true;
4577 goto Found;
4578 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004579 }
4580 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004581 Found:
Michael Wrightd02c5b62014-02-10 15:10:22 -08004582
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004583 if (!found) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004584 if (DEBUG_FOCUS) {
4585 ALOGD("Focus transfer failed because from window did not have focus.");
4586 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004587 return false;
4588 }
4589
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004590 sp<Connection> fromConnection = getConnectionLocked(fromToken);
4591 sp<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004592 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004593 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004594 CancelationOptions
4595 options(CancelationOptions::CANCEL_POINTER_EVENTS,
4596 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004597 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004598 synthesizePointerDownEventsForConnectionLocked(toConnection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004599 }
4600
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004601 if (DEBUG_FOCUS) {
4602 logDispatchStateLocked();
4603 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004604 } // release lock
4605
4606 // Wake up poll loop since it may need to make new input dispatching choices.
4607 mLooper->wake();
4608 return true;
4609}
4610
4611void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004612 if (DEBUG_FOCUS) {
4613 ALOGD("Resetting and dropping all events (%s).", reason);
4614 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004615
4616 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
4617 synthesizeCancelationEventsForAllConnectionsLocked(options);
4618
4619 resetKeyRepeatLocked();
4620 releasePendingEventLocked();
4621 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004622 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004623
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004624 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08004625 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004626 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07004627 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004628}
4629
4630void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004631 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004632 dumpDispatchStateLocked(dump);
4633
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004634 std::istringstream stream(dump);
4635 std::string line;
4636
4637 while (std::getline(stream, line, '\n')) {
4638 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004639 }
4640}
4641
Vishnu Nairad321cd2020-08-20 16:40:21 -07004642std::string InputDispatcher::dumpFocusedWindowsLocked() {
4643 if (mFocusedWindowTokenByDisplay.empty()) {
4644 return INDENT "FocusedWindows: <none>\n";
4645 }
4646
4647 std::string dump;
4648 dump += INDENT "FocusedWindows:\n";
4649 for (auto& it : mFocusedWindowTokenByDisplay) {
4650 const int32_t displayId = it.first;
4651 const sp<InputWindowHandle> windowHandle = getFocusedWindowHandleLocked(displayId);
4652 if (windowHandle) {
4653 dump += StringPrintf(INDENT2 "displayId=%" PRId32 ", name='%s'\n", displayId,
4654 windowHandle->getName().c_str());
4655 } else {
4656 dump += StringPrintf(INDENT2 "displayId=%" PRId32
4657 " has focused token without a window'\n",
4658 displayId);
4659 }
4660 }
4661 return dump;
4662}
4663
Siarhei Vishniakouad991402020-10-28 11:40:09 -05004664std::string InputDispatcher::dumpPendingFocusRequestsLocked() {
4665 if (mPendingFocusRequests.empty()) {
4666 return INDENT "mPendingFocusRequests: <none>\n";
4667 }
4668
4669 std::string dump;
4670 dump += INDENT "mPendingFocusRequests:\n";
4671 for (const auto& [displayId, focusRequest] : mPendingFocusRequests) {
4672 // Rather than printing raw values for focusRequest.token and focusRequest.focusedToken,
4673 // try to resolve them to actual windows.
4674 std::string windowName = getConnectionNameLocked(focusRequest.token);
4675 std::string focusedWindowName = getConnectionNameLocked(focusRequest.focusedToken);
4676 dump += StringPrintf(INDENT2 "displayId=%" PRId32 ", token->%s, focusedToken->%s\n",
4677 displayId, windowName.c_str(), focusedWindowName.c_str());
4678 }
4679 return dump;
4680}
4681
Prabir Pradhan99987712020-11-10 18:43:05 -08004682std::string InputDispatcher::dumpPointerCaptureStateLocked() {
4683 std::string dump;
4684
4685 dump += StringPrintf(INDENT "FocusedWindowRequestedPointerCapture: %s\n",
4686 toString(mFocusedWindowRequestedPointerCapture));
4687
4688 std::string windowName = "None";
4689 if (mWindowTokenWithPointerCapture) {
4690 const sp<InputWindowHandle> captureWindowHandle =
4691 getWindowHandleLocked(mWindowTokenWithPointerCapture);
4692 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
4693 : "token has capture without window";
4694 }
4695 dump += StringPrintf(INDENT "CurrentWindowWithPointerCapture: %s\n", windowName.c_str());
4696
4697 return dump;
4698}
4699
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004700void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07004701 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
4702 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
4703 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08004704 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004705
Tiger Huang721e26f2018-07-24 22:26:19 +08004706 if (!mFocusedApplicationHandlesByDisplay.empty()) {
4707 dump += StringPrintf(INDENT "FocusedApplications:\n");
4708 for (auto& it : mFocusedApplicationHandlesByDisplay) {
4709 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07004710 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05004711 const std::chrono::duration timeout =
4712 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004713 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004714 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05004715 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08004716 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004717 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08004718 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004719 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004720
Vishnu Nairad321cd2020-08-20 16:40:21 -07004721 dump += dumpFocusedWindowsLocked();
Siarhei Vishniakouad991402020-10-28 11:40:09 -05004722 dump += dumpPendingFocusRequestsLocked();
Prabir Pradhan99987712020-11-10 18:43:05 -08004723 dump += dumpPointerCaptureStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004724
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004725 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004726 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004727 for (const std::pair<int32_t, TouchState>& pair : mTouchStatesByDisplay) {
4728 const TouchState& state = pair.second;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004729 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004730 state.displayId, toString(state.down), toString(state.split),
4731 state.deviceId, state.source);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004732 if (!state.windows.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004733 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004734 for (size_t i = 0; i < state.windows.size(); i++) {
4735 const TouchedWindow& touchedWindow = state.windows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004736 dump += StringPrintf(INDENT4
4737 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
4738 i, touchedWindow.windowHandle->getName().c_str(),
4739 touchedWindow.pointerIds.value, touchedWindow.targetFlags);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004740 }
4741 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004742 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004743 }
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004744 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004745 dump += INDENT3 "Portal windows:\n";
4746 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004747 const sp<InputWindowHandle> portalWindowHandle = state.portalWindows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004748 dump += StringPrintf(INDENT4 "%zu: name='%s'\n", i,
4749 portalWindowHandle->getName().c_str());
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004750 }
4751 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004752 }
4753 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004754 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004755 }
4756
Arthur Hungb92218b2018-08-14 12:00:21 +08004757 if (!mWindowHandlesByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004758 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004759 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
Arthur Hung3b413f22018-10-26 18:05:34 +08004760 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", it.first);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004761 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004762 dump += INDENT2 "Windows:\n";
4763 for (size_t i = 0; i < windowHandles.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004764 const sp<InputWindowHandle>& windowHandle = windowHandles[i];
Arthur Hungb92218b2018-08-14 12:00:21 +08004765 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004766
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00004767 dump += StringPrintf(INDENT3 "%zu: name='%s', id=%" PRId32 ", displayId=%d, "
Vishnu Nair47074b82020-08-14 11:54:47 -07004768 "portalToDisplayId=%d, paused=%s, focusable=%s, "
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00004769 "hasWallpaper=%s, visible=%s, alpha=%.2f, "
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00004770 "flags=%s, type=%s, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004771 "frame=[%d,%d][%d,%d], globalScale=%f, "
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004772 "applicationInfo=%s, "
chaviw1ff3d1e2020-07-01 15:53:47 -07004773 "touchableRegion=",
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00004774 i, windowInfo->name.c_str(), windowInfo->id,
4775 windowInfo->displayId, windowInfo->portalToDisplayId,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004776 toString(windowInfo->paused),
Vishnu Nair47074b82020-08-14 11:54:47 -07004777 toString(windowInfo->focusable),
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004778 toString(windowInfo->hasWallpaper),
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00004779 toString(windowInfo->visible), windowInfo->alpha,
Michael Wright8759d672020-07-21 00:46:45 +01004780 windowInfo->flags.string().c_str(),
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00004781 NamedEnum::string(windowInfo->type).c_str(),
Michael Wright44753b12020-07-08 13:48:11 +01004782 windowInfo->frameLeft, windowInfo->frameTop,
4783 windowInfo->frameRight, windowInfo->frameBottom,
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004784 windowInfo->globalScaleFactor,
4785 windowInfo->applicationInfo.name.c_str());
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00004786 dump += dumpRegion(windowInfo->touchableRegion);
Michael Wright44753b12020-07-08 13:48:11 +01004787 dump += StringPrintf(", inputFeatures=%s",
4788 windowInfo->inputFeatures.string().c_str());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004789 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%" PRId64
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00004790 "ms, trustedOverlay=%s, hasToken=%s, "
4791 "touchOcclusionMode=%s\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004792 windowInfo->ownerPid, windowInfo->ownerUid,
Bernardo Rufinoc2f1fad2020-11-04 17:30:57 +00004793 millis(windowInfo->dispatchingTimeout),
4794 toString(windowInfo->trustedOverlay),
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00004795 toString(windowInfo->token != nullptr),
4796 toString(windowInfo->touchOcclusionMode).c_str());
chaviw85b44202020-07-24 11:46:21 -07004797 windowInfo->transform.dump(dump, "transform", INDENT4);
Arthur Hungb92218b2018-08-14 12:00:21 +08004798 }
4799 } else {
4800 dump += INDENT2 "Windows: <none>\n";
4801 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004802 }
4803 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08004804 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004805 }
4806
Michael Wright3dd60e22019-03-27 22:06:44 +00004807 if (!mGlobalMonitorsByDisplay.empty() || !mGestureMonitorsByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004808 for (auto& it : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004809 const std::vector<Monitor>& monitors = it.second;
4810 dump += StringPrintf(INDENT "Global monitors in display %" PRId32 ":\n", it.first);
4811 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004812 }
4813 for (auto& it : mGestureMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004814 const std::vector<Monitor>& monitors = it.second;
4815 dump += StringPrintf(INDENT "Gesture monitors in display %" PRId32 ":\n", it.first);
4816 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004817 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004818 } else {
Michael Wright3dd60e22019-03-27 22:06:44 +00004819 dump += INDENT "Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004820 }
4821
4822 nsecs_t currentTime = now();
4823
4824 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004825 if (!mRecentQueue.empty()) {
4826 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004827 for (std::shared_ptr<EventEntry>& entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004828 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05004829 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004830 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004831 }
4832 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004833 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004834 }
4835
4836 // Dump event currently being dispatched.
4837 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004838 dump += INDENT "PendingEvent:\n";
4839 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05004840 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004841 dump += StringPrintf(", age=%" PRId64 "ms\n",
4842 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004843 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004844 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004845 }
4846
4847 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004848 if (!mInboundQueue.empty()) {
4849 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004850 for (std::shared_ptr<EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004851 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05004852 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004853 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004854 }
4855 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004856 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004857 }
4858
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004859 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004860 dump += INDENT "ReplacedKeys:\n";
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004861 for (const std::pair<KeyReplacement, int32_t>& pair : mReplacedKeys) {
4862 const KeyReplacement& replacement = pair.first;
4863 int32_t newKeyCode = pair.second;
4864 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004865 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07004866 }
4867 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004868 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07004869 }
4870
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004871 if (!mConnectionsByFd.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004872 dump += INDENT "Connections:\n";
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004873 for (const auto& pair : mConnectionsByFd) {
4874 const sp<Connection>& connection = pair.second;
4875 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004876 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004877 pair.first, connection->getInputChannelName().c_str(),
4878 connection->getWindowName().c_str(), connection->getStatusLabel(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004879 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004880
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004881 if (!connection->outboundQueue.empty()) {
4882 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
4883 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05004884 dump += dumpQueue(connection->outboundQueue, currentTime);
4885
Michael Wrightd02c5b62014-02-10 15:10:22 -08004886 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004887 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004888 }
4889
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004890 if (!connection->waitQueue.empty()) {
4891 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
4892 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05004893 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004894 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004895 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004896 }
4897 }
4898 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004899 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004900 }
4901
4902 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004903 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
4904 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004905 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004906 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004907 }
4908
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004909 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004910 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
4911 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
4912 ns2ms(mConfig.keyRepeatTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004913}
4914
Michael Wright3dd60e22019-03-27 22:06:44 +00004915void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
4916 const size_t numMonitors = monitors.size();
4917 for (size_t i = 0; i < numMonitors; i++) {
4918 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004919 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00004920 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
4921 dump += "\n";
4922 }
4923}
4924
Garfield Tan15601662020-09-22 15:32:38 -07004925base::Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(
4926 const std::string& name) {
4927#if DEBUG_CHANNEL_CREATION
4928 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004929#endif
4930
Garfield Tan15601662020-09-22 15:32:38 -07004931 std::shared_ptr<InputChannel> serverChannel;
4932 std::unique_ptr<InputChannel> clientChannel;
4933 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
4934
4935 if (result) {
4936 return base::Error(result) << "Failed to open input channel pair with name " << name;
4937 }
4938
Michael Wrightd02c5b62014-02-10 15:10:22 -08004939 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004940 std::scoped_lock _l(mLock);
Garfield Tan15601662020-09-22 15:32:38 -07004941 sp<Connection> connection = new Connection(serverChannel, false /*monitor*/, mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004942
Garfield Tan15601662020-09-22 15:32:38 -07004943 int fd = serverChannel->getFd();
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004944 mConnectionsByFd[fd] = connection;
Garfield Tan15601662020-09-22 15:32:38 -07004945 mInputChannelsByToken[serverChannel->getConnectionToken()] = serverChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004946
Michael Wrightd02c5b62014-02-10 15:10:22 -08004947 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
4948 } // release lock
4949
4950 // Wake the looper because some connections have changed.
4951 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07004952 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004953}
4954
Garfield Tan15601662020-09-22 15:32:38 -07004955base::Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(
Siarhei Vishniakou58cfc602020-12-14 23:21:30 +00004956 int32_t displayId, bool isGestureMonitor, const std::string& name, int32_t pid) {
Garfield Tan15601662020-09-22 15:32:38 -07004957 std::shared_ptr<InputChannel> serverChannel;
4958 std::unique_ptr<InputChannel> clientChannel;
4959 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
4960 if (result) {
4961 return base::Error(result) << "Failed to open input channel pair with name " << name;
4962 }
4963
Michael Wright3dd60e22019-03-27 22:06:44 +00004964 { // acquire lock
4965 std::scoped_lock _l(mLock);
4966
4967 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07004968 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
4969 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00004970 }
4971
Garfield Tan15601662020-09-22 15:32:38 -07004972 sp<Connection> connection = new Connection(serverChannel, true /*monitor*/, mIdGenerator);
Michael Wright3dd60e22019-03-27 22:06:44 +00004973
Garfield Tan15601662020-09-22 15:32:38 -07004974 const int fd = serverChannel->getFd();
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004975 mConnectionsByFd[fd] = connection;
Garfield Tan15601662020-09-22 15:32:38 -07004976 mInputChannelsByToken[serverChannel->getConnectionToken()] = serverChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00004977
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004978 auto& monitorsByDisplay =
4979 isGestureMonitor ? mGestureMonitorsByDisplay : mGlobalMonitorsByDisplay;
Siarhei Vishniakou58cfc602020-12-14 23:21:30 +00004980 monitorsByDisplay[displayId].emplace_back(serverChannel, pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00004981
4982 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
Michael Wright3dd60e22019-03-27 22:06:44 +00004983 }
Garfield Tan15601662020-09-22 15:32:38 -07004984
Michael Wright3dd60e22019-03-27 22:06:44 +00004985 // Wake the looper because some connections have changed.
4986 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07004987 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00004988}
4989
Garfield Tan15601662020-09-22 15:32:38 -07004990status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004991 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004992 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004993
Garfield Tan15601662020-09-22 15:32:38 -07004994 status_t status = removeInputChannelLocked(connectionToken, false /*notify*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004995 if (status) {
4996 return status;
4997 }
4998 } // release lock
4999
5000 // Wake the poll loop because removing the connection may have changed the current
5001 // synchronization state.
5002 mLooper->wake();
5003 return OK;
5004}
5005
Garfield Tan15601662020-09-22 15:32:38 -07005006status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
5007 bool notify) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005008 sp<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005009 if (connection == nullptr) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005010 ALOGW("Attempted to unregister already unregistered input channel");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005011 return BAD_VALUE;
5012 }
5013
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005014 removeConnectionLocked(connection);
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005015 mInputChannelsByToken.erase(connectionToken);
Robert Carr5c8a0262018-10-03 16:30:44 -07005016
Michael Wrightd02c5b62014-02-10 15:10:22 -08005017 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005018 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005019 }
5020
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005021 mLooper->removeFd(connection->inputChannel->getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005022
5023 nsecs_t currentTime = now();
5024 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
5025
5026 connection->status = Connection::STATUS_ZOMBIE;
5027 return OK;
5028}
5029
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005030void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
5031 removeMonitorChannelLocked(connectionToken, mGlobalMonitorsByDisplay);
5032 removeMonitorChannelLocked(connectionToken, mGestureMonitorsByDisplay);
Michael Wright3dd60e22019-03-27 22:06:44 +00005033}
5034
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005035void InputDispatcher::removeMonitorChannelLocked(
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005036 const sp<IBinder>& connectionToken,
Michael Wright3dd60e22019-03-27 22:06:44 +00005037 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005038 for (auto it = monitorsByDisplay.begin(); it != monitorsByDisplay.end();) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005039 std::vector<Monitor>& monitors = it->second;
5040 const size_t numMonitors = monitors.size();
5041 for (size_t i = 0; i < numMonitors; i++) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005042 if (monitors[i].inputChannel->getConnectionToken() == connectionToken) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005043 monitors.erase(monitors.begin() + i);
5044 break;
5045 }
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005046 }
Michael Wright3dd60e22019-03-27 22:06:44 +00005047 if (monitors.empty()) {
5048 it = monitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005049 } else {
5050 ++it;
5051 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005052 }
5053}
5054
Michael Wright3dd60e22019-03-27 22:06:44 +00005055status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
5056 { // acquire lock
5057 std::scoped_lock _l(mLock);
5058 std::optional<int32_t> foundDisplayId = findGestureMonitorDisplayByTokenLocked(token);
5059
5060 if (!foundDisplayId) {
5061 ALOGW("Attempted to pilfer pointers from an un-registered monitor or invalid token");
5062 return BAD_VALUE;
5063 }
5064 int32_t displayId = foundDisplayId.value();
5065
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005066 std::unordered_map<int32_t, TouchState>::iterator stateIt =
5067 mTouchStatesByDisplay.find(displayId);
5068 if (stateIt == mTouchStatesByDisplay.end()) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005069 ALOGW("Failed to pilfer pointers: no pointers on display %" PRId32 ".", displayId);
5070 return BAD_VALUE;
5071 }
5072
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005073 TouchState& state = stateIt->second;
Michael Wright3dd60e22019-03-27 22:06:44 +00005074 std::optional<int32_t> foundDeviceId;
5075 for (const TouchedMonitor& touchedMonitor : state.gestureMonitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005076 if (touchedMonitor.monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005077 foundDeviceId = state.deviceId;
5078 }
5079 }
5080 if (!foundDeviceId || !state.down) {
5081 ALOGW("Attempted to pilfer points from a monitor without any on-going pointer streams."
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005082 " Ignoring.");
Michael Wright3dd60e22019-03-27 22:06:44 +00005083 return BAD_VALUE;
5084 }
5085 int32_t deviceId = foundDeviceId.value();
5086
5087 // Send cancel events to all the input channels we're stealing from.
5088 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005089 "gesture monitor stole pointer stream");
Michael Wright3dd60e22019-03-27 22:06:44 +00005090 options.deviceId = deviceId;
5091 options.displayId = displayId;
5092 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005093 std::shared_ptr<InputChannel> channel =
5094 getInputChannelLocked(window.windowHandle->getToken());
Michael Wright3a240c42019-12-10 20:53:41 +00005095 if (channel != nullptr) {
5096 synthesizeCancelationEventsForInputChannelLocked(channel, options);
5097 }
Michael Wright3dd60e22019-03-27 22:06:44 +00005098 }
5099 // Then clear the current touch state so we stop dispatching to them as well.
5100 state.filterNonMonitors();
5101 }
5102 return OK;
5103}
5104
Prabir Pradhan99987712020-11-10 18:43:05 -08005105void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
5106 { // acquire lock
5107 std::scoped_lock _l(mLock);
5108 if (DEBUG_FOCUS) {
5109 const sp<InputWindowHandle> windowHandle = getWindowHandleLocked(windowToken);
5110 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
5111 windowHandle != nullptr ? windowHandle->getName().c_str()
5112 : "token without window");
5113 }
5114
5115 const sp<IBinder> focusedToken =
5116 getValueByKey(mFocusedWindowTokenByDisplay, mFocusedDisplayId);
5117 if (focusedToken != windowToken) {
5118 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
5119 enabled ? "enable" : "disable");
5120 return;
5121 }
5122
5123 if (enabled == mFocusedWindowRequestedPointerCapture) {
5124 ALOGW("Ignoring request to %s Pointer Capture: "
5125 "window has %s requested pointer capture.",
5126 enabled ? "enable" : "disable", enabled ? "already" : "not");
5127 return;
5128 }
5129
5130 mFocusedWindowRequestedPointerCapture = enabled;
5131 setPointerCaptureLocked(enabled);
5132 } // release lock
5133
5134 // Wake the thread to process command entries.
5135 mLooper->wake();
5136}
5137
Michael Wright3dd60e22019-03-27 22:06:44 +00005138std::optional<int32_t> InputDispatcher::findGestureMonitorDisplayByTokenLocked(
5139 const sp<IBinder>& token) {
5140 for (const auto& it : mGestureMonitorsByDisplay) {
5141 const std::vector<Monitor>& monitors = it.second;
5142 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005143 if (monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005144 return it.first;
5145 }
5146 }
5147 }
5148 return std::nullopt;
5149}
5150
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005151sp<Connection> InputDispatcher::getConnectionLocked(const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005152 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005153 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08005154 }
5155
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005156 for (const auto& pair : mConnectionsByFd) {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005157 const sp<Connection>& connection = pair.second;
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005158 if (connection->inputChannel->getConnectionToken() == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005159 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005160 }
5161 }
Robert Carr4e670e52018-08-15 13:26:12 -07005162
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005163 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005164}
5165
Siarhei Vishniakouad991402020-10-28 11:40:09 -05005166std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
5167 sp<Connection> connection = getConnectionLocked(connectionToken);
5168 if (connection == nullptr) {
5169 return "<nullptr>";
5170 }
5171 return connection->getInputChannelName();
5172}
5173
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005174void InputDispatcher::removeConnectionLocked(const sp<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005175 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005176 removeByValue(mConnectionsByFd, connection);
5177}
5178
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005179void InputDispatcher::onDispatchCycleFinishedLocked(nsecs_t currentTime,
5180 const sp<Connection>& connection, uint32_t seq,
5181 bool handled) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005182 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5183 &InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005184 commandEntry->connection = connection;
5185 commandEntry->eventTime = currentTime;
5186 commandEntry->seq = seq;
5187 commandEntry->handled = handled;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005188 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005189}
5190
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005191void InputDispatcher::onDispatchCycleBrokenLocked(nsecs_t currentTime,
5192 const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005193 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005194 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005195
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005196 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5197 &InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005198 commandEntry->connection = connection;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005199 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005200}
5201
Vishnu Nairad321cd2020-08-20 16:40:21 -07005202void InputDispatcher::notifyFocusChangedLocked(const sp<IBinder>& oldToken,
5203 const sp<IBinder>& newToken) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005204 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5205 &InputDispatcher::doNotifyFocusChangedLockedInterruptible);
chaviw0c06c6e2019-01-09 13:27:07 -08005206 commandEntry->oldToken = oldToken;
5207 commandEntry->newToken = newToken;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005208 postCommandLocked(std::move(commandEntry));
Robert Carrf759f162018-11-13 12:57:11 -08005209}
5210
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -05005211void InputDispatcher::onAnrLocked(const Connection& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005212 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
5213 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -05005214 if (connection.waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005215 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -05005216 connection.inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005217 return;
5218 }
5219 /**
5220 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
5221 * may not be the one that caused the timeout to occur. One possibility is that window timeout
5222 * has changed. This could cause newer entries to time out before the already dispatched
5223 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
5224 * processes the events linearly. So providing information about the oldest entry seems to be
5225 * most useful.
5226 */
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -05005227 DispatchEntry* oldestEntry = *connection.waitQueue.begin();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005228 const nsecs_t currentWait = now() - oldestEntry->deliveryTime;
5229 std::string reason =
5230 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -05005231 connection.inputChannel->getName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005232 ns2ms(currentWait),
5233 oldestEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06005234 sp<IBinder> connectionToken = connection.inputChannel->getConnectionToken();
5235 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005236
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005237 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5238 &InputDispatcher::doNotifyConnectionUnresponsiveLockedInterruptible);
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06005239 commandEntry->connectionToken = connectionToken;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005240 commandEntry->reason = std::move(reason);
5241 postCommandLocked(std::move(commandEntry));
5242}
5243
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005244void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
5245 std::string reason =
5246 StringPrintf("%s does not have a focused window", application->getName().c_str());
5247 updateLastAnrStateLocked(*application, reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005248
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005249 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5250 &InputDispatcher::doNotifyNoFocusedWindowAnrLockedInterruptible);
5251 commandEntry->inputApplicationHandle = std::move(application);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005252 postCommandLocked(std::move(commandEntry));
5253}
5254
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00005255void InputDispatcher::onUntrustedTouchLocked(const std::string& obscuringPackage) {
5256 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5257 &InputDispatcher::doNotifyUntrustedTouchLockedInterruptible);
5258 commandEntry->obscuringPackage = obscuringPackage;
5259 postCommandLocked(std::move(commandEntry));
5260}
5261
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005262void InputDispatcher::updateLastAnrStateLocked(const sp<InputWindowHandle>& window,
5263 const std::string& reason) {
5264 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
5265 updateLastAnrStateLocked(windowLabel, reason);
5266}
5267
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005268void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
5269 const std::string& reason) {
5270 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005271 updateLastAnrStateLocked(windowLabel, reason);
5272}
5273
5274void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
5275 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005276 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07005277 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005278 struct tm tm;
5279 localtime_r(&t, &tm);
5280 char timestr[64];
5281 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005282 mLastAnrState.clear();
5283 mLastAnrState += INDENT "ANR:\n";
5284 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005285 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
5286 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005287 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005288}
5289
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005290void InputDispatcher::doNotifyConfigurationChangedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005291 mLock.unlock();
5292
5293 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
5294
5295 mLock.lock();
5296}
5297
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005298void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005299 sp<Connection> connection = commandEntry->connection;
5300
5301 if (connection->status != Connection::STATUS_ZOMBIE) {
5302 mLock.unlock();
5303
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005304 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005305
5306 mLock.lock();
5307 }
5308}
5309
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005310void InputDispatcher::doNotifyFocusChangedLockedInterruptible(CommandEntry* commandEntry) {
chaviw0c06c6e2019-01-09 13:27:07 -08005311 sp<IBinder> oldToken = commandEntry->oldToken;
5312 sp<IBinder> newToken = commandEntry->newToken;
Robert Carrf759f162018-11-13 12:57:11 -08005313 mLock.unlock();
chaviw0c06c6e2019-01-09 13:27:07 -08005314 mPolicy->notifyFocusChanged(oldToken, newToken);
Robert Carrf759f162018-11-13 12:57:11 -08005315 mLock.lock();
5316}
5317
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005318void InputDispatcher::doNotifyNoFocusedWindowAnrLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005319 mLock.unlock();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005320
5321 mPolicy->notifyNoFocusedWindowAnr(commandEntry->inputApplicationHandle);
5322
5323 mLock.lock();
5324}
5325
5326void InputDispatcher::doNotifyConnectionUnresponsiveLockedInterruptible(
5327 CommandEntry* commandEntry) {
5328 mLock.unlock();
5329
5330 mPolicy->notifyConnectionUnresponsive(commandEntry->connectionToken, commandEntry->reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005331
5332 mLock.lock();
5333
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005334 // stop waking up for events in this connection, it is already not responding
5335 sp<Connection> connection = getConnectionLocked(commandEntry->connectionToken);
5336 if (connection == nullptr) {
5337 return;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005338 }
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005339 cancelEventsForAnrLocked(connection);
5340}
5341
5342void InputDispatcher::doNotifyConnectionResponsiveLockedInterruptible(CommandEntry* commandEntry) {
5343 mLock.unlock();
5344
5345 mPolicy->notifyConnectionResponsive(commandEntry->connectionToken);
5346
5347 mLock.lock();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005348}
5349
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00005350void InputDispatcher::doNotifyUntrustedTouchLockedInterruptible(CommandEntry* commandEntry) {
5351 mLock.unlock();
5352
5353 mPolicy->notifyUntrustedTouch(commandEntry->obscuringPackage);
5354
5355 mLock.lock();
5356}
5357
Michael Wrightd02c5b62014-02-10 15:10:22 -08005358void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
5359 CommandEntry* commandEntry) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005360 KeyEntry& entry = *(commandEntry->keyEntry);
5361 KeyEvent event = createKeyEvent(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005362
5363 mLock.unlock();
5364
Michael Wright2b3c3302018-03-02 17:19:13 +00005365 android::base::Timer t;
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06005366 const sp<IBinder>& token = commandEntry->connectionToken;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005367 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(token, &event, entry.policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00005368 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
5369 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005370 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00005371 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005372
5373 mLock.lock();
5374
5375 if (delay < 0) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005376 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005377 } else if (!delay) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005378 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005379 } else {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005380 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
5381 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005382 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005383}
5384
chaviwfd6d3512019-03-25 13:23:49 -07005385void InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible(CommandEntry* commandEntry) {
5386 mLock.unlock();
5387 mPolicy->onPointerDownOutsideFocus(commandEntry->newToken);
5388 mLock.lock();
5389}
5390
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005391/**
5392 * Connection is responsive if it has no events in the waitQueue that are older than the
5393 * current time.
5394 */
5395static bool isConnectionResponsive(const Connection& connection) {
5396 const nsecs_t currentTime = now();
5397 for (const DispatchEntry* entry : connection.waitQueue) {
5398 if (entry->timeoutTime < currentTime) {
5399 return false;
5400 }
5401 }
5402 return true;
5403}
5404
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005405void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005406 sp<Connection> connection = commandEntry->connection;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005407 const nsecs_t finishTime = commandEntry->eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005408 uint32_t seq = commandEntry->seq;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005409 const bool handled = commandEntry->handled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005410
5411 // Handle post-event policy actions.
Garfield Tane84e6f92019-08-29 17:28:41 -07005412 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005413 if (dispatchEntryIt == connection->waitQueue.end()) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005414 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005415 }
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005416 DispatchEntry* dispatchEntry = *dispatchEntryIt;
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07005417 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005418 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005419 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
5420 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005421 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07005422 reportDispatchStatistics(std::chrono::nanoseconds(eventDuration), *connection, handled);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005423
5424 bool restartEvent;
Siarhei Vishniakou49483272019-10-22 13:13:47 -07005425 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005426 KeyEntry& keyEntry = static_cast<KeyEntry&>(*(dispatchEntry->eventEntry));
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005427 restartEvent =
5428 afterKeyEventLockedInterruptible(connection, dispatchEntry, keyEntry, handled);
Siarhei Vishniakou49483272019-10-22 13:13:47 -07005429 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005430 MotionEntry& motionEntry = static_cast<MotionEntry&>(*(dispatchEntry->eventEntry));
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005431 restartEvent = afterMotionEventLockedInterruptible(connection, dispatchEntry, motionEntry,
5432 handled);
5433 } else {
5434 restartEvent = false;
5435 }
5436
5437 // Dequeue the event and start the next cycle.
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07005438 // Because the lock might have been released, it is possible that the
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005439 // contents of the wait queue to have been drained, so we need to double-check
5440 // a few things.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005441 dispatchEntryIt = connection->findWaitQueueEntry(seq);
5442 if (dispatchEntryIt != connection->waitQueue.end()) {
5443 dispatchEntry = *dispatchEntryIt;
5444 connection->waitQueue.erase(dispatchEntryIt);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005445 const sp<IBinder>& connectionToken = connection->inputChannel->getConnectionToken();
5446 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005447 if (!connection->responsive) {
5448 connection->responsive = isConnectionResponsive(*connection);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005449 if (connection->responsive) {
5450 // The connection was unresponsive, and now it's responsive. Tell the policy
5451 // about it so that it can stop ANR.
5452 std::unique_ptr<CommandEntry> connectionResponsiveCommand =
5453 std::make_unique<CommandEntry>(
5454 &InputDispatcher::doNotifyConnectionResponsiveLockedInterruptible);
5455 connectionResponsiveCommand->connectionToken = connectionToken;
5456 postCommandLocked(std::move(connectionResponsiveCommand));
5457 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005458 }
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005459 traceWaitQueueLength(connection);
5460 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005461 connection->outboundQueue.push_front(dispatchEntry);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005462 traceOutboundQueueLength(connection);
5463 } else {
5464 releaseDispatchEntry(dispatchEntry);
5465 }
5466 }
5467
5468 // Start the next dispatch cycle for this connection.
5469 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005470}
5471
5472bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005473 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005474 KeyEntry& keyEntry, bool handled) {
5475 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005476 if (!handled) {
5477 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005478 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005479 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005480 return false;
5481 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005482
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005483 // Get the fallback key state.
5484 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005485 int32_t originalKeyCode = keyEntry.keyCode;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005486 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005487 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005488 connection->inputState.removeFallbackKey(originalKeyCode);
5489 }
5490
5491 if (handled || !dispatchEntry->hasForegroundTarget()) {
5492 // If the application handles the original key for which we previously
5493 // generated a fallback or if the window is not a foreground window,
5494 // then cancel the associated fallback key, if any.
5495 if (fallbackKeyCode != -1) {
5496 // Dispatch the unhandled key to the policy with the cancel flag.
Michael Wrightd02c5b62014-02-10 15:10:22 -08005497#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005498 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005499 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005500 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005501#endif
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005502 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005503 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005504
5505 mLock.unlock();
5506
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005507 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005508 keyEntry.policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005509
5510 mLock.lock();
5511
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005512 // Cancel the fallback key.
5513 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005514 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005515 "application handled the original non-fallback key "
5516 "or is no longer a foreground target, "
5517 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005518 options.keyCode = fallbackKeyCode;
5519 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005520 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005521 connection->inputState.removeFallbackKey(originalKeyCode);
5522 }
5523 } else {
5524 // If the application did not handle a non-fallback key, first check
5525 // that we are in a good state to perform unhandled key event processing
5526 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005527 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005528 if (fallbackKeyCode == -1 && !initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005529#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005530 ALOGD("Unhandled key event: Skipping unhandled key event processing "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005531 "since this is not an initial down. "
5532 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005533 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005534#endif
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005535 return false;
5536 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005537
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005538 // Dispatch the unhandled key to the policy.
5539#if DEBUG_OUTBOUND_EVENT_DETAILS
5540 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005541 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005542 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005543#endif
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005544 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005545
5546 mLock.unlock();
5547
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005548 bool fallback =
5549 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005550 &event, keyEntry.policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005551
5552 mLock.lock();
5553
5554 if (connection->status != Connection::STATUS_NORMAL) {
5555 connection->inputState.removeFallbackKey(originalKeyCode);
5556 return false;
5557 }
5558
5559 // Latch the fallback keycode for this key on an initial down.
5560 // The fallback keycode cannot change at any other point in the lifecycle.
5561 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005562 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005563 fallbackKeyCode = event.getKeyCode();
5564 } else {
5565 fallbackKeyCode = AKEYCODE_UNKNOWN;
5566 }
5567 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
5568 }
5569
5570 ALOG_ASSERT(fallbackKeyCode != -1);
5571
5572 // Cancel the fallback key if the policy decides not to send it anymore.
5573 // We will continue to dispatch the key to the policy but we will no
5574 // longer dispatch a fallback key to the application.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005575 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
5576 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005577#if DEBUG_OUTBOUND_EVENT_DETAILS
5578 if (fallback) {
5579 ALOGD("Unhandled key event: Policy requested to send key %d"
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005580 "as a fallback for %d, but on the DOWN it had requested "
5581 "to send %d instead. Fallback canceled.",
5582 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005583 } else {
5584 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005585 "but on the DOWN it had requested to send %d. "
5586 "Fallback canceled.",
5587 originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005588 }
5589#endif
5590
5591 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
5592 "canceling fallback, policy no longer desires it");
5593 options.keyCode = fallbackKeyCode;
5594 synthesizeCancelationEventsForConnectionLocked(connection, options);
5595
5596 fallback = false;
5597 fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005598 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005599 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005600 }
5601 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005602
5603#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005604 {
5605 std::string msg;
5606 const KeyedVector<int32_t, int32_t>& fallbackKeys =
5607 connection->inputState.getFallbackKeys();
5608 for (size_t i = 0; i < fallbackKeys.size(); i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005609 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005610 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005611 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005612 fallbackKeys.size(), msg.c_str());
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005613 }
5614#endif
5615
5616 if (fallback) {
5617 // Restart the dispatch cycle using the fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005618 keyEntry.eventTime = event.getEventTime();
5619 keyEntry.deviceId = event.getDeviceId();
5620 keyEntry.source = event.getSource();
5621 keyEntry.displayId = event.getDisplayId();
5622 keyEntry.flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
5623 keyEntry.keyCode = fallbackKeyCode;
5624 keyEntry.scanCode = event.getScanCode();
5625 keyEntry.metaState = event.getMetaState();
5626 keyEntry.repeatCount = event.getRepeatCount();
5627 keyEntry.downTime = event.getDownTime();
5628 keyEntry.syntheticRepeat = false;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005629
5630#if DEBUG_OUTBOUND_EVENT_DETAILS
5631 ALOGD("Unhandled key event: Dispatching fallback key. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005632 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005633 originalKeyCode, fallbackKeyCode, keyEntry.metaState);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005634#endif
5635 return true; // restart the event
5636 } else {
5637#if DEBUG_OUTBOUND_EVENT_DETAILS
5638 ALOGD("Unhandled key event: No fallback key.");
5639#endif
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005640
5641 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005642 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005643 }
5644 }
5645 return false;
5646}
5647
5648bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005649 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005650 MotionEntry& motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005651 return false;
5652}
5653
5654void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
5655 mLock.unlock();
5656
5657 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType);
5658
5659 mLock.lock();
5660}
5661
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07005662void InputDispatcher::reportDispatchStatistics(std::chrono::nanoseconds eventDuration,
5663 const Connection& connection, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005664 // TODO Write some statistics about how long we spend waiting.
5665}
5666
Siarhei Vishniakoude4bf152019-08-16 11:12:52 -05005667/**
5668 * Report the touch event latency to the statsd server.
5669 * Input events are reported for statistics if:
5670 * - This is a touchscreen event
5671 * - InputFilter is not enabled
5672 * - Event is not injected or synthesized
5673 *
5674 * Statistics should be reported before calling addValue, to prevent a fresh new sample
5675 * from getting aggregated with the "old" data.
5676 */
5677void InputDispatcher::reportTouchEventForStatistics(const MotionEntry& motionEntry)
5678 REQUIRES(mLock) {
5679 const bool reportForStatistics = (motionEntry.source == AINPUT_SOURCE_TOUCHSCREEN) &&
5680 !(motionEntry.isSynthesized()) && !mInputFilterEnabled;
5681 if (!reportForStatistics) {
5682 return;
5683 }
5684
5685 if (mTouchStatistics.shouldReport()) {
5686 android::util::stats_write(android::util::TOUCH_EVENT_REPORTED, mTouchStatistics.getMin(),
5687 mTouchStatistics.getMax(), mTouchStatistics.getMean(),
5688 mTouchStatistics.getStDev(), mTouchStatistics.getCount());
5689 mTouchStatistics.reset();
5690 }
5691 const float latencyMicros = nanoseconds_to_microseconds(now() - motionEntry.eventTime);
5692 mTouchStatistics.addValue(latencyMicros);
5693}
5694
Michael Wrightd02c5b62014-02-10 15:10:22 -08005695void InputDispatcher::traceInboundQueueLengthLocked() {
5696 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005697 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005698 }
5699}
5700
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08005701void InputDispatcher::traceOutboundQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005702 if (ATRACE_ENABLED()) {
5703 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08005704 snprintf(counterName, sizeof(counterName), "oq:%s", connection->getWindowName().c_str());
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005705 ATRACE_INT(counterName, connection->outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005706 }
5707}
5708
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08005709void InputDispatcher::traceWaitQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005710 if (ATRACE_ENABLED()) {
5711 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08005712 snprintf(counterName, sizeof(counterName), "wq:%s", connection->getWindowName().c_str());
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005713 ATRACE_INT(counterName, connection->waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005714 }
5715}
5716
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005717void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005718 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005719
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005720 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005721 dumpDispatchStateLocked(dump);
5722
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005723 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005724 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005725 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005726 }
5727}
5728
5729void InputDispatcher::monitor() {
5730 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005731 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005732 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005733 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005734}
5735
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08005736/**
5737 * Wake up the dispatcher and wait until it processes all events and commands.
5738 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
5739 * this method can be safely called from any thread, as long as you've ensured that
5740 * the work you are interested in completing has already been queued.
5741 */
5742bool InputDispatcher::waitForIdle() {
5743 /**
5744 * Timeout should represent the longest possible time that a device might spend processing
5745 * events and commands.
5746 */
5747 constexpr std::chrono::duration TIMEOUT = 100ms;
5748 std::unique_lock lock(mLock);
5749 mLooper->wake();
5750 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
5751 return result == std::cv_status::no_timeout;
5752}
5753
Vishnu Naire798b472020-07-23 13:52:21 -07005754/**
5755 * Sets focus to the window identified by the token. This must be called
5756 * after updating any input window handles.
5757 *
5758 * Params:
5759 * request.token - input channel token used to identify the window that should gain focus.
5760 * request.focusedToken - the token that the caller expects currently to be focused. If the
5761 * specified token does not match the currently focused window, this request will be dropped.
5762 * If the specified focused token matches the currently focused window, the call will succeed.
5763 * Set this to "null" if this call should succeed no matter what the currently focused token is.
5764 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
5765 * when requesting the focus change. This determines which request gets
5766 * precedence if there is a focus change request from another source such as pointer down.
5767 */
Vishnu Nair958da932020-08-21 17:12:37 -07005768void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
5769 { // acquire lock
5770 std::scoped_lock _l(mLock);
5771
5772 const int32_t displayId = request.displayId;
5773 const sp<IBinder> oldFocusedToken = getValueByKey(mFocusedWindowTokenByDisplay, displayId);
5774 if (request.focusedToken && oldFocusedToken != request.focusedToken) {
5775 ALOGD_IF(DEBUG_FOCUS,
5776 "setFocusedWindow on display %" PRId32
5777 " ignored, reason: focusedToken is not focused",
5778 displayId);
5779 return;
5780 }
5781
5782 mPendingFocusRequests.erase(displayId);
5783 FocusResult result = handleFocusRequestLocked(request);
5784 if (result == FocusResult::NOT_VISIBLE) {
5785 // The requested window is not currently visible. Wait for the window to become visible
5786 // and then provide it focus. This is to handle situations where a user action triggers
5787 // a new window to appear. We want to be able to queue any key events after the user
5788 // action and deliver it to the newly focused window. In order for this to happen, we
5789 // take focus from the currently focused window so key events can be queued.
5790 ALOGD_IF(DEBUG_FOCUS,
5791 "setFocusedWindow on display %" PRId32
5792 " pending, reason: window is not visible",
5793 displayId);
5794 mPendingFocusRequests[displayId] = request;
5795 onFocusChangedLocked(oldFocusedToken, nullptr, displayId,
5796 "setFocusedWindow_AwaitingWindowVisibility");
5797 } else if (result != FocusResult::OK) {
5798 ALOGW("setFocusedWindow on display %" PRId32 " ignored, reason:%s", displayId,
5799 typeToString(result));
5800 }
5801 } // release lock
5802 // Wake up poll loop since it may need to make new input dispatching choices.
5803 mLooper->wake();
5804}
5805
5806InputDispatcher::FocusResult InputDispatcher::handleFocusRequestLocked(
5807 const FocusRequest& request) {
5808 const int32_t displayId = request.displayId;
5809 const sp<IBinder> newFocusedToken = request.token;
5810 const sp<IBinder> oldFocusedToken = getValueByKey(mFocusedWindowTokenByDisplay, displayId);
5811
5812 if (oldFocusedToken == request.token) {
5813 ALOGD_IF(DEBUG_FOCUS,
5814 "setFocusedWindow on display %" PRId32 " ignored, reason: already focused",
5815 displayId);
5816 return FocusResult::OK;
5817 }
5818
5819 FocusResult result = checkTokenFocusableLocked(newFocusedToken, displayId);
5820 if (result != FocusResult::OK) {
5821 return result;
5822 }
5823
5824 std::string_view reason =
5825 (request.focusedToken) ? "setFocusedWindow_FocusCheck" : "setFocusedWindow";
5826 onFocusChangedLocked(oldFocusedToken, newFocusedToken, displayId, reason);
5827 return FocusResult::OK;
5828}
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005829
Vishnu Nairad321cd2020-08-20 16:40:21 -07005830void InputDispatcher::onFocusChangedLocked(const sp<IBinder>& oldFocusedToken,
5831 const sp<IBinder>& newFocusedToken, int32_t displayId,
5832 std::string_view reason) {
5833 if (oldFocusedToken) {
5834 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(oldFocusedToken);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005835 if (focusedInputChannel) {
5836 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
5837 "focus left window");
5838 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Vishnu Nairad321cd2020-08-20 16:40:21 -07005839 enqueueFocusEventLocked(oldFocusedToken, false /*hasFocus*/, reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005840 }
Vishnu Nairad321cd2020-08-20 16:40:21 -07005841 mFocusedWindowTokenByDisplay.erase(displayId);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005842 }
Vishnu Nairad321cd2020-08-20 16:40:21 -07005843 if (newFocusedToken) {
5844 mFocusedWindowTokenByDisplay[displayId] = newFocusedToken;
5845 enqueueFocusEventLocked(newFocusedToken, true /*hasFocus*/, reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005846 }
5847
Prabir Pradhan99987712020-11-10 18:43:05 -08005848 // If a window has pointer capture, then it must have focus. We need to ensure that this
5849 // contract is upheld when pointer capture is being disabled due to a loss of window focus.
5850 // If the window loses focus before it loses pointer capture, then the window can be in a state
5851 // where it has pointer capture but not focus, violating the contract. Therefore we must
5852 // dispatch the pointer capture event before the focus event. Since focus events are added to
5853 // the front of the queue (above), we add the pointer capture event to the front of the queue
5854 // after the focus events are added. This ensures the pointer capture event ends up at the
5855 // front.
5856 disablePointerCaptureForcedLocked();
5857
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005858 if (mFocusedDisplayId == displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005859 notifyFocusChangedLocked(oldFocusedToken, newFocusedToken);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005860 }
5861}
Vishnu Nair958da932020-08-21 17:12:37 -07005862
Prabir Pradhan99987712020-11-10 18:43:05 -08005863void InputDispatcher::disablePointerCaptureForcedLocked() {
5864 if (!mFocusedWindowRequestedPointerCapture && !mWindowTokenWithPointerCapture) {
5865 return;
5866 }
5867
5868 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
5869
5870 if (mFocusedWindowRequestedPointerCapture) {
5871 mFocusedWindowRequestedPointerCapture = false;
5872 setPointerCaptureLocked(false);
5873 }
5874
5875 if (!mWindowTokenWithPointerCapture) {
5876 // No need to send capture changes because no window has capture.
5877 return;
5878 }
5879
5880 if (mPendingEvent != nullptr) {
5881 // Move the pending event to the front of the queue. This will give the chance
5882 // for the pending event to be dropped if it is a captured event.
5883 mInboundQueue.push_front(mPendingEvent);
5884 mPendingEvent = nullptr;
5885 }
5886
5887 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
5888 false /* hasCapture */);
5889 mInboundQueue.push_front(std::move(entry));
5890}
5891
Vishnu Nair958da932020-08-21 17:12:37 -07005892/**
5893 * Checks if the window token can be focused on a display. The token can be focused if there is
5894 * at least one window handle that is visible with the same token and all window handles with the
5895 * same token are focusable.
5896 *
5897 * In the case of mirroring, two windows may share the same window token and their visibility
5898 * might be different. Example, the mirrored window can cover the window its mirroring. However,
5899 * we expect the focusability of the windows to match since its hard to reason why one window can
5900 * receive focus events and the other cannot when both are backed by the same input channel.
5901 */
5902InputDispatcher::FocusResult InputDispatcher::checkTokenFocusableLocked(const sp<IBinder>& token,
5903 int32_t displayId) const {
5904 bool allWindowsAreFocusable = true;
5905 bool visibleWindowFound = false;
5906 bool windowFound = false;
5907 for (const sp<InputWindowHandle>& window : getWindowHandlesLocked(displayId)) {
5908 if (window->getToken() != token) {
5909 continue;
5910 }
5911 windowFound = true;
5912 if (window->getInfo()->visible) {
5913 // Check if at least a single window is visible.
5914 visibleWindowFound = true;
5915 }
5916 if (!window->getInfo()->focusable) {
5917 // Check if all windows with the window token are focusable.
5918 allWindowsAreFocusable = false;
5919 break;
5920 }
5921 }
5922
5923 if (!windowFound) {
5924 return FocusResult::NO_WINDOW;
5925 }
5926 if (!allWindowsAreFocusable) {
5927 return FocusResult::NOT_FOCUSABLE;
5928 }
5929 if (!visibleWindowFound) {
5930 return FocusResult::NOT_VISIBLE;
5931 }
5932
5933 return FocusResult::OK;
5934}
Prabir Pradhan99987712020-11-10 18:43:05 -08005935
5936void InputDispatcher::setPointerCaptureLocked(bool enabled) {
5937 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5938 &InputDispatcher::doSetPointerCaptureLockedInterruptible);
5939 commandEntry->enabled = enabled;
5940 postCommandLocked(std::move(commandEntry));
5941}
5942
5943void InputDispatcher::doSetPointerCaptureLockedInterruptible(
5944 android::inputdispatcher::CommandEntry* commandEntry) {
5945 mLock.unlock();
5946
5947 mPolicy->setPointerCapture(commandEntry->enabled);
5948
5949 mLock.lock();
5950}
5951
Garfield Tane84e6f92019-08-29 17:28:41 -07005952} // namespace android::inputdispatcher