blob: 0c286ce9bbdce4bf360ae72c3613cfbf2f5de657 [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;
Prabir Pradhan7d030382020-12-21 07:58:35 -08001269 if (mFocusedWindowRequestedPointerCapture) {
1270 mFocusedWindowRequestedPointerCapture = false;
1271 setPointerCaptureLocked(false);
1272 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001273 }
1274
1275 auto channel = getInputChannelLocked(token);
1276 if (channel == nullptr) {
1277 // Window has gone away, clean up Pointer Capture state.
1278 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan7d030382020-12-21 07:58:35 -08001279 if (mFocusedWindowRequestedPointerCapture) {
1280 mFocusedWindowRequestedPointerCapture = false;
1281 setPointerCaptureLocked(false);
1282 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001283 return;
1284 }
1285 InputTarget target;
1286 target.inputChannel = channel;
1287 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1288 entry->dispatchInProgress = true;
1289 dispatchEventLocked(currentTime, entry, {target});
1290
1291 dropReason = DropReason::NOT_DROPPED;
1292}
1293
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001294bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, std::shared_ptr<KeyEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001295 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001296 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001297 if (!entry->dispatchInProgress) {
1298 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1299 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1300 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1301 if (mKeyRepeatState.lastKeyEntry &&
Chris Ye2ad95392020-09-01 13:44:44 -07001302 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode &&
Michael Wrightd02c5b62014-02-10 15:10:22 -08001303 // We have seen two identical key downs in a row which indicates that the device
1304 // driver is automatically generating key repeats itself. We take note of the
1305 // repeat here, but we disable our own next key repeat timer since it is clear that
1306 // we will not need to synthesize key repeats ourselves.
Chris Ye2ad95392020-09-01 13:44:44 -07001307 mKeyRepeatState.lastKeyEntry->deviceId == entry->deviceId) {
1308 // Make sure we don't get key down from a different device. If a different
1309 // device Id has same key pressed down, the new device Id will replace the
1310 // current one to hold the key repeat with repeat count reset.
1311 // In the future when got a KEY_UP on the device id, drop it and do not
1312 // stop the key repeat on current device.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001313 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1314 resetKeyRepeatLocked();
1315 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
1316 } else {
1317 // Not a repeat. Save key down state in case we do see a repeat later.
1318 resetKeyRepeatLocked();
1319 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1320 }
1321 mKeyRepeatState.lastKeyEntry = entry;
Chris Ye2ad95392020-09-01 13:44:44 -07001322 } else if (entry->action == AKEY_EVENT_ACTION_UP && mKeyRepeatState.lastKeyEntry &&
1323 mKeyRepeatState.lastKeyEntry->deviceId != entry->deviceId) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001324 // The key on device 'deviceId' is still down, do not stop key repeat
Chris Ye2ad95392020-09-01 13:44:44 -07001325#if DEBUG_INBOUND_EVENT_DETAILS
1326 ALOGD("deviceId=%d got KEY_UP as stale", entry->deviceId);
1327#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001328 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001329 resetKeyRepeatLocked();
1330 }
1331
1332 if (entry->repeatCount == 1) {
1333 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1334 } else {
1335 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1336 }
1337
1338 entry->dispatchInProgress = true;
1339
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001340 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001341 }
1342
1343 // Handle case where the policy asked us to try again later last time.
1344 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
1345 if (currentTime < entry->interceptKeyWakeupTime) {
1346 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1347 *nextWakeupTime = entry->interceptKeyWakeupTime;
1348 }
1349 return false; // wait until next wakeup
1350 }
1351 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
1352 entry->interceptKeyWakeupTime = 0;
1353 }
1354
1355 // Give the policy a chance to intercept the key.
1356 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
1357 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001358 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
Siarhei Vishniakou49a350a2019-07-26 18:44:23 -07001359 &InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible);
Vishnu Nairad321cd2020-08-20 16:40:21 -07001360 sp<IBinder> focusedWindowToken =
1361 getValueByKey(mFocusedWindowTokenByDisplay, getTargetDisplayId(*entry));
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06001362 commandEntry->connectionToken = focusedWindowToken;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001363 commandEntry->keyEntry = entry;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001364 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001365 return false; // wait for the command to run
1366 } else {
1367 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
1368 }
1369 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001370 if (*dropReason == DropReason::NOT_DROPPED) {
1371 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001372 }
1373 }
1374
1375 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001376 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001377 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001378 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1379 : InputEventInjectionResult::FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001380 mReporter->reportDroppedKey(entry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001381 return true;
1382 }
1383
1384 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001385 std::vector<InputTarget> inputTargets;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001386 InputEventInjectionResult injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001387 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001388 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001389 return false;
1390 }
1391
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001392 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001393 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001394 return true;
1395 }
1396
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001397 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001398 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001399
1400 // Dispatch the key.
1401 dispatchEventLocked(currentTime, entry, inputTargets);
1402 return true;
1403}
1404
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001405void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001406#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01001407 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001408 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1409 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001410 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1411 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
1412 entry.repeatCount, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001413#endif
1414}
1415
Chris Yef59a2f42020-10-16 12:55:26 -07001416void InputDispatcher::doNotifySensorLockedInterruptible(CommandEntry* commandEntry) {
1417 mLock.unlock();
1418
1419 const std::shared_ptr<SensorEntry>& entry = commandEntry->sensorEntry;
1420 if (entry->accuracyChanged) {
1421 mPolicy->notifySensorAccuracy(entry->deviceId, entry->sensorType, entry->accuracy);
1422 }
1423 mPolicy->notifySensorEvent(entry->deviceId, entry->sensorType, entry->accuracy,
1424 entry->hwTimestamp, entry->values);
1425 mLock.lock();
1426}
1427
1428void InputDispatcher::dispatchSensorLocked(nsecs_t currentTime, std::shared_ptr<SensorEntry> entry,
1429 DropReason* dropReason, nsecs_t* nextWakeupTime) {
1430#if DEBUG_OUTBOUND_EVENT_DETAILS
1431 ALOGD("notifySensorEvent eventTime=%" PRId64 ", hwTimestamp=%" PRId64 ", deviceId=%d, "
1432 "source=0x%x, sensorType=%s",
1433 entry->eventTime, entry->hwTimestamp, entry->deviceId, entry->source,
1434 NamedEnum::string(sensorType).c_str());
1435#endif
1436 std::unique_ptr<CommandEntry> commandEntry =
1437 std::make_unique<CommandEntry>(&InputDispatcher::doNotifySensorLockedInterruptible);
1438 commandEntry->sensorEntry = entry;
1439 postCommandLocked(std::move(commandEntry));
1440}
1441
1442bool InputDispatcher::flushSensor(int deviceId, InputDeviceSensorType sensorType) {
1443#if DEBUG_OUTBOUND_EVENT_DETAILS
1444 ALOGD("flushSensor deviceId=%d, sensorType=%s", deviceId,
1445 NamedEnum::string(sensorType).c_str());
1446#endif
1447 { // acquire lock
1448 std::scoped_lock _l(mLock);
1449
1450 for (auto it = mInboundQueue.begin(); it != mInboundQueue.end(); it++) {
1451 std::shared_ptr<EventEntry> entry = *it;
1452 if (entry->type == EventEntry::Type::SENSOR) {
1453 it = mInboundQueue.erase(it);
1454 releaseInboundEventLocked(entry);
1455 }
1456 }
1457 }
1458 return true;
1459}
1460
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001461bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, std::shared_ptr<MotionEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001462 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001463 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001464 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001465 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001466 entry->dispatchInProgress = true;
1467
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001468 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001469 }
1470
1471 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001472 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001473 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001474 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1475 : InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001476 return true;
1477 }
1478
1479 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
1480
1481 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001482 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001483
1484 bool conflictingPointerActions = false;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001485 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001486 if (isPointerEvent) {
1487 // Pointer event. (eg. touchscreen)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001488 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001489 findTouchedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001490 &conflictingPointerActions);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001491 } else {
1492 // Non touch event. (eg. trackball)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001493 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001494 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001495 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001496 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001497 return false;
1498 }
1499
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001500 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001501 if (injectionResult == InputEventInjectionResult::PERMISSION_DENIED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001502 ALOGW("Permission denied, dropping the motion (isPointer=%s)", toString(isPointerEvent));
1503 return true;
1504 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001505 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001506 CancelationOptions::Mode mode(isPointerEvent
1507 ? CancelationOptions::CANCEL_POINTER_EVENTS
1508 : CancelationOptions::CANCEL_NON_POINTER_EVENTS);
1509 CancelationOptions options(mode, "input event injection failed");
1510 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001511 return true;
1512 }
1513
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001514 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001515 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001516
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001517 if (isPointerEvent) {
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07001518 std::unordered_map<int32_t, TouchState>::iterator it =
1519 mTouchStatesByDisplay.find(entry->displayId);
1520 if (it != mTouchStatesByDisplay.end()) {
1521 const TouchState& state = it->second;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001522 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001523 // The event has gone through these portal windows, so we add monitoring targets of
1524 // the corresponding displays as well.
1525 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001526 const InputWindowInfo* windowInfo = state.portalWindows[i]->getInfo();
Michael Wright3dd60e22019-03-27 22:06:44 +00001527 addGlobalMonitoringTargetsLocked(inputTargets, windowInfo->portalToDisplayId,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001528 -windowInfo->frameLeft, -windowInfo->frameTop);
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001529 }
1530 }
1531 }
1532 }
1533
Michael Wrightd02c5b62014-02-10 15:10:22 -08001534 // Dispatch the motion.
1535 if (conflictingPointerActions) {
1536 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001537 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001538 synthesizeCancelationEventsForAllConnectionsLocked(options);
1539 }
1540 dispatchEventLocked(currentTime, entry, inputTargets);
1541 return true;
1542}
1543
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001544void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001545#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08001546 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001547 ", policyFlags=0x%x, "
1548 "action=0x%x, actionButton=0x%x, flags=0x%x, "
1549 "metaState=0x%x, buttonState=0x%x,"
1550 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001551 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1552 entry.action, entry.actionButton, entry.flags, entry.metaState, entry.buttonState,
1553 entry.edgeFlags, entry.xPrecision, entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001554
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001555 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001556 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001557 "x=%f, y=%f, pressure=%f, size=%f, "
1558 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1559 "orientation=%f",
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001560 i, entry.pointerProperties[i].id, entry.pointerProperties[i].toolType,
1561 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1562 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1563 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1564 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1565 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1566 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1567 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1568 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1569 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001570 }
1571#endif
1572}
1573
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001574void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
1575 std::shared_ptr<EventEntry> eventEntry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001576 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001577 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001578#if DEBUG_DISPATCH_CYCLE
1579 ALOGD("dispatchEventToCurrentInputTargets");
1580#endif
1581
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001582 updateInteractionTokensLocked(*eventEntry, inputTargets);
1583
Michael Wrightd02c5b62014-02-10 15:10:22 -08001584 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1585
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001586 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001587
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001588 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001589 sp<Connection> connection =
1590 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001591 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08001592 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001593 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001594 if (DEBUG_FOCUS) {
1595 ALOGD("Dropping event delivery to target with channel '%s' because it "
1596 "is no longer registered with the input dispatcher.",
1597 inputTarget.inputChannel->getName().c_str());
1598 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001599 }
1600 }
1601}
1602
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001603void InputDispatcher::cancelEventsForAnrLocked(const sp<Connection>& connection) {
1604 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
1605 // If the policy decides to close the app, we will get a channel removal event via
1606 // unregisterInputChannel, and will clean up the connection that way. We are already not
1607 // sending new pointers to the connection when it blocked, but focused events will continue to
1608 // pile up.
1609 ALOGW("Canceling events for %s because it is unresponsive",
1610 connection->inputChannel->getName().c_str());
1611 if (connection->status == Connection::STATUS_NORMAL) {
1612 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1613 "application not responding");
1614 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001615 }
1616}
1617
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001618void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001619 if (DEBUG_FOCUS) {
1620 ALOGD("Resetting ANR timeouts.");
1621 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001622
1623 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001624 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07001625 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001626}
1627
Tiger Huang721e26f2018-07-24 22:26:19 +08001628/**
1629 * Get the display id that the given event should go to. If this event specifies a valid display id,
1630 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1631 * Focused display is the display that the user most recently interacted with.
1632 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001633int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001634 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001635 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001636 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001637 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1638 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001639 break;
1640 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001641 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001642 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1643 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001644 break;
1645 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001646 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001647 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001648 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07001649 case EventEntry::Type::DEVICE_RESET:
1650 case EventEntry::Type::SENSOR: {
1651 ALOGE("%s events do not have a target display", NamedEnum::string(entry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001652 return ADISPLAY_ID_NONE;
1653 }
Tiger Huang721e26f2018-07-24 22:26:19 +08001654 }
1655 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1656}
1657
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001658bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
1659 const char* focusedWindowName) {
1660 if (mAnrTracker.empty()) {
1661 // already processed all events that we waited for
1662 mKeyIsWaitingForEventsTimeout = std::nullopt;
1663 return false;
1664 }
1665
1666 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
1667 // Start the timer
1668 ALOGD("Waiting to send key to %s because there are unprocessed events that may cause "
1669 "focus to change",
1670 focusedWindowName);
Siarhei Vishniakou70622952020-07-30 11:17:23 -05001671 mKeyIsWaitingForEventsTimeout = currentTime +
1672 std::chrono::duration_cast<std::chrono::nanoseconds>(KEY_WAITING_FOR_EVENTS_TIMEOUT)
1673 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001674 return true;
1675 }
1676
1677 // We still have pending events, and already started the timer
1678 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
1679 return true; // Still waiting
1680 }
1681
1682 // Waited too long, and some connection still hasn't processed all motions
1683 // Just send the key to the focused window
1684 ALOGW("Dispatching key to %s even though there are other unprocessed events",
1685 focusedWindowName);
1686 mKeyIsWaitingForEventsTimeout = std::nullopt;
1687 return false;
1688}
1689
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001690InputEventInjectionResult InputDispatcher::findFocusedWindowTargetsLocked(
1691 nsecs_t currentTime, const EventEntry& entry, std::vector<InputTarget>& inputTargets,
1692 nsecs_t* nextWakeupTime) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001693 std::string reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001694
Tiger Huang721e26f2018-07-24 22:26:19 +08001695 int32_t displayId = getTargetDisplayId(entry);
Vishnu Nairad321cd2020-08-20 16:40:21 -07001696 sp<InputWindowHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07001697 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08001698 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1699
Michael Wrightd02c5b62014-02-10 15:10:22 -08001700 // If there is no currently focused window and no focused application
1701 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001702 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
1703 ALOGI("Dropping %s event because there is no focused window or focused application in "
1704 "display %" PRId32 ".",
Chris Yef59a2f42020-10-16 12:55:26 -07001705 NamedEnum::string(entry.type).c_str(), displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001706 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001707 }
1708
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001709 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
1710 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
1711 // start interacting with another application via touch (app switch). This code can be removed
1712 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
1713 // an app is expected to have a focused window.
1714 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
1715 if (!mNoFocusedWindowTimeoutTime.has_value()) {
1716 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001717 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
1718 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
1719 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001720 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05001721 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001722 ALOGW("Waiting because no window has focus but %s may eventually add a "
1723 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001724 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001725 *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001726 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001727 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
1728 // Already raised ANR. Drop the event
1729 ALOGE("Dropping %s event because there is no focused window",
Chris Yef59a2f42020-10-16 12:55:26 -07001730 NamedEnum::string(entry.type).c_str());
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001731 return InputEventInjectionResult::FAILED;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001732 } else {
1733 // Still waiting for the focused window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001734 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001735 }
1736 }
1737
1738 // we have a valid, non-null focused window
1739 resetNoFocusedWindowTimeoutLocked();
1740
Michael Wrightd02c5b62014-02-10 15:10:22 -08001741 // Check permissions.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001742 if (!checkInjectionPermission(focusedWindowHandle, entry.injectionState)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001743 return InputEventInjectionResult::PERMISSION_DENIED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001744 }
1745
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001746 if (focusedWindowHandle->getInfo()->paused) {
1747 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001748 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001749 }
1750
1751 // If the event is a key event, then we must wait for all previous events to
1752 // complete before delivering it because previous events may have the
1753 // side-effect of transferring focus to a different window and we want to
1754 // ensure that the following keys are sent to the new window.
1755 //
1756 // Suppose the user touches a button in a window then immediately presses "A".
1757 // If the button causes a pop-up window to appear then we want to ensure that
1758 // the "A" key is delivered to the new pop-up window. This is because users
1759 // often anticipate pending UI changes when typing on a keyboard.
1760 // To obtain this behavior, we must serialize key events with respect to all
1761 // prior input events.
1762 if (entry.type == EventEntry::Type::KEY) {
1763 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
1764 *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001765 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001766 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001767 }
1768
1769 // Success! Output targets.
Tiger Huang721e26f2018-07-24 22:26:19 +08001770 addWindowTargetLocked(focusedWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001771 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS,
1772 BitSet32(0), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001773
1774 // Done.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001775 return InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001776}
1777
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001778/**
1779 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
1780 * that are currently unresponsive.
1781 */
1782std::vector<TouchedMonitor> InputDispatcher::selectResponsiveMonitorsLocked(
1783 const std::vector<TouchedMonitor>& monitors) const {
1784 std::vector<TouchedMonitor> responsiveMonitors;
1785 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
1786 [this](const TouchedMonitor& monitor) REQUIRES(mLock) {
1787 sp<Connection> connection = getConnectionLocked(
1788 monitor.monitor.inputChannel->getConnectionToken());
1789 if (connection == nullptr) {
1790 ALOGE("Could not find connection for monitor %s",
1791 monitor.monitor.inputChannel->getName().c_str());
1792 return false;
1793 }
1794 if (!connection->responsive) {
1795 ALOGW("Unresponsive monitor %s will not get the new gesture",
1796 connection->inputChannel->getName().c_str());
1797 return false;
1798 }
1799 return true;
1800 });
1801 return responsiveMonitors;
1802}
1803
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001804InputEventInjectionResult InputDispatcher::findTouchedWindowTargetsLocked(
1805 nsecs_t currentTime, const MotionEntry& entry, std::vector<InputTarget>& inputTargets,
1806 nsecs_t* nextWakeupTime, bool* outConflictingPointerActions) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001807 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001808 enum InjectionPermission {
1809 INJECTION_PERMISSION_UNKNOWN,
1810 INJECTION_PERMISSION_GRANTED,
1811 INJECTION_PERMISSION_DENIED
1812 };
1813
Michael Wrightd02c5b62014-02-10 15:10:22 -08001814 // For security reasons, we defer updating the touch state until we are sure that
1815 // event injection will be allowed.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001816 int32_t displayId = entry.displayId;
1817 int32_t action = entry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001818 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
1819
1820 // Update the touch state as needed based on the properties of the touch event.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001821 InputEventInjectionResult injectionResult = InputEventInjectionResult::PENDING;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001822 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
Garfield Tandf26e862020-07-01 20:18:19 -07001823 sp<InputWindowHandle> newHoverWindowHandle(mLastHoverWindowHandle);
1824 sp<InputWindowHandle> newTouchedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001825
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001826 // Copy current touch state into tempTouchState.
1827 // This state will be used to update mTouchStatesByDisplay at the end of this function.
1828 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07001829 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001830 TouchState tempTouchState;
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07001831 std::unordered_map<int32_t, TouchState>::iterator oldStateIt =
1832 mTouchStatesByDisplay.find(displayId);
1833 if (oldStateIt != mTouchStatesByDisplay.end()) {
1834 oldState = &(oldStateIt->second);
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001835 tempTouchState.copyFrom(*oldState);
Jeff Brownf086ddb2014-02-11 14:28:48 -08001836 }
1837
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001838 bool isSplit = tempTouchState.split;
1839 bool switchedDevice = tempTouchState.deviceId >= 0 && tempTouchState.displayId >= 0 &&
1840 (tempTouchState.deviceId != entry.deviceId || tempTouchState.source != entry.source ||
1841 tempTouchState.displayId != displayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001842 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
1843 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
1844 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
1845 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN ||
1846 maskedAction == AMOTION_EVENT_ACTION_SCROLL || isHoverAction);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001847 const bool isFromMouse = entry.source == AINPUT_SOURCE_MOUSE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001848 bool wrongDevice = false;
1849 if (newGesture) {
1850 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001851 if (switchedDevice && tempTouchState.down && !down && !isHoverAction) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001852 ALOGI("Dropping event because a pointer for a different device is already down "
1853 "in display %" PRId32,
1854 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001855 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001856 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001857 switchedDevice = false;
1858 wrongDevice = true;
1859 goto Failed;
1860 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001861 tempTouchState.reset();
1862 tempTouchState.down = down;
1863 tempTouchState.deviceId = entry.deviceId;
1864 tempTouchState.source = entry.source;
1865 tempTouchState.displayId = displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001866 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001867 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001868 ALOGI("Dropping move event because a pointer for a different device is already active "
1869 "in display %" PRId32,
1870 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001871 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001872 injectionResult = InputEventInjectionResult::PERMISSION_DENIED;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001873 switchedDevice = false;
1874 wrongDevice = true;
1875 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001876 }
1877
1878 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
1879 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
1880
Garfield Tan00f511d2019-06-12 16:55:40 -07001881 int32_t x;
1882 int32_t y;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001883 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Garfield Tan00f511d2019-06-12 16:55:40 -07001884 // Always dispatch mouse events to cursor position.
1885 if (isFromMouse) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001886 x = int32_t(entry.xCursorPosition);
1887 y = int32_t(entry.yCursorPosition);
Garfield Tan00f511d2019-06-12 16:55:40 -07001888 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001889 x = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X));
1890 y = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y));
Garfield Tan00f511d2019-06-12 16:55:40 -07001891 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001892 bool isDown = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Garfield Tandf26e862020-07-01 20:18:19 -07001893 newTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001894 findTouchedWindowAtLocked(displayId, x, y, &tempTouchState,
1895 isDown /*addOutsideTargets*/, true /*addPortalWindows*/);
Michael Wright3dd60e22019-03-27 22:06:44 +00001896
1897 std::vector<TouchedMonitor> newGestureMonitors = isDown
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001898 ? findTouchedGestureMonitorsLocked(displayId, tempTouchState.portalWindows)
Michael Wright3dd60e22019-03-27 22:06:44 +00001899 : std::vector<TouchedMonitor>{};
Michael Wrightd02c5b62014-02-10 15:10:22 -08001900
Michael Wrightd02c5b62014-02-10 15:10:22 -08001901 // Figure out whether splitting will be allowed for this window.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001902 if (newTouchedWindowHandle != nullptr &&
1903 newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Garfield Tanaddb02b2019-06-25 16:36:13 -07001904 // New window supports splitting, but we should never split mouse events.
1905 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001906 } else if (isSplit) {
1907 // New window does not support splitting but we have already split events.
1908 // Ignore the new window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001909 newTouchedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001910 }
1911
1912 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001913 if (newTouchedWindowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001914 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001915 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001916 }
1917
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001918 if (newTouchedWindowHandle != nullptr && newTouchedWindowHandle->getInfo()->paused) {
1919 ALOGI("Not sending touch event to %s because it is paused",
1920 newTouchedWindowHandle->getName().c_str());
1921 newTouchedWindowHandle = nullptr;
1922 }
1923
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001924 // Ensure the window has a connection and the connection is responsive
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001925 if (newTouchedWindowHandle != nullptr) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001926 const bool isResponsive = hasResponsiveConnectionLocked(*newTouchedWindowHandle);
1927 if (!isResponsive) {
1928 ALOGW("%s will not receive the new gesture at %" PRIu64,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001929 newTouchedWindowHandle->getName().c_str(), entry.eventTime);
1930 newTouchedWindowHandle = nullptr;
1931 }
1932 }
1933
Bernardo Rufinoea97d182020-08-19 14:43:14 +01001934 // Drop events that can't be trusted due to occlusion
1935 if (newTouchedWindowHandle != nullptr &&
1936 mBlockUntrustedTouchesMode != BlockUntrustedTouchesMode::DISABLED) {
1937 TouchOcclusionInfo occlusionInfo =
1938 computeTouchOcclusionInfoLocked(newTouchedWindowHandle, x, y);
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00001939 if (!isTouchTrustedLocked(occlusionInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00001940 if (DEBUG_TOUCH_OCCLUSION) {
1941 ALOGD("Stack of obscuring windows during untrusted touch (%d, %d):", x, y);
1942 for (const auto& log : occlusionInfo.debugInfo) {
1943 ALOGD("%s", log.c_str());
1944 }
1945 }
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00001946 onUntrustedTouchLocked(occlusionInfo.obscuringPackage);
1947 if (mBlockUntrustedTouchesMode == BlockUntrustedTouchesMode::BLOCK) {
1948 ALOGW("Dropping untrusted touch event due to %s/%d",
1949 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid);
1950 newTouchedWindowHandle = nullptr;
1951 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01001952 }
1953 }
1954
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001955 // Also don't send the new touch event to unresponsive gesture monitors
1956 newGestureMonitors = selectResponsiveMonitorsLocked(newGestureMonitors);
1957
Michael Wright3dd60e22019-03-27 22:06:44 +00001958 if (newTouchedWindowHandle == nullptr && newGestureMonitors.empty()) {
1959 ALOGI("Dropping event because there is no touchable window or gesture monitor at "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001960 "(%d, %d) in display %" PRId32 ".",
1961 x, y, displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001962 injectionResult = InputEventInjectionResult::FAILED;
Michael Wright3dd60e22019-03-27 22:06:44 +00001963 goto Failed;
1964 }
1965
1966 if (newTouchedWindowHandle != nullptr) {
1967 // Set target flags.
1968 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
1969 if (isSplit) {
1970 targetFlags |= InputTarget::FLAG_SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001971 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001972 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1973 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1974 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
1975 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1976 }
1977
1978 // Update hover state.
Garfield Tandf26e862020-07-01 20:18:19 -07001979 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
1980 newHoverWindowHandle = nullptr;
1981 } else if (isHoverAction) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001982 newHoverWindowHandle = newTouchedWindowHandle;
Michael Wright3dd60e22019-03-27 22:06:44 +00001983 }
1984
1985 // Update the temporary touch state.
1986 BitSet32 pointerIds;
1987 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001988 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wright3dd60e22019-03-27 22:06:44 +00001989 pointerIds.markBit(pointerId);
1990 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001991 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001992 }
1993
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001994 tempTouchState.addGestureMonitors(newGestureMonitors);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001995 } else {
1996 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
1997
1998 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001999 if (!tempTouchState.down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002000 if (DEBUG_FOCUS) {
2001 ALOGD("Dropping event because the pointer is not down or we previously "
2002 "dropped the pointer down event in display %" PRId32,
2003 displayId);
2004 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002005 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002006 goto Failed;
2007 }
2008
2009 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002010 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002011 tempTouchState.isSlippery()) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002012 int32_t x = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
2013 int32_t y = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002014
2015 sp<InputWindowHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002016 tempTouchState.getFirstForegroundWindowHandle();
Garfield Tandf26e862020-07-01 20:18:19 -07002017 newTouchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y, &tempTouchState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002018 if (oldTouchedWindowHandle != newTouchedWindowHandle &&
2019 oldTouchedWindowHandle != nullptr && newTouchedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002020 if (DEBUG_FOCUS) {
2021 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
2022 oldTouchedWindowHandle->getName().c_str(),
2023 newTouchedWindowHandle->getName().c_str(), displayId);
2024 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002025 // Make a slippery exit from the old window.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002026 tempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
2027 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT,
2028 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002029
2030 // Make a slippery entrance into the new window.
2031 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
2032 isSplit = true;
2033 }
2034
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002035 int32_t targetFlags =
2036 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002037 if (isSplit) {
2038 targetFlags |= InputTarget::FLAG_SPLIT;
2039 }
2040 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
2041 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002042 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
2043 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002044 }
2045
2046 BitSet32 pointerIds;
2047 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002048 pointerIds.markBit(entry.pointerProperties[0].id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002049 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002050 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002051 }
2052 }
2053 }
2054
2055 if (newHoverWindowHandle != mLastHoverWindowHandle) {
Garfield Tandf26e862020-07-01 20:18:19 -07002056 // Let the previous window know that the hover sequence is over, unless we already did it
2057 // when dispatching it as is to newTouchedWindowHandle.
2058 if (mLastHoverWindowHandle != nullptr &&
2059 (maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT ||
2060 mLastHoverWindowHandle != newTouchedWindowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002061#if DEBUG_HOVER
2062 ALOGD("Sending hover exit event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002063 mLastHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002064#endif
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002065 tempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
2066 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002067 }
2068
Garfield Tandf26e862020-07-01 20:18:19 -07002069 // Let the new window know that the hover sequence is starting, unless we already did it
2070 // when dispatching it as is to newTouchedWindowHandle.
2071 if (newHoverWindowHandle != nullptr &&
2072 (maskedAction != AMOTION_EVENT_ACTION_HOVER_ENTER ||
2073 newHoverWindowHandle != newTouchedWindowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002074#if DEBUG_HOVER
2075 ALOGD("Sending hover enter event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002076 newHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002077#endif
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002078 tempTouchState.addOrUpdateWindow(newHoverWindowHandle,
2079 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER,
2080 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002081 }
2082 }
2083
2084 // Check permission to inject into all touched foreground windows and ensure there
2085 // is at least one touched foreground window.
2086 {
2087 bool haveForegroundWindow = false;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002088 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002089 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
2090 haveForegroundWindow = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002091 if (!checkInjectionPermission(touchedWindow.windowHandle, entry.injectionState)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002092 injectionResult = InputEventInjectionResult::PERMISSION_DENIED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002093 injectionPermission = INJECTION_PERMISSION_DENIED;
2094 goto Failed;
2095 }
2096 }
2097 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002098 bool hasGestureMonitor = !tempTouchState.gestureMonitors.empty();
Michael Wright3dd60e22019-03-27 22:06:44 +00002099 if (!haveForegroundWindow && !hasGestureMonitor) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002100 ALOGI("Dropping event because there is no touched foreground window in display "
2101 "%" PRId32 " or gesture monitor to receive it.",
2102 displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002103 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002104 goto Failed;
2105 }
2106
2107 // Permission granted to injection into all touched foreground windows.
2108 injectionPermission = INJECTION_PERMISSION_GRANTED;
2109 }
2110
2111 // Check whether windows listening for outside touches are owned by the same UID. If it is
2112 // set the policy flag that we will not reveal coordinate information to this window.
2113 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2114 sp<InputWindowHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002115 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002116 if (foregroundWindowHandle) {
2117 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002118 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002119 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2120 sp<InputWindowHandle> inputWindowHandle = touchedWindow.windowHandle;
2121 if (inputWindowHandle->getInfo()->ownerUid != foregroundWindowUid) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002122 tempTouchState.addOrUpdateWindow(inputWindowHandle,
2123 InputTarget::FLAG_ZERO_COORDS,
2124 BitSet32(0));
Michael Wright3dd60e22019-03-27 22:06:44 +00002125 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002126 }
2127 }
2128 }
2129 }
2130
Michael Wrightd02c5b62014-02-10 15:10:22 -08002131 // If this is the first pointer going down and the touched window has a wallpaper
2132 // then also add the touched wallpaper windows so they are locked in for the duration
2133 // of the touch gesture.
2134 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
2135 // engine only supports touch events. We would need to add a mechanism similar
2136 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
2137 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2138 sp<InputWindowHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002139 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002140 if (foregroundWindowHandle && foregroundWindowHandle->getInfo()->hasWallpaper) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07002141 const std::vector<sp<InputWindowHandle>>& windowHandles =
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002142 getWindowHandlesLocked(displayId);
2143 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002144 const InputWindowInfo* info = windowHandle->getInfo();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002145 if (info->displayId == displayId &&
Michael Wright44753b12020-07-08 13:48:11 +01002146 windowHandle->getInfo()->type == InputWindowInfo::Type::WALLPAPER) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002147 tempTouchState
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002148 .addOrUpdateWindow(windowHandle,
2149 InputTarget::FLAG_WINDOW_IS_OBSCURED |
2150 InputTarget::
2151 FLAG_WINDOW_IS_PARTIALLY_OBSCURED |
2152 InputTarget::FLAG_DISPATCH_AS_IS,
2153 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002154 }
2155 }
2156 }
2157 }
2158
2159 // Success! Output targets.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002160 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002161
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002162 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002163 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002164 touchedWindow.pointerIds, inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002165 }
2166
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002167 for (const TouchedMonitor& touchedMonitor : tempTouchState.gestureMonitors) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002168 addMonitoringTargetLocked(touchedMonitor.monitor, touchedMonitor.xOffset,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002169 touchedMonitor.yOffset, inputTargets);
Michael Wright3dd60e22019-03-27 22:06:44 +00002170 }
2171
Michael Wrightd02c5b62014-02-10 15:10:22 -08002172 // Drop the outside or hover touch windows since we will not care about them
2173 // in the next iteration.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002174 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002175
2176Failed:
2177 // Check injection permission once and for all.
2178 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002179 if (checkInjectionPermission(nullptr, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002180 injectionPermission = INJECTION_PERMISSION_GRANTED;
2181 } else {
2182 injectionPermission = INJECTION_PERMISSION_DENIED;
2183 }
2184 }
2185
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002186 if (injectionPermission != INJECTION_PERMISSION_GRANTED) {
2187 return injectionResult;
2188 }
2189
Michael Wrightd02c5b62014-02-10 15:10:22 -08002190 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002191 if (!wrongDevice) {
2192 if (switchedDevice) {
2193 if (DEBUG_FOCUS) {
2194 ALOGD("Conflicting pointer actions: Switched to a different device.");
2195 }
2196 *outConflictingPointerActions = true;
2197 }
2198
2199 if (isHoverAction) {
2200 // Started hovering, therefore no longer down.
2201 if (oldState && oldState->down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002202 if (DEBUG_FOCUS) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002203 ALOGD("Conflicting pointer actions: Hover received while pointer was "
2204 "down.");
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002205 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002206 *outConflictingPointerActions = true;
2207 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002208 tempTouchState.reset();
2209 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2210 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
2211 tempTouchState.deviceId = entry.deviceId;
2212 tempTouchState.source = entry.source;
2213 tempTouchState.displayId = displayId;
2214 }
2215 } else if (maskedAction == AMOTION_EVENT_ACTION_UP ||
2216 maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
2217 // All pointers up or canceled.
2218 tempTouchState.reset();
2219 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2220 // First pointer went down.
2221 if (oldState && oldState->down) {
2222 if (DEBUG_FOCUS) {
2223 ALOGD("Conflicting pointer actions: Down received while already down.");
2224 }
2225 *outConflictingPointerActions = true;
2226 }
2227 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2228 // One pointer went up.
2229 if (isSplit) {
2230 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2231 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002232
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002233 for (size_t i = 0; i < tempTouchState.windows.size();) {
2234 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2235 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
2236 touchedWindow.pointerIds.clearBit(pointerId);
2237 if (touchedWindow.pointerIds.isEmpty()) {
2238 tempTouchState.windows.erase(tempTouchState.windows.begin() + i);
2239 continue;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002240 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002241 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002242 i += 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002243 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002244 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002245 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002246
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002247 // Save changes unless the action was scroll in which case the temporary touch
2248 // state was only valid for this one action.
2249 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
2250 if (tempTouchState.displayId >= 0) {
2251 mTouchStatesByDisplay[displayId] = tempTouchState;
2252 } else {
2253 mTouchStatesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002254 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002255 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002256
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002257 // Update hover state.
2258 mLastHoverWindowHandle = newHoverWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002259 }
2260
Michael Wrightd02c5b62014-02-10 15:10:22 -08002261 return injectionResult;
2262}
2263
2264void InputDispatcher::addWindowTargetLocked(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002265 int32_t targetFlags, BitSet32 pointerIds,
2266 std::vector<InputTarget>& inputTargets) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002267 std::vector<InputTarget>::iterator it =
2268 std::find_if(inputTargets.begin(), inputTargets.end(),
2269 [&windowHandle](const InputTarget& inputTarget) {
2270 return inputTarget.inputChannel->getConnectionToken() ==
2271 windowHandle->getToken();
2272 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002273
Chavi Weingarten114b77f2020-01-15 22:35:10 +00002274 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002275
2276 if (it == inputTargets.end()) {
2277 InputTarget inputTarget;
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05002278 std::shared_ptr<InputChannel> inputChannel =
2279 getInputChannelLocked(windowHandle->getToken());
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002280 if (inputChannel == nullptr) {
2281 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
2282 return;
2283 }
2284 inputTarget.inputChannel = inputChannel;
2285 inputTarget.flags = targetFlags;
2286 inputTarget.globalScaleFactor = windowInfo->globalScaleFactor;
2287 inputTargets.push_back(inputTarget);
2288 it = inputTargets.end() - 1;
2289 }
2290
2291 ALOG_ASSERT(it->flags == targetFlags);
2292 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
2293
chaviw1ff3d1e2020-07-01 15:53:47 -07002294 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002295}
2296
Michael Wright3dd60e22019-03-27 22:06:44 +00002297void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002298 int32_t displayId, float xOffset,
2299 float yOffset) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002300 std::unordered_map<int32_t, std::vector<Monitor>>::const_iterator it =
2301 mGlobalMonitorsByDisplay.find(displayId);
2302
2303 if (it != mGlobalMonitorsByDisplay.end()) {
2304 const std::vector<Monitor>& monitors = it->second;
2305 for (const Monitor& monitor : monitors) {
2306 addMonitoringTargetLocked(monitor, xOffset, yOffset, inputTargets);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002307 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002308 }
2309}
2310
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002311void InputDispatcher::addMonitoringTargetLocked(const Monitor& monitor, float xOffset,
2312 float yOffset,
2313 std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002314 InputTarget target;
2315 target.inputChannel = monitor.inputChannel;
2316 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
chaviw1ff3d1e2020-07-01 15:53:47 -07002317 ui::Transform t;
2318 t.set(xOffset, yOffset);
2319 target.setDefaultPointerTransform(t);
Michael Wright3dd60e22019-03-27 22:06:44 +00002320 inputTargets.push_back(target);
2321}
2322
Michael Wrightd02c5b62014-02-10 15:10:22 -08002323bool InputDispatcher::checkInjectionPermission(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002324 const InjectionState* injectionState) {
2325 if (injectionState &&
2326 (windowHandle == nullptr ||
2327 windowHandle->getInfo()->ownerUid != injectionState->injectorUid) &&
2328 !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002329 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002330 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002331 "owned by uid %d",
2332 injectionState->injectorPid, injectionState->injectorUid,
2333 windowHandle->getName().c_str(), windowHandle->getInfo()->ownerUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002334 } else {
2335 ALOGW("Permission denied: injecting event from pid %d uid %d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002336 injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002337 }
2338 return false;
2339 }
2340 return true;
2341}
2342
Robert Carrc9bf1d32020-04-13 17:21:08 -07002343/**
2344 * Indicate whether one window handle should be considered as obscuring
2345 * another window handle. We only check a few preconditions. Actually
2346 * checking the bounds is left to the caller.
2347 */
2348static bool canBeObscuredBy(const sp<InputWindowHandle>& windowHandle,
2349 const sp<InputWindowHandle>& otherHandle) {
2350 // Compare by token so cloned layers aren't counted
2351 if (haveSameToken(windowHandle, otherHandle)) {
2352 return false;
2353 }
2354 auto info = windowHandle->getInfo();
2355 auto otherInfo = otherHandle->getInfo();
2356 if (!otherInfo->visible) {
2357 return false;
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002358 } else if (otherInfo->alpha == 0 &&
2359 otherInfo->flags.test(InputWindowInfo::Flag::NOT_TOUCHABLE)) {
2360 // Those act as if they were invisible, so we don't need to flag them.
2361 // We do want to potentially flag touchable windows even if they have 0
2362 // opacity, since they can consume touches and alter the effects of the
2363 // user interaction (eg. apps that rely on
2364 // FLAG_WINDOW_IS_PARTIALLY_OBSCURED should still be told about those
2365 // windows), hence we also check for FLAG_NOT_TOUCHABLE.
2366 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00002367 } else if (info->ownerUid == otherInfo->ownerUid) {
2368 // If ownerUid is the same we don't generate occlusion events as there
2369 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002370 return false;
Chris Yefcdff3e2020-05-10 15:16:04 -07002371 } else if (otherInfo->trustedOverlay) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002372 return false;
2373 } else if (otherInfo->displayId != info->displayId) {
2374 return false;
2375 }
2376 return true;
2377}
2378
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002379/**
2380 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
2381 * untrusted, one should check:
2382 *
2383 * 1. If result.hasBlockingOcclusion is true.
2384 * If it's, it means the touch should be blocked due to a window with occlusion mode of
2385 * BLOCK_UNTRUSTED.
2386 *
2387 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
2388 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
2389 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
2390 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
2391 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
2392 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
2393 *
2394 * If neither of those is true, then it means the touch can be allowed.
2395 */
2396InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
2397 const sp<InputWindowHandle>& windowHandle, int32_t x, int32_t y) const {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002398 const InputWindowInfo* windowInfo = windowHandle->getInfo();
2399 int32_t displayId = windowInfo->displayId;
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002400 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2401 TouchOcclusionInfo info;
2402 info.hasBlockingOcclusion = false;
2403 info.obscuringOpacity = 0;
2404 info.obscuringUid = -1;
2405 std::map<int32_t, float> opacityByUid;
2406 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
2407 if (windowHandle == otherHandle) {
2408 break; // All future windows are below us. Exit early.
2409 }
2410 const InputWindowInfo* otherInfo = otherHandle->getInfo();
2411 if (canBeObscuredBy(windowHandle, otherHandle) &&
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002412 windowInfo->ownerUid != otherInfo->ownerUid && otherInfo->frameContainsPoint(x, y)) {
2413 if (DEBUG_TOUCH_OCCLUSION) {
2414 info.debugInfo.push_back(
2415 dumpWindowForTouchOcclusion(otherInfo, /* isTouchedWindow */ false));
2416 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002417 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
2418 // we perform the checks below to see if the touch can be propagated or not based on the
2419 // window's touch occlusion mode
2420 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
2421 info.hasBlockingOcclusion = true;
2422 info.obscuringUid = otherInfo->ownerUid;
2423 info.obscuringPackage = otherInfo->packageName;
2424 break;
2425 }
2426 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
2427 uint32_t uid = otherInfo->ownerUid;
2428 float opacity =
2429 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
2430 // Given windows A and B:
2431 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
2432 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
2433 opacityByUid[uid] = opacity;
2434 if (opacity > info.obscuringOpacity) {
2435 info.obscuringOpacity = opacity;
2436 info.obscuringUid = uid;
2437 info.obscuringPackage = otherInfo->packageName;
2438 }
2439 }
2440 }
2441 }
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002442 if (DEBUG_TOUCH_OCCLUSION) {
2443 info.debugInfo.push_back(
2444 dumpWindowForTouchOcclusion(windowInfo, /* isTouchedWindow */ true));
2445 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002446 return info;
2447}
2448
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002449std::string InputDispatcher::dumpWindowForTouchOcclusion(const InputWindowInfo* info,
2450 bool isTouchedWindow) const {
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00002451 return StringPrintf(INDENT2 "* %stype=%s, package=%s/%" PRId32 ", id=%" PRId32
2452 ", mode=%s, alpha=%.2f, "
Bernardo Rufinoc2f1fad2020-11-04 17:30:57 +00002453 "frame=[%" PRId32 ",%" PRId32 "][%" PRId32 ",%" PRId32
2454 "], touchableRegion=%s, window={%s}, applicationInfo=%s, "
2455 "flags={%s}, inputFeatures={%s}, hasToken=%s\n",
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002456 (isTouchedWindow) ? "[TOUCHED] " : "",
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00002457 NamedEnum::string(info->type, "%" PRId32).c_str(),
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00002458 info->packageName.c_str(), info->ownerUid, info->id,
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00002459 toString(info->touchOcclusionMode).c_str(), info->alpha, info->frameLeft,
2460 info->frameTop, info->frameRight, info->frameBottom,
2461 dumpRegion(info->touchableRegion).c_str(), info->name.c_str(),
Bernardo Rufinoc2f1fad2020-11-04 17:30:57 +00002462 info->applicationInfo.name.c_str(), info->flags.string().c_str(),
2463 info->inputFeatures.string().c_str(), toString(info->token != nullptr));
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002464}
2465
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002466bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
2467 if (occlusionInfo.hasBlockingOcclusion) {
2468 ALOGW("Untrusted touch due to occlusion by %s/%d", occlusionInfo.obscuringPackage.c_str(),
2469 occlusionInfo.obscuringUid);
2470 return false;
2471 }
2472 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
2473 ALOGW("Untrusted touch due to occlusion by %s/%d (obscuring opacity = "
2474 "%.2f, maximum allowed = %.2f)",
2475 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid,
2476 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
2477 return false;
2478 }
2479 return true;
2480}
2481
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002482bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<InputWindowHandle>& windowHandle,
2483 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002484 int32_t displayId = windowHandle->getInfo()->displayId;
Vishnu Nairad321cd2020-08-20 16:40:21 -07002485 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002486 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002487 if (windowHandle == otherHandle) {
2488 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002489 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002490 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002491 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002492 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002493 return true;
2494 }
2495 }
2496 return false;
2497}
2498
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002499bool InputDispatcher::isWindowObscuredLocked(const sp<InputWindowHandle>& windowHandle) const {
2500 int32_t displayId = windowHandle->getInfo()->displayId;
Vishnu Nairad321cd2020-08-20 16:40:21 -07002501 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002502 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002503 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002504 if (windowHandle == otherHandle) {
2505 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002506 }
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002507 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002508 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002509 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002510 return true;
2511 }
2512 }
2513 return false;
2514}
2515
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002516std::string InputDispatcher::getApplicationWindowLabel(
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05002517 const InputApplicationHandle* applicationHandle,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002518 const sp<InputWindowHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002519 if (applicationHandle != nullptr) {
2520 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002521 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002522 } else {
2523 return applicationHandle->getName();
2524 }
Yi Kong9b14ac62018-07-17 13:48:38 -07002525 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002526 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002527 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002528 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002529 }
2530}
2531
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002532void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Prabir Pradhan99987712020-11-10 18:43:05 -08002533 if (eventEntry.type == EventEntry::Type::FOCUS ||
2534 eventEntry.type == EventEntry::Type::POINTER_CAPTURE_CHANGED) {
2535 // Focus or pointer capture changed events are passed to apps, but do not represent user
2536 // activity.
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002537 return;
2538 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002539 int32_t displayId = getTargetDisplayId(eventEntry);
Vishnu Nairad321cd2020-08-20 16:40:21 -07002540 sp<InputWindowHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Tiger Huang721e26f2018-07-24 22:26:19 +08002541 if (focusedWindowHandle != nullptr) {
2542 const InputWindowInfo* info = focusedWindowHandle->getInfo();
Michael Wright44753b12020-07-08 13:48:11 +01002543 if (info->inputFeatures.test(InputWindowInfo::Feature::DISABLE_USER_ACTIVITY)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002544#if DEBUG_DISPATCH_CYCLE
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002545 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002546#endif
2547 return;
2548 }
2549 }
2550
2551 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002552 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002553 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002554 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
2555 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002556 return;
2557 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002558
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002559 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002560 eventType = USER_ACTIVITY_EVENT_TOUCH;
2561 }
2562 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002563 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002564 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002565 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
2566 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002567 return;
2568 }
2569 eventType = USER_ACTIVITY_EVENT_BUTTON;
2570 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002571 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002572 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002573 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08002574 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07002575 case EventEntry::Type::SENSOR:
Prabir Pradhan99987712020-11-10 18:43:05 -08002576 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002577 LOG_ALWAYS_FATAL("%s events are not user activity",
Chris Yef59a2f42020-10-16 12:55:26 -07002578 NamedEnum::string(eventEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002579 break;
2580 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002581 }
2582
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002583 std::unique_ptr<CommandEntry> commandEntry =
2584 std::make_unique<CommandEntry>(&InputDispatcher::doPokeUserActivityLockedInterruptible);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002585 commandEntry->eventTime = eventEntry.eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002586 commandEntry->userActivityEventType = eventType;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002587 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002588}
2589
2590void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002591 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002592 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002593 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002594 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002595 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002596 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002597 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002598 ATRACE_NAME(message.c_str());
2599 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002600#if DEBUG_DISPATCH_CYCLE
2601 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002602 "globalScaleFactor=%f, pointerIds=0x%x %s",
2603 connection->getInputChannelName().c_str(), inputTarget.flags,
2604 inputTarget.globalScaleFactor, inputTarget.pointerIds.value,
2605 inputTarget.getPointerInfoString().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002606#endif
2607
2608 // Skip this event if the connection status is not normal.
2609 // We don't want to enqueue additional outbound events if the connection is broken.
2610 if (connection->status != Connection::STATUS_NORMAL) {
2611#if DEBUG_DISPATCH_CYCLE
2612 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002613 connection->getInputChannelName().c_str(), connection->getStatusLabel());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002614#endif
2615 return;
2616 }
2617
2618 // Split a motion event if needed.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002619 if (inputTarget.flags & InputTarget::FLAG_SPLIT) {
2620 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
2621 "Entry type %s should not have FLAG_SPLIT",
Chris Yef59a2f42020-10-16 12:55:26 -07002622 NamedEnum::string(eventEntry->type).c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002623
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002624 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002625 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002626 std::unique_ptr<MotionEntry> splitMotionEntry =
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002627 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002628 if (!splitMotionEntry) {
2629 return; // split event was dropped
2630 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002631 if (DEBUG_FOCUS) {
2632 ALOGD("channel '%s' ~ Split motion event.",
2633 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002634 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002635 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002636 enqueueDispatchEntriesLocked(currentTime, connection, std::move(splitMotionEntry),
2637 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002638 return;
2639 }
2640 }
2641
2642 // Not splitting. Enqueue dispatch entries for the event as is.
2643 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
2644}
2645
2646void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002647 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002648 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002649 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002650 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002651 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002652 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002653 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002654 ATRACE_NAME(message.c_str());
2655 }
2656
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002657 bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002658
2659 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07002660 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002661 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002662 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002663 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07002664 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002665 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07002666 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002667 InputTarget::FLAG_DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07002668 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002669 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002670 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002671 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002672
2673 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002674 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002675 startDispatchCycleLocked(currentTime, connection);
2676 }
2677}
2678
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002679void InputDispatcher::enqueueDispatchEntryLocked(const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002680 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002681 const InputTarget& inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002682 int32_t dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002683 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002684 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
2685 connection->getInputChannelName().c_str(),
2686 dispatchModeToString(dispatchMode).c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002687 ATRACE_NAME(message.c_str());
2688 }
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002689 int32_t inputTargetFlags = inputTarget.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002690 if (!(inputTargetFlags & dispatchMode)) {
2691 return;
2692 }
2693 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
2694
2695 // This is a new event.
2696 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002697 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002698 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002699
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002700 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
2701 // different EventEntry than what was passed in.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002702 EventEntry& newEntry = *(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002703 // Apply target flags and update the connection's input state.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002704 switch (newEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002705 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002706 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002707 dispatchEntry->resolvedEventId = keyEntry.id;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002708 dispatchEntry->resolvedAction = keyEntry.action;
2709 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002710
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002711 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
2712 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002713#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002714 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key event",
2715 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002716#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002717 return; // skip the inconsistent event
2718 }
2719 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002720 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002721
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002722 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002723 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002724 // Assign a default value to dispatchEntry that will never be generated by InputReader,
2725 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
2726 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
2727 static_cast<int32_t>(IdGenerator::Source::OTHER);
2728 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002729 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2730 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
2731 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
2732 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
2733 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
2734 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2735 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
2736 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
2737 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
2738 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
2739 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002740 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002741 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002742 }
2743 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002744 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
2745 motionEntry.displayId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002746#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002747 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover enter "
2748 "event",
2749 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002750#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002751 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2752 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002753
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002754 dispatchEntry->resolvedFlags = motionEntry.flags;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002755 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
2756 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
2757 }
2758 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
2759 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2760 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002761
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002762 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
2763 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002764#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002765 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
2766 "event",
2767 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002768#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002769 return; // skip the inconsistent event
2770 }
2771
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002772 dispatchEntry->resolvedEventId =
2773 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
2774 ? mIdGenerator.nextId()
2775 : motionEntry.id;
2776 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
2777 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
2778 ") to MotionEvent(id=0x%" PRIx32 ").",
2779 motionEntry.id, dispatchEntry->resolvedEventId);
2780 ATRACE_NAME(message.c_str());
2781 }
2782
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002783 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002784 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002785
2786 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002787 }
Prabir Pradhan99987712020-11-10 18:43:05 -08002788 case EventEntry::Type::FOCUS:
2789 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002790 break;
2791 }
Chris Yef59a2f42020-10-16 12:55:26 -07002792 case EventEntry::Type::SENSOR: {
2793 LOG_ALWAYS_FATAL("SENSOR events should not go to apps via input channel");
2794 break;
2795 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002796 case EventEntry::Type::CONFIGURATION_CHANGED:
2797 case EventEntry::Type::DEVICE_RESET: {
2798 LOG_ALWAYS_FATAL("%s events should not go to apps",
Chris Yef59a2f42020-10-16 12:55:26 -07002799 NamedEnum::string(newEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002800 break;
2801 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002802 }
2803
2804 // Remember that we are waiting for this dispatch to complete.
2805 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002806 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002807 }
2808
2809 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002810 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002811 traceOutboundQueueLength(connection);
chaviw8c9cf542019-03-25 13:02:48 -07002812}
2813
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00002814/**
2815 * This function is purely for debugging. It helps us understand where the user interaction
2816 * was taking place. For example, if user is touching launcher, we will see a log that user
2817 * started interacting with launcher. In that example, the event would go to the wallpaper as well.
2818 * We will see both launcher and wallpaper in that list.
2819 * Once the interaction with a particular set of connections starts, no new logs will be printed
2820 * until the set of interacted connections changes.
2821 *
2822 * The following items are skipped, to reduce the logspam:
2823 * ACTION_OUTSIDE: any windows that are receiving ACTION_OUTSIDE are not logged
2824 * ACTION_UP: any windows that receive ACTION_UP are not logged (for both keys and motions).
2825 * This includes situations like the soft BACK button key. When the user releases (lifts up the
2826 * finger) the back button, then navigation bar will inject KEYCODE_BACK with ACTION_UP.
2827 * Both of those ACTION_UP events would not be logged
2828 * Monitors (both gesture and global): any gesture monitors or global monitors receiving events
2829 * will not be logged. This is omitted to reduce the amount of data printed.
2830 * If you see <none>, it's likely that one of the gesture monitors pilfered the event, and therefore
2831 * gesture monitor is the only connection receiving the remainder of the gesture.
2832 */
2833void InputDispatcher::updateInteractionTokensLocked(const EventEntry& entry,
2834 const std::vector<InputTarget>& targets) {
2835 // Skip ACTION_UP events, and all events other than keys and motions
2836 if (entry.type == EventEntry::Type::KEY) {
2837 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
2838 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
2839 return;
2840 }
2841 } else if (entry.type == EventEntry::Type::MOTION) {
2842 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
2843 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
2844 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
2845 return;
2846 }
2847 } else {
2848 return; // Not a key or a motion
2849 }
2850
2851 std::unordered_set<sp<IBinder>, IBinderHash> newConnectionTokens;
2852 std::vector<sp<Connection>> newConnections;
2853 for (const InputTarget& target : targets) {
2854 if ((target.flags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) ==
2855 InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2856 continue; // Skip windows that receive ACTION_OUTSIDE
2857 }
2858
2859 sp<IBinder> token = target.inputChannel->getConnectionToken();
2860 sp<Connection> connection = getConnectionLocked(token);
2861 if (connection == nullptr || connection->monitor) {
2862 continue; // We only need to keep track of the non-monitor connections.
2863 }
2864 newConnectionTokens.insert(std::move(token));
2865 newConnections.emplace_back(connection);
2866 }
2867 if (newConnectionTokens == mInteractionConnectionTokens) {
2868 return; // no change
2869 }
2870 mInteractionConnectionTokens = newConnectionTokens;
2871
2872 std::string windowList;
2873 for (const sp<Connection>& connection : newConnections) {
2874 windowList += connection->getWindowName() + ", ";
2875 }
2876 std::string message = "Interaction with windows: " + windowList;
2877 if (windowList.empty()) {
2878 message += "<none>";
2879 }
2880 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
2881}
2882
chaviwfd6d3512019-03-25 13:23:49 -07002883void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07002884 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07002885 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07002886 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
2887 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07002888 return;
2889 }
2890
Vishnu Nairad321cd2020-08-20 16:40:21 -07002891 sp<IBinder> focusedToken = getValueByKey(mFocusedWindowTokenByDisplay, mFocusedDisplayId);
2892 if (focusedToken == token) {
2893 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07002894 return;
2895 }
2896
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002897 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
2898 &InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible);
Vishnu Nairad321cd2020-08-20 16:40:21 -07002899 commandEntry->newToken = token;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002900 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002901}
2902
2903void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002904 const sp<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002905 if (ATRACE_ENABLED()) {
2906 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002907 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002908 ATRACE_NAME(message.c_str());
2909 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002910#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002911 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002912#endif
2913
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002914 while (connection->status == Connection::STATUS_NORMAL && !connection->outboundQueue.empty()) {
2915 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002916 dispatchEntry->deliveryTime = currentTime;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05002917 const std::chrono::nanoseconds timeout =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002918 getDispatchingTimeoutLocked(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou70622952020-07-30 11:17:23 -05002919 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002920
2921 // Publish the event.
2922 status_t status;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002923 const EventEntry& eventEntry = *(dispatchEntry->eventEntry);
2924 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002925 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002926 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
2927 std::array<uint8_t, 32> hmac = getSignature(keyEntry, *dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002928
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002929 // Publish the key event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002930 status = connection->inputPublisher
2931 .publishKeyEvent(dispatchEntry->seq,
2932 dispatchEntry->resolvedEventId, keyEntry.deviceId,
2933 keyEntry.source, keyEntry.displayId,
2934 std::move(hmac), dispatchEntry->resolvedAction,
2935 dispatchEntry->resolvedFlags, keyEntry.keyCode,
2936 keyEntry.scanCode, keyEntry.metaState,
2937 keyEntry.repeatCount, keyEntry.downTime,
2938 keyEntry.eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002939 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002940 }
2941
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002942 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002943 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002944
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002945 PointerCoords scaledCoords[MAX_POINTERS];
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002946 const PointerCoords* usingCoords = motionEntry.pointerCoords;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002947
chaviw82357092020-01-28 13:13:06 -08002948 // Set the X and Y offset and X and Y scale depending on the input source.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002949 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) &&
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002950 !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
2951 float globalScaleFactor = dispatchEntry->globalScaleFactor;
chaviw82357092020-01-28 13:13:06 -08002952 if (globalScaleFactor != 1.0f) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002953 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
2954 scaledCoords[i] = motionEntry.pointerCoords[i];
chaviw82357092020-01-28 13:13:06 -08002955 // Don't apply window scale here since we don't want scale to affect raw
2956 // coordinates. The scale will be sent back to the client and applied
2957 // later when requesting relative coordinates.
2958 scaledCoords[i].scale(globalScaleFactor, 1 /* windowXScale */,
2959 1 /* windowYScale */);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002960 }
2961 usingCoords = scaledCoords;
2962 }
2963 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002964 // We don't want the dispatch target to know.
2965 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002966 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002967 scaledCoords[i].clear();
2968 }
2969 usingCoords = scaledCoords;
2970 }
2971 }
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07002972
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002973 std::array<uint8_t, 32> hmac = getSignature(motionEntry, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002974
2975 // Publish the motion event.
2976 status = connection->inputPublisher
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002977 .publishMotionEvent(dispatchEntry->seq,
2978 dispatchEntry->resolvedEventId,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002979 motionEntry.deviceId, motionEntry.source,
2980 motionEntry.displayId, std::move(hmac),
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002981 dispatchEntry->resolvedAction,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002982 motionEntry.actionButton,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002983 dispatchEntry->resolvedFlags,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002984 motionEntry.edgeFlags, motionEntry.metaState,
2985 motionEntry.buttonState,
2986 motionEntry.classification,
chaviw9eaa22c2020-07-01 16:21:27 -07002987 dispatchEntry->transform,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002988 motionEntry.xPrecision, motionEntry.yPrecision,
2989 motionEntry.xCursorPosition,
2990 motionEntry.yCursorPosition,
2991 motionEntry.downTime, motionEntry.eventTime,
2992 motionEntry.pointerCount,
2993 motionEntry.pointerProperties, usingCoords);
2994 reportTouchEventForStatistics(motionEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002995 break;
2996 }
Prabir Pradhan99987712020-11-10 18:43:05 -08002997
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002998 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002999 const FocusEntry& focusEntry = static_cast<const FocusEntry&>(eventEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003000 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003001 focusEntry.id,
3002 focusEntry.hasFocus,
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003003 mInTouchMode);
3004 break;
3005 }
3006
Prabir Pradhan99987712020-11-10 18:43:05 -08003007 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3008 const auto& captureEntry =
3009 static_cast<const PointerCaptureChangedEntry&>(eventEntry);
3010 status = connection->inputPublisher
3011 .publishCaptureEvent(dispatchEntry->seq, captureEntry.id,
3012 captureEntry.pointerCaptureEnabled);
3013 break;
3014 }
3015
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003016 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003017 case EventEntry::Type::DEVICE_RESET:
3018 case EventEntry::Type::SENSOR: {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003019 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
Chris Yef59a2f42020-10-16 12:55:26 -07003020 NamedEnum::string(eventEntry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003021 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003022 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003023 }
3024
3025 // Check the result.
3026 if (status) {
3027 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003028 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003029 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003030 "This is unexpected because the wait queue is empty, so the pipe "
3031 "should be empty and we shouldn't have any problems writing an "
3032 "event to it, status=%d",
3033 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003034 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3035 } else {
3036 // Pipe is full and we are waiting for the app to finish process some events
3037 // before sending more events to it.
3038#if DEBUG_DISPATCH_CYCLE
3039 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003040 "waiting for the application to catch up",
3041 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003042#endif
Michael Wrightd02c5b62014-02-10 15:10:22 -08003043 }
3044 } else {
3045 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003046 "status=%d",
3047 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003048 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3049 }
3050 return;
3051 }
3052
3053 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003054 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
3055 connection->outboundQueue.end(),
3056 dispatchEntry));
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003057 traceOutboundQueueLength(connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003058 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003059 if (connection->responsive) {
3060 mAnrTracker.insert(dispatchEntry->timeoutTime,
3061 connection->inputChannel->getConnectionToken());
3062 }
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003063 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003064 }
3065}
3066
chaviw09c8d2d2020-08-24 15:48:26 -07003067std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
3068 size_t size;
3069 switch (event.type) {
3070 case VerifiedInputEvent::Type::KEY: {
3071 size = sizeof(VerifiedKeyEvent);
3072 break;
3073 }
3074 case VerifiedInputEvent::Type::MOTION: {
3075 size = sizeof(VerifiedMotionEvent);
3076 break;
3077 }
3078 }
3079 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
3080 return mHmacKeyManager.sign(start, size);
3081}
3082
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003083const std::array<uint8_t, 32> InputDispatcher::getSignature(
3084 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
3085 int32_t actionMasked = dispatchEntry.resolvedAction & AMOTION_EVENT_ACTION_MASK;
3086 if ((actionMasked == AMOTION_EVENT_ACTION_UP) || (actionMasked == AMOTION_EVENT_ACTION_DOWN)) {
3087 // Only sign events up and down events as the purely move events
3088 // are tied to their up/down counterparts so signing would be redundant.
3089 VerifiedMotionEvent verifiedEvent = verifiedMotionEventFromMotionEntry(motionEntry);
3090 verifiedEvent.actionMasked = actionMasked;
3091 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
chaviw09c8d2d2020-08-24 15:48:26 -07003092 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003093 }
3094 return INVALID_HMAC;
3095}
3096
3097const std::array<uint8_t, 32> InputDispatcher::getSignature(
3098 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
3099 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
3100 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
3101 verifiedEvent.action = dispatchEntry.resolvedAction;
chaviw09c8d2d2020-08-24 15:48:26 -07003102 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003103}
3104
Michael Wrightd02c5b62014-02-10 15:10:22 -08003105void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003106 const sp<Connection>& connection, uint32_t seq,
3107 bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003108#if DEBUG_DISPATCH_CYCLE
3109 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003110 connection->getInputChannelName().c_str(), seq, toString(handled));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003111#endif
3112
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003113 if (connection->status == Connection::STATUS_BROKEN ||
3114 connection->status == Connection::STATUS_ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003115 return;
3116 }
3117
3118 // Notify other system components and prepare to start the next dispatch cycle.
3119 onDispatchCycleFinishedLocked(currentTime, connection, seq, handled);
3120}
3121
3122void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003123 const sp<Connection>& connection,
3124 bool notify) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003125#if DEBUG_DISPATCH_CYCLE
3126 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003127 connection->getInputChannelName().c_str(), toString(notify));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003128#endif
3129
3130 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003131 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003132 traceOutboundQueueLength(connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003133 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003134 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003135
3136 // The connection appears to be unrecoverably broken.
3137 // Ignore already broken or zombie connections.
3138 if (connection->status == Connection::STATUS_NORMAL) {
3139 connection->status = Connection::STATUS_BROKEN;
3140
3141 if (notify) {
3142 // Notify other system components.
3143 onDispatchCycleBrokenLocked(currentTime, connection);
3144 }
3145 }
3146}
3147
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003148void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
3149 while (!queue.empty()) {
3150 DispatchEntry* dispatchEntry = queue.front();
3151 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003152 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003153 }
3154}
3155
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003156void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003157 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003158 decrementPendingForegroundDispatches(*(dispatchEntry->eventEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003159 }
3160 delete dispatchEntry;
3161}
3162
3163int InputDispatcher::handleReceiveCallback(int fd, int events, void* data) {
3164 InputDispatcher* d = static_cast<InputDispatcher*>(data);
3165
3166 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003167 std::scoped_lock _l(d->mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003168
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003169 if (d->mConnectionsByFd.find(fd) == d->mConnectionsByFd.end()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003170 ALOGE("Received spurious receive callback for unknown input channel. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003171 "fd=%d, events=0x%x",
3172 fd, events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003173 return 0; // remove the callback
3174 }
3175
3176 bool notify;
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003177 sp<Connection> connection = d->mConnectionsByFd[fd];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003178 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
3179 if (!(events & ALOOPER_EVENT_INPUT)) {
3180 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003181 "events=0x%x",
3182 connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003183 return 1;
3184 }
3185
3186 nsecs_t currentTime = now();
3187 bool gotOne = false;
3188 status_t status;
3189 for (;;) {
3190 uint32_t seq;
3191 bool handled;
3192 status = connection->inputPublisher.receiveFinishedSignal(&seq, &handled);
3193 if (status) {
3194 break;
3195 }
3196 d->finishDispatchCycleLocked(currentTime, connection, seq, handled);
3197 gotOne = true;
3198 }
3199 if (gotOne) {
3200 d->runCommandsLockedInterruptible();
3201 if (status == WOULD_BLOCK) {
3202 return 1;
3203 }
3204 }
3205
3206 notify = status != DEAD_OBJECT || !connection->monitor;
3207 if (notify) {
3208 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003209 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003210 }
3211 } else {
3212 // Monitor channels are never explicitly unregistered.
3213 // We do it automatically when the remote endpoint is closed so don't warn
3214 // about them.
arthurhungd352cb32020-04-28 17:09:28 +08003215 const bool stillHaveWindowHandle =
3216 d->getWindowHandleLocked(connection->inputChannel->getConnectionToken()) !=
3217 nullptr;
3218 notify = !connection->monitor && stillHaveWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003219 if (notify) {
3220 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003221 "events=0x%x",
3222 connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003223 }
3224 }
3225
Garfield Tan15601662020-09-22 15:32:38 -07003226 // Remove the channel.
3227 d->removeInputChannelLocked(connection->inputChannel->getConnectionToken(), notify);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003228 return 0; // remove the callback
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003229 } // release lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08003230}
3231
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003232void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08003233 const CancelationOptions& options) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +00003234 for (const auto& [fd, connection] : mConnectionsByFd) {
3235 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003236 }
3237}
3238
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003239void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003240 const CancelationOptions& options) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003241 synthesizeCancelationEventsForMonitorsLocked(options, mGlobalMonitorsByDisplay);
3242 synthesizeCancelationEventsForMonitorsLocked(options, mGestureMonitorsByDisplay);
3243}
3244
3245void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
3246 const CancelationOptions& options,
3247 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
3248 for (const auto& it : monitorsByDisplay) {
3249 const std::vector<Monitor>& monitors = it.second;
3250 for (const Monitor& monitor : monitors) {
3251 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003252 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003253 }
3254}
3255
Michael Wrightd02c5b62014-02-10 15:10:22 -08003256void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003257 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07003258 sp<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003259 if (connection == nullptr) {
3260 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003261 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003262
3263 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003264}
3265
3266void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
3267 const sp<Connection>& connection, const CancelationOptions& options) {
3268 if (connection->status == Connection::STATUS_BROKEN) {
3269 return;
3270 }
3271
3272 nsecs_t currentTime = now();
3273
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003274 std::vector<std::unique_ptr<EventEntry>> cancelationEvents =
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07003275 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003276
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003277 if (cancelationEvents.empty()) {
3278 return;
3279 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003280#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003281 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
3282 "with reality: %s, mode=%d.",
3283 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
3284 options.mode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003285#endif
Svet Ganov5d3bc372020-01-26 23:11:07 -08003286
3287 InputTarget target;
3288 sp<InputWindowHandle> windowHandle =
3289 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3290 if (windowHandle != nullptr) {
3291 const InputWindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003292 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003293 target.globalScaleFactor = windowInfo->globalScaleFactor;
3294 }
3295 target.inputChannel = connection->inputChannel;
3296 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3297
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003298 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003299 std::unique_ptr<EventEntry> cancelationEventEntry = std::move(cancelationEvents[i]);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003300 switch (cancelationEventEntry->type) {
3301 case EventEntry::Type::KEY: {
3302 logOutboundKeyDetails("cancel - ",
3303 static_cast<const KeyEntry&>(*cancelationEventEntry));
3304 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003305 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003306 case EventEntry::Type::MOTION: {
3307 logOutboundMotionDetails("cancel - ",
3308 static_cast<const MotionEntry&>(*cancelationEventEntry));
3309 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003310 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003311 case EventEntry::Type::FOCUS:
3312 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3313 LOG_ALWAYS_FATAL("Canceling %s events is not supported",
Chris Yef59a2f42020-10-16 12:55:26 -07003314 NamedEnum::string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003315 break;
3316 }
3317 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003318 case EventEntry::Type::DEVICE_RESET:
3319 case EventEntry::Type::SENSOR: {
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003320 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Chris Yef59a2f42020-10-16 12:55:26 -07003321 NamedEnum::string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003322 break;
3323 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003324 }
3325
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003326 enqueueDispatchEntryLocked(connection, std::move(cancelationEventEntry), target,
3327 InputTarget::FLAG_DISPATCH_AS_IS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003328 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003329
3330 startDispatchCycleLocked(currentTime, connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003331}
3332
Svet Ganov5d3bc372020-01-26 23:11:07 -08003333void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
3334 const sp<Connection>& connection) {
3335 if (connection->status == Connection::STATUS_BROKEN) {
3336 return;
3337 }
3338
3339 nsecs_t currentTime = now();
3340
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003341 std::vector<std::unique_ptr<EventEntry>> downEvents =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003342 connection->inputState.synthesizePointerDownEvents(currentTime);
3343
3344 if (downEvents.empty()) {
3345 return;
3346 }
3347
3348#if DEBUG_OUTBOUND_EVENT_DETAILS
3349 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
3350 connection->getInputChannelName().c_str(), downEvents.size());
3351#endif
3352
3353 InputTarget target;
3354 sp<InputWindowHandle> windowHandle =
3355 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3356 if (windowHandle != nullptr) {
3357 const InputWindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003358 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003359 target.globalScaleFactor = windowInfo->globalScaleFactor;
3360 }
3361 target.inputChannel = connection->inputChannel;
3362 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3363
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003364 for (std::unique_ptr<EventEntry>& downEventEntry : downEvents) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003365 switch (downEventEntry->type) {
3366 case EventEntry::Type::MOTION: {
3367 logOutboundMotionDetails("down - ",
3368 static_cast<const MotionEntry&>(*downEventEntry));
3369 break;
3370 }
3371
3372 case EventEntry::Type::KEY:
3373 case EventEntry::Type::FOCUS:
3374 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08003375 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07003376 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3377 case EventEntry::Type::SENSOR: {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003378 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Chris Yef59a2f42020-10-16 12:55:26 -07003379 NamedEnum::string(downEventEntry->type).c_str());
Svet Ganov5d3bc372020-01-26 23:11:07 -08003380 break;
3381 }
3382 }
3383
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003384 enqueueDispatchEntryLocked(connection, std::move(downEventEntry), target,
3385 InputTarget::FLAG_DISPATCH_AS_IS);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003386 }
3387
3388 startDispatchCycleLocked(currentTime, connection);
3389}
3390
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003391std::unique_ptr<MotionEntry> InputDispatcher::splitMotionEvent(
3392 const MotionEntry& originalMotionEntry, BitSet32 pointerIds) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003393 ALOG_ASSERT(pointerIds.value != 0);
3394
3395 uint32_t splitPointerIndexMap[MAX_POINTERS];
3396 PointerProperties splitPointerProperties[MAX_POINTERS];
3397 PointerCoords splitPointerCoords[MAX_POINTERS];
3398
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003399 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003400 uint32_t splitPointerCount = 0;
3401
3402 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003403 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003404 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003405 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003406 uint32_t pointerId = uint32_t(pointerProperties.id);
3407 if (pointerIds.hasBit(pointerId)) {
3408 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
3409 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
3410 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003411 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003412 splitPointerCount += 1;
3413 }
3414 }
3415
3416 if (splitPointerCount != pointerIds.count()) {
3417 // This is bad. We are missing some of the pointers that we expected to deliver.
3418 // Most likely this indicates that we received an ACTION_MOVE events that has
3419 // different pointer ids than we expected based on the previous ACTION_DOWN
3420 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
3421 // in this way.
3422 ALOGW("Dropping split motion event because the pointer count is %d but "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003423 "we expected there to be %d pointers. This probably means we received "
3424 "a broken sequence of pointer ids from the input device.",
3425 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07003426 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003427 }
3428
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003429 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003430 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003431 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
3432 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003433 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
3434 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003435 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003436 uint32_t pointerId = uint32_t(pointerProperties.id);
3437 if (pointerIds.hasBit(pointerId)) {
3438 if (pointerIds.count() == 1) {
3439 // The first/last pointer went down/up.
3440 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003441 ? AMOTION_EVENT_ACTION_DOWN
arthurhungea3f4fc2020-12-21 23:18:53 +08003442 : (originalMotionEntry.flags & AMOTION_EVENT_FLAG_CANCELED) != 0
3443 ? AMOTION_EVENT_ACTION_CANCEL
3444 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003445 } else {
3446 // A secondary pointer went down/up.
3447 uint32_t splitPointerIndex = 0;
3448 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
3449 splitPointerIndex += 1;
3450 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003451 action = maskedAction |
3452 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003453 }
3454 } else {
3455 // An unrelated pointer changed.
3456 action = AMOTION_EVENT_ACTION_MOVE;
3457 }
3458 }
3459
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003460 int32_t newId = mIdGenerator.nextId();
3461 if (ATRACE_ENABLED()) {
3462 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
3463 ") to MotionEvent(id=0x%" PRIx32 ").",
3464 originalMotionEntry.id, newId);
3465 ATRACE_NAME(message.c_str());
3466 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003467 std::unique_ptr<MotionEntry> splitMotionEntry =
3468 std::make_unique<MotionEntry>(newId, originalMotionEntry.eventTime,
3469 originalMotionEntry.deviceId, originalMotionEntry.source,
3470 originalMotionEntry.displayId,
3471 originalMotionEntry.policyFlags, action,
3472 originalMotionEntry.actionButton,
3473 originalMotionEntry.flags, originalMotionEntry.metaState,
3474 originalMotionEntry.buttonState,
3475 originalMotionEntry.classification,
3476 originalMotionEntry.edgeFlags,
3477 originalMotionEntry.xPrecision,
3478 originalMotionEntry.yPrecision,
3479 originalMotionEntry.xCursorPosition,
3480 originalMotionEntry.yCursorPosition,
3481 originalMotionEntry.downTime, splitPointerCount,
3482 splitPointerProperties, splitPointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003483
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003484 if (originalMotionEntry.injectionState) {
3485 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003486 splitMotionEntry->injectionState->refCount += 1;
3487 }
3488
3489 return splitMotionEntry;
3490}
3491
3492void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
3493#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003494 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003495#endif
3496
3497 bool needWake;
3498 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003499 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003500
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003501 std::unique_ptr<ConfigurationChangedEntry> newEntry =
3502 std::make_unique<ConfigurationChangedEntry>(args->id, args->eventTime);
3503 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003504 } // release lock
3505
3506 if (needWake) {
3507 mLooper->wake();
3508 }
3509}
3510
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003511/**
3512 * If one of the meta shortcuts is detected, process them here:
3513 * Meta + Backspace -> generate BACK
3514 * Meta + Enter -> generate HOME
3515 * This will potentially overwrite keyCode and metaState.
3516 */
3517void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003518 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003519 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
3520 int32_t newKeyCode = AKEYCODE_UNKNOWN;
3521 if (keyCode == AKEYCODE_DEL) {
3522 newKeyCode = AKEYCODE_BACK;
3523 } else if (keyCode == AKEYCODE_ENTER) {
3524 newKeyCode = AKEYCODE_HOME;
3525 }
3526 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003527 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003528 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003529 mReplacedKeys[replacement] = newKeyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003530 keyCode = newKeyCode;
3531 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3532 }
3533 } else if (action == AKEY_EVENT_ACTION_UP) {
3534 // In order to maintain a consistent stream of up and down events, check to see if the key
3535 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
3536 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003537 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003538 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003539 auto replacementIt = mReplacedKeys.find(replacement);
3540 if (replacementIt != mReplacedKeys.end()) {
3541 keyCode = replacementIt->second;
3542 mReplacedKeys.erase(replacementIt);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003543 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3544 }
3545 }
3546}
3547
Michael Wrightd02c5b62014-02-10 15:10:22 -08003548void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
3549#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003550 ALOGD("notifyKey - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
3551 "policyFlags=0x%x, action=0x%x, "
3552 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
3553 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
3554 args->action, args->flags, args->keyCode, args->scanCode, args->metaState,
3555 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003556#endif
3557 if (!validateKeyEvent(args->action)) {
3558 return;
3559 }
3560
3561 uint32_t policyFlags = args->policyFlags;
3562 int32_t flags = args->flags;
3563 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07003564 // InputDispatcher tracks and generates key repeats on behalf of
3565 // whatever notifies it, so repeatCount should always be set to 0
3566 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003567 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
3568 policyFlags |= POLICY_FLAG_VIRTUAL;
3569 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
3570 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003571 if (policyFlags & POLICY_FLAG_FUNCTION) {
3572 metaState |= AMETA_FUNCTION_ON;
3573 }
3574
3575 policyFlags |= POLICY_FLAG_TRUSTED;
3576
Michael Wright78f24442014-08-06 15:55:28 -07003577 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003578 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07003579
Michael Wrightd02c5b62014-02-10 15:10:22 -08003580 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003581 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08003582 args->action, flags, keyCode, args->scanCode, metaState, repeatCount,
3583 args->downTime, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003584
Michael Wright2b3c3302018-03-02 17:19:13 +00003585 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003586 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003587 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3588 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003589 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003590 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003591
Michael Wrightd02c5b62014-02-10 15:10:22 -08003592 bool needWake;
3593 { // acquire lock
3594 mLock.lock();
3595
3596 if (shouldSendKeyToInputFilterLocked(args)) {
3597 mLock.unlock();
3598
3599 policyFlags |= POLICY_FLAG_FILTERED;
3600 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3601 return; // event was consumed by the filter
3602 }
3603
3604 mLock.lock();
3605 }
3606
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003607 std::unique_ptr<KeyEntry> newEntry =
3608 std::make_unique<KeyEntry>(args->id, args->eventTime, args->deviceId, args->source,
3609 args->displayId, policyFlags, args->action, flags,
3610 keyCode, args->scanCode, metaState, repeatCount,
3611 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003612
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003613 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003614 mLock.unlock();
3615 } // release lock
3616
3617 if (needWake) {
3618 mLooper->wake();
3619 }
3620}
3621
3622bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
3623 return mInputFilterEnabled;
3624}
3625
3626void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
3627#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003628 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
3629 "displayId=%" PRId32 ", policyFlags=0x%x, "
Garfield Tan00f511d2019-06-12 16:55:40 -07003630 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
3631 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
Garfield Tanab0ab9c2019-07-10 18:58:28 -07003632 "yCursorPosition=%f, downTime=%" PRId64,
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003633 args->id, args->eventTime, args->deviceId, args->source, args->displayId,
3634 args->policyFlags, args->action, args->actionButton, args->flags, args->metaState,
3635 args->buttonState, args->edgeFlags, args->xPrecision, args->yPrecision,
3636 args->xCursorPosition, args->yCursorPosition, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003637 for (uint32_t i = 0; i < args->pointerCount; i++) {
3638 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003639 "x=%f, y=%f, pressure=%f, size=%f, "
3640 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
3641 "orientation=%f",
3642 i, args->pointerProperties[i].id, args->pointerProperties[i].toolType,
3643 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
3644 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
3645 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
3646 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
3647 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
3648 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
3649 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
3650 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
3651 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003652 }
3653#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003654 if (!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
3655 args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003656 return;
3657 }
3658
3659 uint32_t policyFlags = args->policyFlags;
3660 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003661
3662 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08003663 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003664 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3665 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003666 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003667 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003668
3669 bool needWake;
3670 { // acquire lock
3671 mLock.lock();
3672
3673 if (shouldSendMotionToInputFilterLocked(args)) {
3674 mLock.unlock();
3675
3676 MotionEvent event;
chaviw9eaa22c2020-07-01 16:21:27 -07003677 ui::Transform transform;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003678 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
3679 args->action, args->actionButton, args->flags, args->edgeFlags,
chaviw9eaa22c2020-07-01 16:21:27 -07003680 args->metaState, args->buttonState, args->classification, transform,
3681 args->xPrecision, args->yPrecision, args->xCursorPosition,
3682 args->yCursorPosition, args->downTime, args->eventTime,
3683 args->pointerCount, args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003684
3685 policyFlags |= POLICY_FLAG_FILTERED;
3686 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3687 return; // event was consumed by the filter
3688 }
3689
3690 mLock.lock();
3691 }
3692
3693 // Just enqueue a new motion event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003694 std::unique_ptr<MotionEntry> newEntry =
3695 std::make_unique<MotionEntry>(args->id, args->eventTime, args->deviceId,
3696 args->source, args->displayId, policyFlags,
3697 args->action, args->actionButton, args->flags,
3698 args->metaState, args->buttonState,
3699 args->classification, args->edgeFlags,
3700 args->xPrecision, args->yPrecision,
3701 args->xCursorPosition, args->yCursorPosition,
3702 args->downTime, args->pointerCount,
3703 args->pointerProperties, args->pointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003704
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003705 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003706 mLock.unlock();
3707 } // release lock
3708
3709 if (needWake) {
3710 mLooper->wake();
3711 }
3712}
3713
Chris Yef59a2f42020-10-16 12:55:26 -07003714void InputDispatcher::notifySensor(const NotifySensorArgs* args) {
3715#if DEBUG_INBOUND_EVENT_DETAILS
3716 ALOGD("notifySensor - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
3717 " sensorType=%s",
3718 args->id, args->eventTime, args->deviceId, args->source,
3719 NamedEnum::string(args->sensorType).c_str());
3720#endif
3721
3722 bool needWake;
3723 { // acquire lock
3724 mLock.lock();
3725
3726 // Just enqueue a new sensor event.
3727 std::unique_ptr<SensorEntry> newEntry =
3728 std::make_unique<SensorEntry>(args->id, args->eventTime, args->deviceId,
3729 args->source, 0 /* policyFlags*/, args->hwTimestamp,
3730 args->sensorType, args->accuracy,
3731 args->accuracyChanged, args->values);
3732
3733 needWake = enqueueInboundEventLocked(std::move(newEntry));
3734 mLock.unlock();
3735 } // release lock
3736
3737 if (needWake) {
3738 mLooper->wake();
3739 }
3740}
3741
Michael Wrightd02c5b62014-02-10 15:10:22 -08003742bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08003743 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003744}
3745
3746void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
3747#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003748 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003749 "switchMask=0x%08x",
3750 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003751#endif
3752
3753 uint32_t policyFlags = args->policyFlags;
3754 policyFlags |= POLICY_FLAG_TRUSTED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003755 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003756}
3757
3758void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
3759#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003760 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
3761 args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003762#endif
3763
3764 bool needWake;
3765 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003766 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003767
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003768 std::unique_ptr<DeviceResetEntry> newEntry =
3769 std::make_unique<DeviceResetEntry>(args->id, args->eventTime, args->deviceId);
3770 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003771 } // release lock
3772
3773 if (needWake) {
3774 mLooper->wake();
3775 }
3776}
3777
Prabir Pradhan7e186182020-11-10 13:56:45 -08003778void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs* args) {
3779#if DEBUG_INBOUND_EVENT_DETAILS
3780 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args->eventTime,
3781 args->enabled ? "true" : "false");
3782#endif
3783
Prabir Pradhan99987712020-11-10 18:43:05 -08003784 bool needWake;
3785 { // acquire lock
3786 std::scoped_lock _l(mLock);
3787 auto entry = std::make_unique<PointerCaptureChangedEntry>(args->id, args->eventTime,
3788 args->enabled);
3789 needWake = enqueueInboundEventLocked(std::move(entry));
3790 } // release lock
3791
3792 if (needWake) {
3793 mLooper->wake();
3794 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08003795}
3796
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003797InputEventInjectionResult InputDispatcher::injectInputEvent(
3798 const InputEvent* event, int32_t injectorPid, int32_t injectorUid,
3799 InputEventInjectionSync syncMode, std::chrono::milliseconds timeout, uint32_t policyFlags) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003800#if DEBUG_INBOUND_EVENT_DETAILS
3801 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003802 "syncMode=%d, timeout=%lld, policyFlags=0x%08x",
3803 event->getType(), injectorPid, injectorUid, syncMode, timeout.count(), policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003804#endif
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003805 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003806
3807 policyFlags |= POLICY_FLAG_INJECTED;
3808 if (hasInjectionPermission(injectorPid, injectorUid)) {
3809 policyFlags |= POLICY_FLAG_TRUSTED;
3810 }
3811
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003812 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003813 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003814 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003815 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
3816 int32_t action = incomingKey.getAction();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003817 if (!validateKeyEvent(action)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003818 return InputEventInjectionResult::FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003819 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003820
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003821 int32_t flags = incomingKey.getFlags();
3822 int32_t keyCode = incomingKey.getKeyCode();
3823 int32_t metaState = incomingKey.getMetaState();
3824 accelerateMetaShortcuts(VIRTUAL_KEYBOARD_ID, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003825 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003826 KeyEvent keyEvent;
Garfield Tan4cc839f2020-01-24 11:26:14 -08003827 keyEvent.initialize(incomingKey.getId(), VIRTUAL_KEYBOARD_ID, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003828 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
3829 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
3830 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003831
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003832 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
3833 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00003834 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003835
3836 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
3837 android::base::Timer t;
3838 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
3839 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3840 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
3841 std::to_string(t.duration().count()).c_str());
3842 }
3843 }
3844
3845 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003846 std::unique_ptr<KeyEntry> injectedEntry =
3847 std::make_unique<KeyEntry>(incomingKey.getId(), incomingKey.getEventTime(),
3848 VIRTUAL_KEYBOARD_ID, incomingKey.getSource(),
3849 incomingKey.getDisplayId(), policyFlags, action,
3850 flags, keyCode, incomingKey.getScanCode(), metaState,
3851 incomingKey.getRepeatCount(),
3852 incomingKey.getDownTime());
3853 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003854 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003855 }
3856
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003857 case AINPUT_EVENT_TYPE_MOTION: {
3858 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
3859 int32_t action = motionEvent->getAction();
3860 size_t pointerCount = motionEvent->getPointerCount();
3861 const PointerProperties* pointerProperties = motionEvent->getPointerProperties();
3862 int32_t actionButton = motionEvent->getActionButton();
3863 int32_t displayId = motionEvent->getDisplayId();
3864 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003865 return InputEventInjectionResult::FAILED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003866 }
3867
3868 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
3869 nsecs_t eventTime = motionEvent->getEventTime();
3870 android::base::Timer t;
3871 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
3872 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3873 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
3874 std::to_string(t.duration().count()).c_str());
3875 }
3876 }
3877
3878 mLock.lock();
3879 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
3880 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003881 std::unique_ptr<MotionEntry> injectedEntry =
3882 std::make_unique<MotionEntry>(motionEvent->getId(), *sampleEventTimes,
3883 VIRTUAL_KEYBOARD_ID, motionEvent->getSource(),
3884 motionEvent->getDisplayId(), policyFlags, action,
3885 actionButton, motionEvent->getFlags(),
3886 motionEvent->getMetaState(),
3887 motionEvent->getButtonState(),
3888 motionEvent->getClassification(),
3889 motionEvent->getEdgeFlags(),
3890 motionEvent->getXPrecision(),
3891 motionEvent->getYPrecision(),
3892 motionEvent->getRawXCursorPosition(),
3893 motionEvent->getRawYCursorPosition(),
3894 motionEvent->getDownTime(),
3895 uint32_t(pointerCount), pointerProperties,
3896 samplePointerCoords, motionEvent->getXOffset(),
3897 motionEvent->getYOffset());
3898 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003899 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
3900 sampleEventTimes += 1;
3901 samplePointerCoords += pointerCount;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003902 std::unique_ptr<MotionEntry> nextInjectedEntry =
3903 std::make_unique<MotionEntry>(motionEvent->getId(), *sampleEventTimes,
3904 VIRTUAL_KEYBOARD_ID, motionEvent->getSource(),
3905 motionEvent->getDisplayId(), policyFlags,
3906 action, actionButton, motionEvent->getFlags(),
3907 motionEvent->getMetaState(),
3908 motionEvent->getButtonState(),
3909 motionEvent->getClassification(),
3910 motionEvent->getEdgeFlags(),
3911 motionEvent->getXPrecision(),
3912 motionEvent->getYPrecision(),
3913 motionEvent->getRawXCursorPosition(),
3914 motionEvent->getRawYCursorPosition(),
3915 motionEvent->getDownTime(),
3916 uint32_t(pointerCount), pointerProperties,
3917 samplePointerCoords,
3918 motionEvent->getXOffset(),
3919 motionEvent->getYOffset());
3920 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003921 }
3922 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003923 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003924
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003925 default:
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08003926 ALOGW("Cannot inject %s events", inputEventTypeToString(event->getType()));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003927 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003928 }
3929
3930 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003931 if (syncMode == InputEventInjectionSync::NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003932 injectionState->injectionIsAsync = true;
3933 }
3934
3935 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003936 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003937
3938 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003939 while (!injectedEntries.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003940 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003941 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003942 }
3943
3944 mLock.unlock();
3945
3946 if (needWake) {
3947 mLooper->wake();
3948 }
3949
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003950 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003951 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003952 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003953
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003954 if (syncMode == InputEventInjectionSync::NONE) {
3955 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003956 } else {
3957 for (;;) {
3958 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003959 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003960 break;
3961 }
3962
3963 nsecs_t remainingTimeout = endTime - now();
3964 if (remainingTimeout <= 0) {
3965#if DEBUG_INJECTION
3966 ALOGD("injectInputEvent - Timed out waiting for injection result "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003967 "to become available.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003968#endif
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003969 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003970 break;
3971 }
3972
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003973 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003974 }
3975
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003976 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
3977 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003978 while (injectionState->pendingForegroundDispatches != 0) {
3979#if DEBUG_INJECTION
3980 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003981 injectionState->pendingForegroundDispatches);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003982#endif
3983 nsecs_t remainingTimeout = endTime - now();
3984 if (remainingTimeout <= 0) {
3985#if DEBUG_INJECTION
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003986 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
3987 "dispatches to finish.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003988#endif
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003989 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003990 break;
3991 }
3992
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003993 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003994 }
3995 }
3996 }
3997
3998 injectionState->release();
3999 } // release lock
4000
4001#if DEBUG_INJECTION
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004002 ALOGD("injectInputEvent - Finished with result %d. injectorPid=%d, injectorUid=%d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004003 injectionResult, injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004004#endif
4005
4006 return injectionResult;
4007}
4008
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004009std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05004010 std::array<uint8_t, 32> calculatedHmac;
4011 std::unique_ptr<VerifiedInputEvent> result;
4012 switch (event.getType()) {
4013 case AINPUT_EVENT_TYPE_KEY: {
4014 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
4015 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
4016 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004017 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05004018 break;
4019 }
4020 case AINPUT_EVENT_TYPE_MOTION: {
4021 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
4022 VerifiedMotionEvent verifiedMotionEvent =
4023 verifiedMotionEventFromMotionEvent(motionEvent);
4024 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004025 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05004026 break;
4027 }
4028 default: {
4029 ALOGE("Cannot verify events of type %" PRId32, event.getType());
4030 return nullptr;
4031 }
4032 }
4033 if (calculatedHmac == INVALID_HMAC) {
4034 return nullptr;
4035 }
4036 if (calculatedHmac != event.getHmac()) {
4037 return nullptr;
4038 }
4039 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004040}
4041
Michael Wrightd02c5b62014-02-10 15:10:22 -08004042bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004043 return injectorUid == 0 ||
4044 mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004045}
4046
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004047void InputDispatcher::setInjectionResult(EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004048 InputEventInjectionResult injectionResult) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004049 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004050 if (injectionState) {
4051#if DEBUG_INJECTION
4052 ALOGD("Setting input event injection result to %d. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004053 "injectorPid=%d, injectorUid=%d",
4054 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004055#endif
4056
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004057 if (injectionState->injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004058 // Log the outcome since the injector did not wait for the injection result.
4059 switch (injectionResult) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004060 case InputEventInjectionResult::SUCCEEDED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004061 ALOGV("Asynchronous input event injection succeeded.");
4062 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004063 case InputEventInjectionResult::FAILED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004064 ALOGW("Asynchronous input event injection failed.");
4065 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004066 case InputEventInjectionResult::PERMISSION_DENIED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004067 ALOGW("Asynchronous input event injection permission denied.");
4068 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004069 case InputEventInjectionResult::TIMED_OUT:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004070 ALOGW("Asynchronous input event injection timed out.");
4071 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004072 case InputEventInjectionResult::PENDING:
4073 ALOGE("Setting result to 'PENDING' for asynchronous injection");
4074 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004075 }
4076 }
4077
4078 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004079 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004080 }
4081}
4082
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004083void InputDispatcher::incrementPendingForegroundDispatches(EventEntry& entry) {
4084 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004085 if (injectionState) {
4086 injectionState->pendingForegroundDispatches += 1;
4087 }
4088}
4089
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004090void InputDispatcher::decrementPendingForegroundDispatches(EventEntry& entry) {
4091 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004092 if (injectionState) {
4093 injectionState->pendingForegroundDispatches -= 1;
4094
4095 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004096 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004097 }
4098 }
4099}
4100
Vishnu Nairad321cd2020-08-20 16:40:21 -07004101const std::vector<sp<InputWindowHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004102 int32_t displayId) const {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004103 static const std::vector<sp<InputWindowHandle>> EMPTY_WINDOW_HANDLES;
4104 auto it = mWindowHandlesByDisplay.find(displayId);
4105 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08004106}
4107
Michael Wrightd02c5b62014-02-10 15:10:22 -08004108sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08004109 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08004110 if (windowHandleToken == nullptr) {
4111 return nullptr;
4112 }
4113
Arthur Hungb92218b2018-08-14 12:00:21 +08004114 for (auto& it : mWindowHandlesByDisplay) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004115 const std::vector<sp<InputWindowHandle>>& windowHandles = it.second;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004116 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004117 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004118 return windowHandle;
4119 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004120 }
4121 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004122 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004123}
4124
Vishnu Nairad321cd2020-08-20 16:40:21 -07004125sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(const sp<IBinder>& windowHandleToken,
4126 int displayId) const {
4127 if (windowHandleToken == nullptr) {
4128 return nullptr;
4129 }
4130
4131 for (const sp<InputWindowHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
4132 if (windowHandle->getToken() == windowHandleToken) {
4133 return windowHandle;
4134 }
4135 }
4136 return nullptr;
4137}
4138
4139sp<InputWindowHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
4140 sp<IBinder> focusedToken = getValueByKey(mFocusedWindowTokenByDisplay, displayId);
4141 return getWindowHandleLocked(focusedToken, displayId);
4142}
4143
Mady Mellor017bcd12020-06-23 19:12:00 +00004144bool InputDispatcher::hasWindowHandleLocked(const sp<InputWindowHandle>& windowHandle) const {
4145 for (auto& it : mWindowHandlesByDisplay) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004146 const std::vector<sp<InputWindowHandle>>& windowHandles = it.second;
Mady Mellor017bcd12020-06-23 19:12:00 +00004147 for (const sp<InputWindowHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08004148 if (handle->getId() == windowHandle->getId() &&
4149 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004150 if (windowHandle->getInfo()->displayId != it.first) {
4151 ALOGE("Found window %s in display %" PRId32
4152 ", but it should belong to display %" PRId32,
4153 windowHandle->getName().c_str(), it.first,
4154 windowHandle->getInfo()->displayId);
4155 }
4156 return true;
Arthur Hungb92218b2018-08-14 12:00:21 +08004157 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004158 }
4159 }
4160 return false;
4161}
4162
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004163bool InputDispatcher::hasResponsiveConnectionLocked(InputWindowHandle& windowHandle) const {
4164 sp<Connection> connection = getConnectionLocked(windowHandle.getToken());
4165 const bool noInputChannel =
4166 windowHandle.getInfo()->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
4167 if (connection != nullptr && noInputChannel) {
4168 ALOGW("%s has feature NO_INPUT_CHANNEL, but it matched to connection %s",
4169 windowHandle.getName().c_str(), connection->inputChannel->getName().c_str());
4170 return false;
4171 }
4172
4173 if (connection == nullptr) {
4174 if (!noInputChannel) {
4175 ALOGI("Could not find connection for %s", windowHandle.getName().c_str());
4176 }
4177 return false;
4178 }
4179 if (!connection->responsive) {
4180 ALOGW("Window %s is not responsive", windowHandle.getName().c_str());
4181 return false;
4182 }
4183 return true;
4184}
4185
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004186std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
4187 const sp<IBinder>& token) const {
Robert Carr5c8a0262018-10-03 16:30:44 -07004188 size_t count = mInputChannelsByToken.count(token);
4189 if (count == 0) {
4190 return nullptr;
4191 }
4192 return mInputChannelsByToken.at(token);
4193}
4194
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004195void InputDispatcher::updateWindowHandlesForDisplayLocked(
4196 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
4197 if (inputWindowHandles.empty()) {
4198 // Remove all handles on a display if there are no windows left.
4199 mWindowHandlesByDisplay.erase(displayId);
4200 return;
4201 }
4202
4203 // Since we compare the pointer of input window handles across window updates, we need
4204 // to make sure the handle object for the same window stays unchanged across updates.
4205 const std::vector<sp<InputWindowHandle>>& oldHandles = getWindowHandlesLocked(displayId);
chaviwaf87b3e2019-10-01 16:59:28 -07004206 std::unordered_map<int32_t /*id*/, sp<InputWindowHandle>> oldHandlesById;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004207 for (const sp<InputWindowHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07004208 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004209 }
4210
4211 std::vector<sp<InputWindowHandle>> newHandles;
4212 for (const sp<InputWindowHandle>& handle : inputWindowHandles) {
4213 if (!handle->updateInfo()) {
4214 // handle no longer valid
4215 continue;
4216 }
4217
4218 const InputWindowInfo* info = handle->getInfo();
4219 if ((getInputChannelLocked(handle->getToken()) == nullptr &&
4220 info->portalToDisplayId == ADISPLAY_ID_NONE)) {
4221 const bool noInputChannel =
Michael Wright44753b12020-07-08 13:48:11 +01004222 info->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
4223 const bool canReceiveInput = !info->flags.test(InputWindowInfo::Flag::NOT_TOUCHABLE) ||
4224 !info->flags.test(InputWindowInfo::Flag::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004225 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07004226 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004227 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07004228 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004229 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004230 }
4231
4232 if (info->displayId != displayId) {
4233 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
4234 handle->getName().c_str(), displayId, info->displayId);
4235 continue;
4236 }
4237
Robert Carredd13602020-04-13 17:24:34 -07004238 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
4239 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviwaf87b3e2019-10-01 16:59:28 -07004240 const sp<InputWindowHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004241 oldHandle->updateFrom(handle);
4242 newHandles.push_back(oldHandle);
4243 } else {
4244 newHandles.push_back(handle);
4245 }
4246 }
4247
4248 // Insert or replace
4249 mWindowHandlesByDisplay[displayId] = newHandles;
4250}
4251
Arthur Hung72d8dc32020-03-28 00:48:39 +00004252void InputDispatcher::setInputWindows(
4253 const std::unordered_map<int32_t, std::vector<sp<InputWindowHandle>>>& handlesPerDisplay) {
4254 { // acquire lock
4255 std::scoped_lock _l(mLock);
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004256 for (const auto& [displayId, handles] : handlesPerDisplay) {
4257 setInputWindowsLocked(handles, displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004258 }
4259 }
4260 // Wake up poll loop since it may need to make new input dispatching choices.
4261 mLooper->wake();
4262}
4263
Arthur Hungb92218b2018-08-14 12:00:21 +08004264/**
4265 * Called from InputManagerService, update window handle list by displayId that can receive input.
4266 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
4267 * If set an empty list, remove all handles from the specific display.
4268 * For focused handle, check if need to change and send a cancel event to previous one.
4269 * For removed handle, check if need to send a cancel event if already in touch.
4270 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00004271void InputDispatcher::setInputWindowsLocked(
4272 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004273 if (DEBUG_FOCUS) {
4274 std::string windowList;
4275 for (const sp<InputWindowHandle>& iwh : inputWindowHandles) {
4276 windowList += iwh->getName() + " ";
4277 }
4278 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
4279 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004280
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004281 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
4282 for (const sp<InputWindowHandle>& window : inputWindowHandles) {
4283 const bool noInputWindow =
4284 window->getInfo()->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
4285 if (noInputWindow && window->getToken() != nullptr) {
4286 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
4287 window->getName().c_str());
4288 window->releaseChannel();
4289 }
4290 }
4291
Arthur Hung72d8dc32020-03-28 00:48:39 +00004292 // Copy old handles for release if they are no longer present.
4293 const std::vector<sp<InputWindowHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004294
Arthur Hung72d8dc32020-03-28 00:48:39 +00004295 updateWindowHandlesForDisplayLocked(inputWindowHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004296
Vishnu Nair958da932020-08-21 17:12:37 -07004297 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
4298 if (mLastHoverWindowHandle &&
4299 std::find(windowHandles.begin(), windowHandles.end(), mLastHoverWindowHandle) ==
4300 windowHandles.end()) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004301 mLastHoverWindowHandle = nullptr;
4302 }
4303
Vishnu Nair958da932020-08-21 17:12:37 -07004304 sp<IBinder> focusedToken = getValueByKey(mFocusedWindowTokenByDisplay, displayId);
4305 if (focusedToken) {
4306 FocusResult result = checkTokenFocusableLocked(focusedToken, displayId);
4307 if (result != FocusResult::OK) {
4308 onFocusChangedLocked(focusedToken, nullptr, displayId, typeToString(result));
4309 }
4310 }
4311
4312 std::optional<FocusRequest> focusRequest =
4313 getOptionalValueByKey(mPendingFocusRequests, displayId);
4314 if (focusRequest) {
4315 // If the window from the pending request is now visible, provide it focus.
4316 FocusResult result = handleFocusRequestLocked(*focusRequest);
4317 if (result != FocusResult::NOT_VISIBLE) {
4318 // Drop the request if we were able to change the focus or we cannot change
4319 // it for another reason.
4320 mPendingFocusRequests.erase(displayId);
4321 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004322 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004323
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004324 std::unordered_map<int32_t, TouchState>::iterator stateIt =
4325 mTouchStatesByDisplay.find(displayId);
4326 if (stateIt != mTouchStatesByDisplay.end()) {
4327 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00004328 for (size_t i = 0; i < state.windows.size();) {
4329 TouchedWindow& touchedWindow = state.windows[i];
Mady Mellor017bcd12020-06-23 19:12:00 +00004330 if (!hasWindowHandleLocked(touchedWindow.windowHandle)) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004331 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004332 ALOGD("Touched window was removed: %s in display %" PRId32,
4333 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004334 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004335 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00004336 getInputChannelLocked(touchedWindow.windowHandle->getToken());
4337 if (touchedInputChannel != nullptr) {
4338 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4339 "touched window was removed");
4340 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004341 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004342 state.windows.erase(state.windows.begin() + i);
4343 } else {
4344 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004345 }
4346 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004347 }
Arthur Hung25e2af12020-03-26 12:58:37 +00004348
Arthur Hung72d8dc32020-03-28 00:48:39 +00004349 // Release information for windows that are no longer present.
4350 // This ensures that unused input channels are released promptly.
4351 // Otherwise, they might stick around until the window handle is destroyed
4352 // which might not happen until the next GC.
4353 for (const sp<InputWindowHandle>& oldWindowHandle : oldWindowHandles) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004354 if (!hasWindowHandleLocked(oldWindowHandle)) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004355 if (DEBUG_FOCUS) {
4356 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00004357 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004358 oldWindowHandle->releaseChannel();
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004359 // To avoid making too many calls into the compat framework, only
4360 // check for window flags when windows are going away.
4361 // TODO(b/157929241) : delete this. This is only needed temporarily
4362 // in order to gather some data about the flag usage
4363 if (oldWindowHandle->getInfo()->flags.test(InputWindowInfo::Flag::SLIPPERY)) {
4364 ALOGW("%s has FLAG_SLIPPERY. Please report this in b/157929241",
4365 oldWindowHandle->getName().c_str());
4366 if (mCompatService != nullptr) {
4367 mCompatService->reportChangeByUid(IInputConstants::BLOCK_FLAG_SLIPPERY,
4368 oldWindowHandle->getInfo()->ownerUid);
4369 }
4370 }
Arthur Hung25e2af12020-03-26 12:58:37 +00004371 }
chaviw291d88a2019-02-14 10:33:58 -08004372 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004373}
4374
4375void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07004376 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004377 if (DEBUG_FOCUS) {
4378 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
4379 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
4380 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004381 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004382 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004383
Chris Yea209fde2020-07-22 13:54:51 -07004384 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08004385 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004386
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004387 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
4388 return; // This application is already focused. No need to wake up or change anything.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004389 }
4390
Chris Yea209fde2020-07-22 13:54:51 -07004391 // Set the new application handle.
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004392 if (inputApplicationHandle != nullptr) {
4393 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
4394 } else {
4395 mFocusedApplicationHandlesByDisplay.erase(displayId);
4396 }
4397
4398 // No matter what the old focused application was, stop waiting on it because it is
4399 // no longer focused.
4400 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004401 } // release lock
4402
4403 // Wake up poll loop since it may need to make new input dispatching choices.
4404 mLooper->wake();
4405}
4406
Tiger Huang721e26f2018-07-24 22:26:19 +08004407/**
4408 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
4409 * the display not specified.
4410 *
4411 * We track any unreleased events for each window. If a window loses the ability to receive the
4412 * released event, we will send a cancel event to it. So when the focused display is changed, we
4413 * cancel all the unreleased display-unspecified events for the focused window on the old focused
4414 * display. The display-specified events won't be affected.
4415 */
4416void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004417 if (DEBUG_FOCUS) {
4418 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
4419 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004420 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004421 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08004422
4423 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004424 sp<IBinder> oldFocusedWindowToken =
4425 getValueByKey(mFocusedWindowTokenByDisplay, mFocusedDisplayId);
4426 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004427 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07004428 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08004429 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004430 CancelationOptions
4431 options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
4432 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004433 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08004434 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
4435 }
4436 }
4437 mFocusedDisplayId = displayId;
4438
Chris Ye3c2d6f52020-08-09 10:39:48 -07004439 // Find new focused window and validate
Vishnu Nairad321cd2020-08-20 16:40:21 -07004440 sp<IBinder> newFocusedWindowToken =
4441 getValueByKey(mFocusedWindowTokenByDisplay, displayId);
4442 notifyFocusChangedLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08004443
Vishnu Nairad321cd2020-08-20 16:40:21 -07004444 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08004445 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07004446 if (!mFocusedWindowTokenByDisplay.empty()) {
4447 ALOGE("But another display has a focused window\n%s",
4448 dumpFocusedWindowsLocked().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08004449 }
4450 }
4451 }
4452
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004453 if (DEBUG_FOCUS) {
4454 logDispatchStateLocked();
4455 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004456 } // release lock
4457
4458 // Wake up poll loop since it may need to make new input dispatching choices.
4459 mLooper->wake();
4460}
4461
Michael Wrightd02c5b62014-02-10 15:10:22 -08004462void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004463 if (DEBUG_FOCUS) {
4464 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
4465 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004466
4467 bool changed;
4468 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004469 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004470
4471 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
4472 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004473 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004474 }
4475
4476 if (mDispatchEnabled && !enabled) {
4477 resetAndDropEverythingLocked("dispatcher is being disabled");
4478 }
4479
4480 mDispatchEnabled = enabled;
4481 mDispatchFrozen = frozen;
4482 changed = true;
4483 } else {
4484 changed = false;
4485 }
4486
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004487 if (DEBUG_FOCUS) {
4488 logDispatchStateLocked();
4489 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004490 } // release lock
4491
4492 if (changed) {
4493 // Wake up poll loop since it may need to make new input dispatching choices.
4494 mLooper->wake();
4495 }
4496}
4497
4498void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004499 if (DEBUG_FOCUS) {
4500 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
4501 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004502
4503 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004504 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004505
4506 if (mInputFilterEnabled == enabled) {
4507 return;
4508 }
4509
4510 mInputFilterEnabled = enabled;
4511 resetAndDropEverythingLocked("input filter is being enabled or disabled");
4512 } // release lock
4513
4514 // Wake up poll loop since there might be work to do to drop everything.
4515 mLooper->wake();
4516}
4517
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08004518void InputDispatcher::setInTouchMode(bool inTouchMode) {
4519 std::scoped_lock lock(mLock);
4520 mInTouchMode = inTouchMode;
4521}
4522
Bernardo Rufinoea97d182020-08-19 14:43:14 +01004523void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
4524 if (opacity < 0 || opacity > 1) {
4525 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
4526 return;
4527 }
4528
4529 std::scoped_lock lock(mLock);
4530 mMaximumObscuringOpacityForTouch = opacity;
4531}
4532
4533void InputDispatcher::setBlockUntrustedTouchesMode(BlockUntrustedTouchesMode mode) {
4534 std::scoped_lock lock(mLock);
4535 mBlockUntrustedTouchesMode = mode;
4536}
4537
chaviwfbe5d9c2018-12-26 12:23:37 -08004538bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken) {
4539 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004540 if (DEBUG_FOCUS) {
4541 ALOGD("Trivial transfer to same window.");
4542 }
chaviwfbe5d9c2018-12-26 12:23:37 -08004543 return true;
4544 }
4545
Michael Wrightd02c5b62014-02-10 15:10:22 -08004546 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004547 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004548
chaviwfbe5d9c2018-12-26 12:23:37 -08004549 sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromToken);
4550 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toToken);
Yi Kong9b14ac62018-07-17 13:48:38 -07004551 if (fromWindowHandle == nullptr || toWindowHandle == nullptr) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004552 ALOGW("Cannot transfer focus because from or to window not found.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004553 return false;
4554 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004555 if (DEBUG_FOCUS) {
4556 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
4557 fromWindowHandle->getName().c_str(), toWindowHandle->getName().c_str());
4558 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004559 if (fromWindowHandle->getInfo()->displayId != toWindowHandle->getInfo()->displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004560 if (DEBUG_FOCUS) {
4561 ALOGD("Cannot transfer focus because windows are on different displays.");
4562 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004563 return false;
4564 }
4565
4566 bool found = false;
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004567 for (std::pair<const int32_t, TouchState>& pair : mTouchStatesByDisplay) {
4568 TouchState& state = pair.second;
Jeff Brownf086ddb2014-02-11 14:28:48 -08004569 for (size_t i = 0; i < state.windows.size(); i++) {
4570 const TouchedWindow& touchedWindow = state.windows[i];
4571 if (touchedWindow.windowHandle == fromWindowHandle) {
4572 int32_t oldTargetFlags = touchedWindow.targetFlags;
4573 BitSet32 pointerIds = touchedWindow.pointerIds;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004574
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004575 state.windows.erase(state.windows.begin() + i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004576
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004577 int32_t newTargetFlags = oldTargetFlags &
4578 (InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_SPLIT |
4579 InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004580 state.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004581
Jeff Brownf086ddb2014-02-11 14:28:48 -08004582 found = true;
4583 goto Found;
4584 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004585 }
4586 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004587 Found:
Michael Wrightd02c5b62014-02-10 15:10:22 -08004588
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004589 if (!found) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004590 if (DEBUG_FOCUS) {
4591 ALOGD("Focus transfer failed because from window did not have focus.");
4592 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004593 return false;
4594 }
4595
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004596 sp<Connection> fromConnection = getConnectionLocked(fromToken);
4597 sp<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004598 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004599 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004600 CancelationOptions
4601 options(CancelationOptions::CANCEL_POINTER_EVENTS,
4602 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004603 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004604 synthesizePointerDownEventsForConnectionLocked(toConnection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004605 }
4606
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004607 if (DEBUG_FOCUS) {
4608 logDispatchStateLocked();
4609 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004610 } // release lock
4611
4612 // Wake up poll loop since it may need to make new input dispatching choices.
4613 mLooper->wake();
4614 return true;
4615}
4616
4617void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004618 if (DEBUG_FOCUS) {
4619 ALOGD("Resetting and dropping all events (%s).", reason);
4620 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004621
4622 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
4623 synthesizeCancelationEventsForAllConnectionsLocked(options);
4624
4625 resetKeyRepeatLocked();
4626 releasePendingEventLocked();
4627 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004628 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004629
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004630 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08004631 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004632 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07004633 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004634}
4635
4636void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004637 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004638 dumpDispatchStateLocked(dump);
4639
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004640 std::istringstream stream(dump);
4641 std::string line;
4642
4643 while (std::getline(stream, line, '\n')) {
4644 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004645 }
4646}
4647
Vishnu Nairad321cd2020-08-20 16:40:21 -07004648std::string InputDispatcher::dumpFocusedWindowsLocked() {
4649 if (mFocusedWindowTokenByDisplay.empty()) {
4650 return INDENT "FocusedWindows: <none>\n";
4651 }
4652
4653 std::string dump;
4654 dump += INDENT "FocusedWindows:\n";
4655 for (auto& it : mFocusedWindowTokenByDisplay) {
4656 const int32_t displayId = it.first;
4657 const sp<InputWindowHandle> windowHandle = getFocusedWindowHandleLocked(displayId);
4658 if (windowHandle) {
4659 dump += StringPrintf(INDENT2 "displayId=%" PRId32 ", name='%s'\n", displayId,
4660 windowHandle->getName().c_str());
4661 } else {
4662 dump += StringPrintf(INDENT2 "displayId=%" PRId32
4663 " has focused token without a window'\n",
4664 displayId);
4665 }
4666 }
4667 return dump;
4668}
4669
Siarhei Vishniakouad991402020-10-28 11:40:09 -05004670std::string InputDispatcher::dumpPendingFocusRequestsLocked() {
4671 if (mPendingFocusRequests.empty()) {
4672 return INDENT "mPendingFocusRequests: <none>\n";
4673 }
4674
4675 std::string dump;
4676 dump += INDENT "mPendingFocusRequests:\n";
4677 for (const auto& [displayId, focusRequest] : mPendingFocusRequests) {
4678 // Rather than printing raw values for focusRequest.token and focusRequest.focusedToken,
4679 // try to resolve them to actual windows.
4680 std::string windowName = getConnectionNameLocked(focusRequest.token);
4681 std::string focusedWindowName = getConnectionNameLocked(focusRequest.focusedToken);
4682 dump += StringPrintf(INDENT2 "displayId=%" PRId32 ", token->%s, focusedToken->%s\n",
4683 displayId, windowName.c_str(), focusedWindowName.c_str());
4684 }
4685 return dump;
4686}
4687
Prabir Pradhan99987712020-11-10 18:43:05 -08004688std::string InputDispatcher::dumpPointerCaptureStateLocked() {
4689 std::string dump;
4690
4691 dump += StringPrintf(INDENT "FocusedWindowRequestedPointerCapture: %s\n",
4692 toString(mFocusedWindowRequestedPointerCapture));
4693
4694 std::string windowName = "None";
4695 if (mWindowTokenWithPointerCapture) {
4696 const sp<InputWindowHandle> captureWindowHandle =
4697 getWindowHandleLocked(mWindowTokenWithPointerCapture);
4698 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
4699 : "token has capture without window";
4700 }
4701 dump += StringPrintf(INDENT "CurrentWindowWithPointerCapture: %s\n", windowName.c_str());
4702
4703 return dump;
4704}
4705
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004706void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07004707 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
4708 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
4709 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08004710 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004711
Tiger Huang721e26f2018-07-24 22:26:19 +08004712 if (!mFocusedApplicationHandlesByDisplay.empty()) {
4713 dump += StringPrintf(INDENT "FocusedApplications:\n");
4714 for (auto& it : mFocusedApplicationHandlesByDisplay) {
4715 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07004716 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05004717 const std::chrono::duration timeout =
4718 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004719 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004720 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05004721 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08004722 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004723 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08004724 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004725 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004726
Vishnu Nairad321cd2020-08-20 16:40:21 -07004727 dump += dumpFocusedWindowsLocked();
Siarhei Vishniakouad991402020-10-28 11:40:09 -05004728 dump += dumpPendingFocusRequestsLocked();
Prabir Pradhan99987712020-11-10 18:43:05 -08004729 dump += dumpPointerCaptureStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004730
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004731 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004732 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004733 for (const std::pair<int32_t, TouchState>& pair : mTouchStatesByDisplay) {
4734 const TouchState& state = pair.second;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004735 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004736 state.displayId, toString(state.down), toString(state.split),
4737 state.deviceId, state.source);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004738 if (!state.windows.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004739 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004740 for (size_t i = 0; i < state.windows.size(); i++) {
4741 const TouchedWindow& touchedWindow = state.windows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004742 dump += StringPrintf(INDENT4
4743 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
4744 i, touchedWindow.windowHandle->getName().c_str(),
4745 touchedWindow.pointerIds.value, touchedWindow.targetFlags);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004746 }
4747 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004748 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004749 }
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004750 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004751 dump += INDENT3 "Portal windows:\n";
4752 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004753 const sp<InputWindowHandle> portalWindowHandle = state.portalWindows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004754 dump += StringPrintf(INDENT4 "%zu: name='%s'\n", i,
4755 portalWindowHandle->getName().c_str());
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004756 }
4757 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004758 }
4759 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004760 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004761 }
4762
Arthur Hungb92218b2018-08-14 12:00:21 +08004763 if (!mWindowHandlesByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004764 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004765 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
Arthur Hung3b413f22018-10-26 18:05:34 +08004766 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", it.first);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004767 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004768 dump += INDENT2 "Windows:\n";
4769 for (size_t i = 0; i < windowHandles.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004770 const sp<InputWindowHandle>& windowHandle = windowHandles[i];
Arthur Hungb92218b2018-08-14 12:00:21 +08004771 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004772
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00004773 dump += StringPrintf(INDENT3 "%zu: name='%s', id=%" PRId32 ", displayId=%d, "
Vishnu Nair47074b82020-08-14 11:54:47 -07004774 "portalToDisplayId=%d, paused=%s, focusable=%s, "
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00004775 "hasWallpaper=%s, visible=%s, alpha=%.2f, "
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00004776 "flags=%s, type=%s, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004777 "frame=[%d,%d][%d,%d], globalScale=%f, "
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004778 "applicationInfo=%s, "
chaviw1ff3d1e2020-07-01 15:53:47 -07004779 "touchableRegion=",
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00004780 i, windowInfo->name.c_str(), windowInfo->id,
4781 windowInfo->displayId, windowInfo->portalToDisplayId,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004782 toString(windowInfo->paused),
Vishnu Nair47074b82020-08-14 11:54:47 -07004783 toString(windowInfo->focusable),
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004784 toString(windowInfo->hasWallpaper),
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00004785 toString(windowInfo->visible), windowInfo->alpha,
Michael Wright8759d672020-07-21 00:46:45 +01004786 windowInfo->flags.string().c_str(),
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00004787 NamedEnum::string(windowInfo->type).c_str(),
Michael Wright44753b12020-07-08 13:48:11 +01004788 windowInfo->frameLeft, windowInfo->frameTop,
4789 windowInfo->frameRight, windowInfo->frameBottom,
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004790 windowInfo->globalScaleFactor,
4791 windowInfo->applicationInfo.name.c_str());
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00004792 dump += dumpRegion(windowInfo->touchableRegion);
Michael Wright44753b12020-07-08 13:48:11 +01004793 dump += StringPrintf(", inputFeatures=%s",
4794 windowInfo->inputFeatures.string().c_str());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004795 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%" PRId64
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00004796 "ms, trustedOverlay=%s, hasToken=%s, "
4797 "touchOcclusionMode=%s\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004798 windowInfo->ownerPid, windowInfo->ownerUid,
Bernardo Rufinoc2f1fad2020-11-04 17:30:57 +00004799 millis(windowInfo->dispatchingTimeout),
4800 toString(windowInfo->trustedOverlay),
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00004801 toString(windowInfo->token != nullptr),
4802 toString(windowInfo->touchOcclusionMode).c_str());
chaviw85b44202020-07-24 11:46:21 -07004803 windowInfo->transform.dump(dump, "transform", INDENT4);
Arthur Hungb92218b2018-08-14 12:00:21 +08004804 }
4805 } else {
4806 dump += INDENT2 "Windows: <none>\n";
4807 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004808 }
4809 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08004810 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004811 }
4812
Michael Wright3dd60e22019-03-27 22:06:44 +00004813 if (!mGlobalMonitorsByDisplay.empty() || !mGestureMonitorsByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004814 for (auto& it : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004815 const std::vector<Monitor>& monitors = it.second;
4816 dump += StringPrintf(INDENT "Global monitors in display %" PRId32 ":\n", it.first);
4817 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004818 }
4819 for (auto& it : mGestureMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004820 const std::vector<Monitor>& monitors = it.second;
4821 dump += StringPrintf(INDENT "Gesture monitors in display %" PRId32 ":\n", it.first);
4822 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004823 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004824 } else {
Michael Wright3dd60e22019-03-27 22:06:44 +00004825 dump += INDENT "Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004826 }
4827
4828 nsecs_t currentTime = now();
4829
4830 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004831 if (!mRecentQueue.empty()) {
4832 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004833 for (std::shared_ptr<EventEntry>& entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004834 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05004835 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004836 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004837 }
4838 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004839 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004840 }
4841
4842 // Dump event currently being dispatched.
4843 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004844 dump += INDENT "PendingEvent:\n";
4845 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05004846 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004847 dump += StringPrintf(", age=%" PRId64 "ms\n",
4848 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004849 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004850 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004851 }
4852
4853 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004854 if (!mInboundQueue.empty()) {
4855 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004856 for (std::shared_ptr<EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004857 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05004858 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004859 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004860 }
4861 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004862 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004863 }
4864
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004865 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004866 dump += INDENT "ReplacedKeys:\n";
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004867 for (const std::pair<KeyReplacement, int32_t>& pair : mReplacedKeys) {
4868 const KeyReplacement& replacement = pair.first;
4869 int32_t newKeyCode = pair.second;
4870 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004871 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07004872 }
4873 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004874 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07004875 }
4876
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004877 if (!mConnectionsByFd.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004878 dump += INDENT "Connections:\n";
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004879 for (const auto& pair : mConnectionsByFd) {
4880 const sp<Connection>& connection = pair.second;
4881 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004882 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004883 pair.first, connection->getInputChannelName().c_str(),
4884 connection->getWindowName().c_str(), connection->getStatusLabel(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004885 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004886
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004887 if (!connection->outboundQueue.empty()) {
4888 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
4889 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05004890 dump += dumpQueue(connection->outboundQueue, currentTime);
4891
Michael Wrightd02c5b62014-02-10 15:10:22 -08004892 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004893 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004894 }
4895
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004896 if (!connection->waitQueue.empty()) {
4897 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
4898 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05004899 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004900 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004901 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004902 }
4903 }
4904 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004905 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004906 }
4907
4908 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004909 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
4910 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004911 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004912 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004913 }
4914
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004915 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004916 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
4917 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
4918 ns2ms(mConfig.keyRepeatTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004919}
4920
Michael Wright3dd60e22019-03-27 22:06:44 +00004921void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
4922 const size_t numMonitors = monitors.size();
4923 for (size_t i = 0; i < numMonitors; i++) {
4924 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004925 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00004926 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
4927 dump += "\n";
4928 }
4929}
4930
Garfield Tan15601662020-09-22 15:32:38 -07004931base::Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(
4932 const std::string& name) {
4933#if DEBUG_CHANNEL_CREATION
4934 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004935#endif
4936
Garfield Tan15601662020-09-22 15:32:38 -07004937 std::shared_ptr<InputChannel> serverChannel;
4938 std::unique_ptr<InputChannel> clientChannel;
4939 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
4940
4941 if (result) {
4942 return base::Error(result) << "Failed to open input channel pair with name " << name;
4943 }
4944
Michael Wrightd02c5b62014-02-10 15:10:22 -08004945 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004946 std::scoped_lock _l(mLock);
Garfield Tan15601662020-09-22 15:32:38 -07004947 sp<Connection> connection = new Connection(serverChannel, false /*monitor*/, mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004948
Garfield Tan15601662020-09-22 15:32:38 -07004949 int fd = serverChannel->getFd();
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004950 mConnectionsByFd[fd] = connection;
Garfield Tan15601662020-09-22 15:32:38 -07004951 mInputChannelsByToken[serverChannel->getConnectionToken()] = serverChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004952
Michael Wrightd02c5b62014-02-10 15:10:22 -08004953 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
4954 } // release lock
4955
4956 // Wake the looper because some connections have changed.
4957 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07004958 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004959}
4960
Garfield Tan15601662020-09-22 15:32:38 -07004961base::Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(
Siarhei Vishniakou58cfc602020-12-14 23:21:30 +00004962 int32_t displayId, bool isGestureMonitor, const std::string& name, int32_t pid) {
Garfield Tan15601662020-09-22 15:32:38 -07004963 std::shared_ptr<InputChannel> serverChannel;
4964 std::unique_ptr<InputChannel> clientChannel;
4965 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
4966 if (result) {
4967 return base::Error(result) << "Failed to open input channel pair with name " << name;
4968 }
4969
Michael Wright3dd60e22019-03-27 22:06:44 +00004970 { // acquire lock
4971 std::scoped_lock _l(mLock);
4972
4973 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07004974 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
4975 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00004976 }
4977
Garfield Tan15601662020-09-22 15:32:38 -07004978 sp<Connection> connection = new Connection(serverChannel, true /*monitor*/, mIdGenerator);
Michael Wright3dd60e22019-03-27 22:06:44 +00004979
Garfield Tan15601662020-09-22 15:32:38 -07004980 const int fd = serverChannel->getFd();
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004981 mConnectionsByFd[fd] = connection;
Garfield Tan15601662020-09-22 15:32:38 -07004982 mInputChannelsByToken[serverChannel->getConnectionToken()] = serverChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00004983
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004984 auto& monitorsByDisplay =
4985 isGestureMonitor ? mGestureMonitorsByDisplay : mGlobalMonitorsByDisplay;
Siarhei Vishniakou58cfc602020-12-14 23:21:30 +00004986 monitorsByDisplay[displayId].emplace_back(serverChannel, pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00004987
4988 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
Michael Wright3dd60e22019-03-27 22:06:44 +00004989 }
Garfield Tan15601662020-09-22 15:32:38 -07004990
Michael Wright3dd60e22019-03-27 22:06:44 +00004991 // Wake the looper because some connections have changed.
4992 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07004993 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00004994}
4995
Garfield Tan15601662020-09-22 15:32:38 -07004996status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004997 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004998 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004999
Garfield Tan15601662020-09-22 15:32:38 -07005000 status_t status = removeInputChannelLocked(connectionToken, false /*notify*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005001 if (status) {
5002 return status;
5003 }
5004 } // release lock
5005
5006 // Wake the poll loop because removing the connection may have changed the current
5007 // synchronization state.
5008 mLooper->wake();
5009 return OK;
5010}
5011
Garfield Tan15601662020-09-22 15:32:38 -07005012status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
5013 bool notify) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005014 sp<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005015 if (connection == nullptr) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005016 ALOGW("Attempted to unregister already unregistered input channel");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005017 return BAD_VALUE;
5018 }
5019
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005020 removeConnectionLocked(connection);
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005021 mInputChannelsByToken.erase(connectionToken);
Robert Carr5c8a0262018-10-03 16:30:44 -07005022
Michael Wrightd02c5b62014-02-10 15:10:22 -08005023 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005024 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005025 }
5026
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005027 mLooper->removeFd(connection->inputChannel->getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005028
5029 nsecs_t currentTime = now();
5030 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
5031
5032 connection->status = Connection::STATUS_ZOMBIE;
5033 return OK;
5034}
5035
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005036void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
5037 removeMonitorChannelLocked(connectionToken, mGlobalMonitorsByDisplay);
5038 removeMonitorChannelLocked(connectionToken, mGestureMonitorsByDisplay);
Michael Wright3dd60e22019-03-27 22:06:44 +00005039}
5040
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005041void InputDispatcher::removeMonitorChannelLocked(
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005042 const sp<IBinder>& connectionToken,
Michael Wright3dd60e22019-03-27 22:06:44 +00005043 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005044 for (auto it = monitorsByDisplay.begin(); it != monitorsByDisplay.end();) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005045 std::vector<Monitor>& monitors = it->second;
5046 const size_t numMonitors = monitors.size();
5047 for (size_t i = 0; i < numMonitors; i++) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005048 if (monitors[i].inputChannel->getConnectionToken() == connectionToken) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005049 monitors.erase(monitors.begin() + i);
5050 break;
5051 }
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005052 }
Michael Wright3dd60e22019-03-27 22:06:44 +00005053 if (monitors.empty()) {
5054 it = monitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005055 } else {
5056 ++it;
5057 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005058 }
5059}
5060
Michael Wright3dd60e22019-03-27 22:06:44 +00005061status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
5062 { // acquire lock
5063 std::scoped_lock _l(mLock);
5064 std::optional<int32_t> foundDisplayId = findGestureMonitorDisplayByTokenLocked(token);
5065
5066 if (!foundDisplayId) {
5067 ALOGW("Attempted to pilfer pointers from an un-registered monitor or invalid token");
5068 return BAD_VALUE;
5069 }
5070 int32_t displayId = foundDisplayId.value();
5071
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005072 std::unordered_map<int32_t, TouchState>::iterator stateIt =
5073 mTouchStatesByDisplay.find(displayId);
5074 if (stateIt == mTouchStatesByDisplay.end()) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005075 ALOGW("Failed to pilfer pointers: no pointers on display %" PRId32 ".", displayId);
5076 return BAD_VALUE;
5077 }
5078
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005079 TouchState& state = stateIt->second;
Michael Wright3dd60e22019-03-27 22:06:44 +00005080 std::optional<int32_t> foundDeviceId;
5081 for (const TouchedMonitor& touchedMonitor : state.gestureMonitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005082 if (touchedMonitor.monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005083 foundDeviceId = state.deviceId;
5084 }
5085 }
5086 if (!foundDeviceId || !state.down) {
5087 ALOGW("Attempted to pilfer points from a monitor without any on-going pointer streams."
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005088 " Ignoring.");
Michael Wright3dd60e22019-03-27 22:06:44 +00005089 return BAD_VALUE;
5090 }
5091 int32_t deviceId = foundDeviceId.value();
5092
5093 // Send cancel events to all the input channels we're stealing from.
5094 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005095 "gesture monitor stole pointer stream");
Michael Wright3dd60e22019-03-27 22:06:44 +00005096 options.deviceId = deviceId;
5097 options.displayId = displayId;
5098 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005099 std::shared_ptr<InputChannel> channel =
5100 getInputChannelLocked(window.windowHandle->getToken());
Michael Wright3a240c42019-12-10 20:53:41 +00005101 if (channel != nullptr) {
5102 synthesizeCancelationEventsForInputChannelLocked(channel, options);
5103 }
Michael Wright3dd60e22019-03-27 22:06:44 +00005104 }
5105 // Then clear the current touch state so we stop dispatching to them as well.
5106 state.filterNonMonitors();
5107 }
5108 return OK;
5109}
5110
Prabir Pradhan99987712020-11-10 18:43:05 -08005111void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
5112 { // acquire lock
5113 std::scoped_lock _l(mLock);
5114 if (DEBUG_FOCUS) {
5115 const sp<InputWindowHandle> windowHandle = getWindowHandleLocked(windowToken);
5116 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
5117 windowHandle != nullptr ? windowHandle->getName().c_str()
5118 : "token without window");
5119 }
5120
5121 const sp<IBinder> focusedToken =
5122 getValueByKey(mFocusedWindowTokenByDisplay, mFocusedDisplayId);
5123 if (focusedToken != windowToken) {
5124 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
5125 enabled ? "enable" : "disable");
5126 return;
5127 }
5128
5129 if (enabled == mFocusedWindowRequestedPointerCapture) {
5130 ALOGW("Ignoring request to %s Pointer Capture: "
5131 "window has %s requested pointer capture.",
5132 enabled ? "enable" : "disable", enabled ? "already" : "not");
5133 return;
5134 }
5135
5136 mFocusedWindowRequestedPointerCapture = enabled;
5137 setPointerCaptureLocked(enabled);
5138 } // release lock
5139
5140 // Wake the thread to process command entries.
5141 mLooper->wake();
5142}
5143
Michael Wright3dd60e22019-03-27 22:06:44 +00005144std::optional<int32_t> InputDispatcher::findGestureMonitorDisplayByTokenLocked(
5145 const sp<IBinder>& token) {
5146 for (const auto& it : mGestureMonitorsByDisplay) {
5147 const std::vector<Monitor>& monitors = it.second;
5148 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005149 if (monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005150 return it.first;
5151 }
5152 }
5153 }
5154 return std::nullopt;
5155}
5156
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005157sp<Connection> InputDispatcher::getConnectionLocked(const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005158 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005159 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08005160 }
5161
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005162 for (const auto& pair : mConnectionsByFd) {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005163 const sp<Connection>& connection = pair.second;
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005164 if (connection->inputChannel->getConnectionToken() == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005165 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005166 }
5167 }
Robert Carr4e670e52018-08-15 13:26:12 -07005168
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005169 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005170}
5171
Siarhei Vishniakouad991402020-10-28 11:40:09 -05005172std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
5173 sp<Connection> connection = getConnectionLocked(connectionToken);
5174 if (connection == nullptr) {
5175 return "<nullptr>";
5176 }
5177 return connection->getInputChannelName();
5178}
5179
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005180void InputDispatcher::removeConnectionLocked(const sp<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005181 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005182 removeByValue(mConnectionsByFd, connection);
5183}
5184
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005185void InputDispatcher::onDispatchCycleFinishedLocked(nsecs_t currentTime,
5186 const sp<Connection>& connection, uint32_t seq,
5187 bool handled) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005188 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5189 &InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005190 commandEntry->connection = connection;
5191 commandEntry->eventTime = currentTime;
5192 commandEntry->seq = seq;
5193 commandEntry->handled = handled;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005194 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005195}
5196
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005197void InputDispatcher::onDispatchCycleBrokenLocked(nsecs_t currentTime,
5198 const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005199 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005200 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005201
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005202 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5203 &InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005204 commandEntry->connection = connection;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005205 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005206}
5207
Vishnu Nairad321cd2020-08-20 16:40:21 -07005208void InputDispatcher::notifyFocusChangedLocked(const sp<IBinder>& oldToken,
5209 const sp<IBinder>& newToken) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005210 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5211 &InputDispatcher::doNotifyFocusChangedLockedInterruptible);
chaviw0c06c6e2019-01-09 13:27:07 -08005212 commandEntry->oldToken = oldToken;
5213 commandEntry->newToken = newToken;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005214 postCommandLocked(std::move(commandEntry));
Robert Carrf759f162018-11-13 12:57:11 -08005215}
5216
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -05005217void InputDispatcher::onAnrLocked(const Connection& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005218 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
5219 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -05005220 if (connection.waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005221 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -05005222 connection.inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005223 return;
5224 }
5225 /**
5226 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
5227 * may not be the one that caused the timeout to occur. One possibility is that window timeout
5228 * has changed. This could cause newer entries to time out before the already dispatched
5229 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
5230 * processes the events linearly. So providing information about the oldest entry seems to be
5231 * most useful.
5232 */
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -05005233 DispatchEntry* oldestEntry = *connection.waitQueue.begin();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005234 const nsecs_t currentWait = now() - oldestEntry->deliveryTime;
5235 std::string reason =
5236 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -05005237 connection.inputChannel->getName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005238 ns2ms(currentWait),
5239 oldestEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06005240 sp<IBinder> connectionToken = connection.inputChannel->getConnectionToken();
5241 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005242
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005243 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5244 &InputDispatcher::doNotifyConnectionUnresponsiveLockedInterruptible);
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06005245 commandEntry->connectionToken = connectionToken;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005246 commandEntry->reason = std::move(reason);
5247 postCommandLocked(std::move(commandEntry));
5248}
5249
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005250void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
5251 std::string reason =
5252 StringPrintf("%s does not have a focused window", application->getName().c_str());
5253 updateLastAnrStateLocked(*application, reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005254
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005255 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5256 &InputDispatcher::doNotifyNoFocusedWindowAnrLockedInterruptible);
5257 commandEntry->inputApplicationHandle = std::move(application);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005258 postCommandLocked(std::move(commandEntry));
5259}
5260
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00005261void InputDispatcher::onUntrustedTouchLocked(const std::string& obscuringPackage) {
5262 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5263 &InputDispatcher::doNotifyUntrustedTouchLockedInterruptible);
5264 commandEntry->obscuringPackage = obscuringPackage;
5265 postCommandLocked(std::move(commandEntry));
5266}
5267
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005268void InputDispatcher::updateLastAnrStateLocked(const sp<InputWindowHandle>& window,
5269 const std::string& reason) {
5270 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
5271 updateLastAnrStateLocked(windowLabel, reason);
5272}
5273
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005274void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
5275 const std::string& reason) {
5276 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005277 updateLastAnrStateLocked(windowLabel, reason);
5278}
5279
5280void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
5281 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005282 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07005283 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005284 struct tm tm;
5285 localtime_r(&t, &tm);
5286 char timestr[64];
5287 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005288 mLastAnrState.clear();
5289 mLastAnrState += INDENT "ANR:\n";
5290 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005291 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
5292 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005293 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005294}
5295
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005296void InputDispatcher::doNotifyConfigurationChangedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005297 mLock.unlock();
5298
5299 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
5300
5301 mLock.lock();
5302}
5303
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005304void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005305 sp<Connection> connection = commandEntry->connection;
5306
5307 if (connection->status != Connection::STATUS_ZOMBIE) {
5308 mLock.unlock();
5309
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005310 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005311
5312 mLock.lock();
5313 }
5314}
5315
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005316void InputDispatcher::doNotifyFocusChangedLockedInterruptible(CommandEntry* commandEntry) {
chaviw0c06c6e2019-01-09 13:27:07 -08005317 sp<IBinder> oldToken = commandEntry->oldToken;
5318 sp<IBinder> newToken = commandEntry->newToken;
Robert Carrf759f162018-11-13 12:57:11 -08005319 mLock.unlock();
chaviw0c06c6e2019-01-09 13:27:07 -08005320 mPolicy->notifyFocusChanged(oldToken, newToken);
Robert Carrf759f162018-11-13 12:57:11 -08005321 mLock.lock();
5322}
5323
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005324void InputDispatcher::doNotifyNoFocusedWindowAnrLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005325 mLock.unlock();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005326
5327 mPolicy->notifyNoFocusedWindowAnr(commandEntry->inputApplicationHandle);
5328
5329 mLock.lock();
5330}
5331
5332void InputDispatcher::doNotifyConnectionUnresponsiveLockedInterruptible(
5333 CommandEntry* commandEntry) {
5334 mLock.unlock();
5335
5336 mPolicy->notifyConnectionUnresponsive(commandEntry->connectionToken, commandEntry->reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005337
5338 mLock.lock();
5339
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005340 // stop waking up for events in this connection, it is already not responding
5341 sp<Connection> connection = getConnectionLocked(commandEntry->connectionToken);
5342 if (connection == nullptr) {
5343 return;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005344 }
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005345 cancelEventsForAnrLocked(connection);
5346}
5347
5348void InputDispatcher::doNotifyConnectionResponsiveLockedInterruptible(CommandEntry* commandEntry) {
5349 mLock.unlock();
5350
5351 mPolicy->notifyConnectionResponsive(commandEntry->connectionToken);
5352
5353 mLock.lock();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005354}
5355
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00005356void InputDispatcher::doNotifyUntrustedTouchLockedInterruptible(CommandEntry* commandEntry) {
5357 mLock.unlock();
5358
5359 mPolicy->notifyUntrustedTouch(commandEntry->obscuringPackage);
5360
5361 mLock.lock();
5362}
5363
Michael Wrightd02c5b62014-02-10 15:10:22 -08005364void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
5365 CommandEntry* commandEntry) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005366 KeyEntry& entry = *(commandEntry->keyEntry);
5367 KeyEvent event = createKeyEvent(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005368
5369 mLock.unlock();
5370
Michael Wright2b3c3302018-03-02 17:19:13 +00005371 android::base::Timer t;
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06005372 const sp<IBinder>& token = commandEntry->connectionToken;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005373 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(token, &event, entry.policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00005374 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
5375 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005376 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00005377 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005378
5379 mLock.lock();
5380
5381 if (delay < 0) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005382 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005383 } else if (!delay) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005384 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005385 } else {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005386 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
5387 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005388 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005389}
5390
chaviwfd6d3512019-03-25 13:23:49 -07005391void InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible(CommandEntry* commandEntry) {
5392 mLock.unlock();
5393 mPolicy->onPointerDownOutsideFocus(commandEntry->newToken);
5394 mLock.lock();
5395}
5396
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005397/**
5398 * Connection is responsive if it has no events in the waitQueue that are older than the
5399 * current time.
5400 */
5401static bool isConnectionResponsive(const Connection& connection) {
5402 const nsecs_t currentTime = now();
5403 for (const DispatchEntry* entry : connection.waitQueue) {
5404 if (entry->timeoutTime < currentTime) {
5405 return false;
5406 }
5407 }
5408 return true;
5409}
5410
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005411void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005412 sp<Connection> connection = commandEntry->connection;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005413 const nsecs_t finishTime = commandEntry->eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005414 uint32_t seq = commandEntry->seq;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005415 const bool handled = commandEntry->handled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005416
5417 // Handle post-event policy actions.
Garfield Tane84e6f92019-08-29 17:28:41 -07005418 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005419 if (dispatchEntryIt == connection->waitQueue.end()) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005420 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005421 }
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005422 DispatchEntry* dispatchEntry = *dispatchEntryIt;
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07005423 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005424 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005425 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
5426 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005427 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07005428 reportDispatchStatistics(std::chrono::nanoseconds(eventDuration), *connection, handled);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005429
5430 bool restartEvent;
Siarhei Vishniakou49483272019-10-22 13:13:47 -07005431 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005432 KeyEntry& keyEntry = static_cast<KeyEntry&>(*(dispatchEntry->eventEntry));
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005433 restartEvent =
5434 afterKeyEventLockedInterruptible(connection, dispatchEntry, keyEntry, handled);
Siarhei Vishniakou49483272019-10-22 13:13:47 -07005435 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005436 MotionEntry& motionEntry = static_cast<MotionEntry&>(*(dispatchEntry->eventEntry));
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005437 restartEvent = afterMotionEventLockedInterruptible(connection, dispatchEntry, motionEntry,
5438 handled);
5439 } else {
5440 restartEvent = false;
5441 }
5442
5443 // Dequeue the event and start the next cycle.
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07005444 // Because the lock might have been released, it is possible that the
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005445 // contents of the wait queue to have been drained, so we need to double-check
5446 // a few things.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005447 dispatchEntryIt = connection->findWaitQueueEntry(seq);
5448 if (dispatchEntryIt != connection->waitQueue.end()) {
5449 dispatchEntry = *dispatchEntryIt;
5450 connection->waitQueue.erase(dispatchEntryIt);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005451 const sp<IBinder>& connectionToken = connection->inputChannel->getConnectionToken();
5452 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005453 if (!connection->responsive) {
5454 connection->responsive = isConnectionResponsive(*connection);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005455 if (connection->responsive) {
5456 // The connection was unresponsive, and now it's responsive. Tell the policy
5457 // about it so that it can stop ANR.
5458 std::unique_ptr<CommandEntry> connectionResponsiveCommand =
5459 std::make_unique<CommandEntry>(
5460 &InputDispatcher::doNotifyConnectionResponsiveLockedInterruptible);
5461 connectionResponsiveCommand->connectionToken = connectionToken;
5462 postCommandLocked(std::move(connectionResponsiveCommand));
5463 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005464 }
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005465 traceWaitQueueLength(connection);
5466 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005467 connection->outboundQueue.push_front(dispatchEntry);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005468 traceOutboundQueueLength(connection);
5469 } else {
5470 releaseDispatchEntry(dispatchEntry);
5471 }
5472 }
5473
5474 // Start the next dispatch cycle for this connection.
5475 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005476}
5477
5478bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005479 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005480 KeyEntry& keyEntry, bool handled) {
5481 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005482 if (!handled) {
5483 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005484 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005485 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005486 return false;
5487 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005488
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005489 // Get the fallback key state.
5490 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005491 int32_t originalKeyCode = keyEntry.keyCode;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005492 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005493 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005494 connection->inputState.removeFallbackKey(originalKeyCode);
5495 }
5496
5497 if (handled || !dispatchEntry->hasForegroundTarget()) {
5498 // If the application handles the original key for which we previously
5499 // generated a fallback or if the window is not a foreground window,
5500 // then cancel the associated fallback key, if any.
5501 if (fallbackKeyCode != -1) {
5502 // Dispatch the unhandled key to the policy with the cancel flag.
Michael Wrightd02c5b62014-02-10 15:10:22 -08005503#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005504 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005505 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005506 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005507#endif
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005508 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005509 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005510
5511 mLock.unlock();
5512
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005513 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005514 keyEntry.policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005515
5516 mLock.lock();
5517
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005518 // Cancel the fallback key.
5519 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005520 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005521 "application handled the original non-fallback key "
5522 "or is no longer a foreground target, "
5523 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005524 options.keyCode = fallbackKeyCode;
5525 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005526 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005527 connection->inputState.removeFallbackKey(originalKeyCode);
5528 }
5529 } else {
5530 // If the application did not handle a non-fallback key, first check
5531 // that we are in a good state to perform unhandled key event processing
5532 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005533 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005534 if (fallbackKeyCode == -1 && !initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005535#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005536 ALOGD("Unhandled key event: Skipping unhandled key event processing "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005537 "since this is not an initial down. "
5538 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005539 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005540#endif
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005541 return false;
5542 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005543
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005544 // Dispatch the unhandled key to the policy.
5545#if DEBUG_OUTBOUND_EVENT_DETAILS
5546 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005547 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005548 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005549#endif
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005550 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005551
5552 mLock.unlock();
5553
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005554 bool fallback =
5555 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005556 &event, keyEntry.policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005557
5558 mLock.lock();
5559
5560 if (connection->status != Connection::STATUS_NORMAL) {
5561 connection->inputState.removeFallbackKey(originalKeyCode);
5562 return false;
5563 }
5564
5565 // Latch the fallback keycode for this key on an initial down.
5566 // The fallback keycode cannot change at any other point in the lifecycle.
5567 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005568 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005569 fallbackKeyCode = event.getKeyCode();
5570 } else {
5571 fallbackKeyCode = AKEYCODE_UNKNOWN;
5572 }
5573 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
5574 }
5575
5576 ALOG_ASSERT(fallbackKeyCode != -1);
5577
5578 // Cancel the fallback key if the policy decides not to send it anymore.
5579 // We will continue to dispatch the key to the policy but we will no
5580 // longer dispatch a fallback key to the application.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005581 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
5582 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005583#if DEBUG_OUTBOUND_EVENT_DETAILS
5584 if (fallback) {
5585 ALOGD("Unhandled key event: Policy requested to send key %d"
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005586 "as a fallback for %d, but on the DOWN it had requested "
5587 "to send %d instead. Fallback canceled.",
5588 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005589 } else {
5590 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005591 "but on the DOWN it had requested to send %d. "
5592 "Fallback canceled.",
5593 originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005594 }
5595#endif
5596
5597 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
5598 "canceling fallback, policy no longer desires it");
5599 options.keyCode = fallbackKeyCode;
5600 synthesizeCancelationEventsForConnectionLocked(connection, options);
5601
5602 fallback = false;
5603 fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005604 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005605 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005606 }
5607 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005608
5609#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005610 {
5611 std::string msg;
5612 const KeyedVector<int32_t, int32_t>& fallbackKeys =
5613 connection->inputState.getFallbackKeys();
5614 for (size_t i = 0; i < fallbackKeys.size(); i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005615 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005616 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005617 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005618 fallbackKeys.size(), msg.c_str());
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005619 }
5620#endif
5621
5622 if (fallback) {
5623 // Restart the dispatch cycle using the fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005624 keyEntry.eventTime = event.getEventTime();
5625 keyEntry.deviceId = event.getDeviceId();
5626 keyEntry.source = event.getSource();
5627 keyEntry.displayId = event.getDisplayId();
5628 keyEntry.flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
5629 keyEntry.keyCode = fallbackKeyCode;
5630 keyEntry.scanCode = event.getScanCode();
5631 keyEntry.metaState = event.getMetaState();
5632 keyEntry.repeatCount = event.getRepeatCount();
5633 keyEntry.downTime = event.getDownTime();
5634 keyEntry.syntheticRepeat = false;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005635
5636#if DEBUG_OUTBOUND_EVENT_DETAILS
5637 ALOGD("Unhandled key event: Dispatching fallback key. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005638 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005639 originalKeyCode, fallbackKeyCode, keyEntry.metaState);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005640#endif
5641 return true; // restart the event
5642 } else {
5643#if DEBUG_OUTBOUND_EVENT_DETAILS
5644 ALOGD("Unhandled key event: No fallback key.");
5645#endif
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005646
5647 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005648 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005649 }
5650 }
5651 return false;
5652}
5653
5654bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005655 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005656 MotionEntry& motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005657 return false;
5658}
5659
5660void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
5661 mLock.unlock();
5662
5663 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType);
5664
5665 mLock.lock();
5666}
5667
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07005668void InputDispatcher::reportDispatchStatistics(std::chrono::nanoseconds eventDuration,
5669 const Connection& connection, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005670 // TODO Write some statistics about how long we spend waiting.
5671}
5672
Siarhei Vishniakoude4bf152019-08-16 11:12:52 -05005673/**
5674 * Report the touch event latency to the statsd server.
5675 * Input events are reported for statistics if:
5676 * - This is a touchscreen event
5677 * - InputFilter is not enabled
5678 * - Event is not injected or synthesized
5679 *
5680 * Statistics should be reported before calling addValue, to prevent a fresh new sample
5681 * from getting aggregated with the "old" data.
5682 */
5683void InputDispatcher::reportTouchEventForStatistics(const MotionEntry& motionEntry)
5684 REQUIRES(mLock) {
5685 const bool reportForStatistics = (motionEntry.source == AINPUT_SOURCE_TOUCHSCREEN) &&
5686 !(motionEntry.isSynthesized()) && !mInputFilterEnabled;
5687 if (!reportForStatistics) {
5688 return;
5689 }
5690
5691 if (mTouchStatistics.shouldReport()) {
5692 android::util::stats_write(android::util::TOUCH_EVENT_REPORTED, mTouchStatistics.getMin(),
5693 mTouchStatistics.getMax(), mTouchStatistics.getMean(),
5694 mTouchStatistics.getStDev(), mTouchStatistics.getCount());
5695 mTouchStatistics.reset();
5696 }
5697 const float latencyMicros = nanoseconds_to_microseconds(now() - motionEntry.eventTime);
5698 mTouchStatistics.addValue(latencyMicros);
5699}
5700
Michael Wrightd02c5b62014-02-10 15:10:22 -08005701void InputDispatcher::traceInboundQueueLengthLocked() {
5702 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005703 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005704 }
5705}
5706
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08005707void InputDispatcher::traceOutboundQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005708 if (ATRACE_ENABLED()) {
5709 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08005710 snprintf(counterName, sizeof(counterName), "oq:%s", connection->getWindowName().c_str());
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005711 ATRACE_INT(counterName, connection->outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005712 }
5713}
5714
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08005715void InputDispatcher::traceWaitQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005716 if (ATRACE_ENABLED()) {
5717 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08005718 snprintf(counterName, sizeof(counterName), "wq:%s", connection->getWindowName().c_str());
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005719 ATRACE_INT(counterName, connection->waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005720 }
5721}
5722
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005723void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005724 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005725
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005726 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005727 dumpDispatchStateLocked(dump);
5728
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005729 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005730 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005731 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005732 }
5733}
5734
5735void InputDispatcher::monitor() {
5736 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005737 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005738 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005739 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005740}
5741
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08005742/**
5743 * Wake up the dispatcher and wait until it processes all events and commands.
5744 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
5745 * this method can be safely called from any thread, as long as you've ensured that
5746 * the work you are interested in completing has already been queued.
5747 */
5748bool InputDispatcher::waitForIdle() {
5749 /**
5750 * Timeout should represent the longest possible time that a device might spend processing
5751 * events and commands.
5752 */
5753 constexpr std::chrono::duration TIMEOUT = 100ms;
5754 std::unique_lock lock(mLock);
5755 mLooper->wake();
5756 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
5757 return result == std::cv_status::no_timeout;
5758}
5759
Vishnu Naire798b472020-07-23 13:52:21 -07005760/**
5761 * Sets focus to the window identified by the token. This must be called
5762 * after updating any input window handles.
5763 *
5764 * Params:
5765 * request.token - input channel token used to identify the window that should gain focus.
5766 * request.focusedToken - the token that the caller expects currently to be focused. If the
5767 * specified token does not match the currently focused window, this request will be dropped.
5768 * If the specified focused token matches the currently focused window, the call will succeed.
5769 * Set this to "null" if this call should succeed no matter what the currently focused token is.
5770 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
5771 * when requesting the focus change. This determines which request gets
5772 * precedence if there is a focus change request from another source such as pointer down.
5773 */
Vishnu Nair958da932020-08-21 17:12:37 -07005774void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
5775 { // acquire lock
5776 std::scoped_lock _l(mLock);
5777
5778 const int32_t displayId = request.displayId;
5779 const sp<IBinder> oldFocusedToken = getValueByKey(mFocusedWindowTokenByDisplay, displayId);
5780 if (request.focusedToken && oldFocusedToken != request.focusedToken) {
5781 ALOGD_IF(DEBUG_FOCUS,
5782 "setFocusedWindow on display %" PRId32
5783 " ignored, reason: focusedToken is not focused",
5784 displayId);
5785 return;
5786 }
5787
5788 mPendingFocusRequests.erase(displayId);
5789 FocusResult result = handleFocusRequestLocked(request);
5790 if (result == FocusResult::NOT_VISIBLE) {
5791 // The requested window is not currently visible. Wait for the window to become visible
5792 // and then provide it focus. This is to handle situations where a user action triggers
5793 // a new window to appear. We want to be able to queue any key events after the user
5794 // action and deliver it to the newly focused window. In order for this to happen, we
5795 // take focus from the currently focused window so key events can be queued.
5796 ALOGD_IF(DEBUG_FOCUS,
5797 "setFocusedWindow on display %" PRId32
5798 " pending, reason: window is not visible",
5799 displayId);
5800 mPendingFocusRequests[displayId] = request;
5801 onFocusChangedLocked(oldFocusedToken, nullptr, displayId,
5802 "setFocusedWindow_AwaitingWindowVisibility");
5803 } else if (result != FocusResult::OK) {
5804 ALOGW("setFocusedWindow on display %" PRId32 " ignored, reason:%s", displayId,
5805 typeToString(result));
5806 }
5807 } // release lock
5808 // Wake up poll loop since it may need to make new input dispatching choices.
5809 mLooper->wake();
5810}
5811
5812InputDispatcher::FocusResult InputDispatcher::handleFocusRequestLocked(
5813 const FocusRequest& request) {
5814 const int32_t displayId = request.displayId;
5815 const sp<IBinder> newFocusedToken = request.token;
5816 const sp<IBinder> oldFocusedToken = getValueByKey(mFocusedWindowTokenByDisplay, displayId);
5817
5818 if (oldFocusedToken == request.token) {
5819 ALOGD_IF(DEBUG_FOCUS,
5820 "setFocusedWindow on display %" PRId32 " ignored, reason: already focused",
5821 displayId);
5822 return FocusResult::OK;
5823 }
5824
5825 FocusResult result = checkTokenFocusableLocked(newFocusedToken, displayId);
5826 if (result != FocusResult::OK) {
5827 return result;
5828 }
5829
5830 std::string_view reason =
5831 (request.focusedToken) ? "setFocusedWindow_FocusCheck" : "setFocusedWindow";
5832 onFocusChangedLocked(oldFocusedToken, newFocusedToken, displayId, reason);
5833 return FocusResult::OK;
5834}
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005835
Vishnu Nairad321cd2020-08-20 16:40:21 -07005836void InputDispatcher::onFocusChangedLocked(const sp<IBinder>& oldFocusedToken,
5837 const sp<IBinder>& newFocusedToken, int32_t displayId,
5838 std::string_view reason) {
5839 if (oldFocusedToken) {
5840 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(oldFocusedToken);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005841 if (focusedInputChannel) {
5842 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
5843 "focus left window");
5844 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Vishnu Nairad321cd2020-08-20 16:40:21 -07005845 enqueueFocusEventLocked(oldFocusedToken, false /*hasFocus*/, reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005846 }
Vishnu Nairad321cd2020-08-20 16:40:21 -07005847 mFocusedWindowTokenByDisplay.erase(displayId);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005848 }
Vishnu Nairad321cd2020-08-20 16:40:21 -07005849 if (newFocusedToken) {
5850 mFocusedWindowTokenByDisplay[displayId] = newFocusedToken;
5851 enqueueFocusEventLocked(newFocusedToken, true /*hasFocus*/, reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005852 }
5853
Prabir Pradhan99987712020-11-10 18:43:05 -08005854 // If a window has pointer capture, then it must have focus. We need to ensure that this
5855 // contract is upheld when pointer capture is being disabled due to a loss of window focus.
5856 // If the window loses focus before it loses pointer capture, then the window can be in a state
5857 // where it has pointer capture but not focus, violating the contract. Therefore we must
5858 // dispatch the pointer capture event before the focus event. Since focus events are added to
5859 // the front of the queue (above), we add the pointer capture event to the front of the queue
5860 // after the focus events are added. This ensures the pointer capture event ends up at the
5861 // front.
5862 disablePointerCaptureForcedLocked();
5863
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005864 if (mFocusedDisplayId == displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005865 notifyFocusChangedLocked(oldFocusedToken, newFocusedToken);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005866 }
5867}
Vishnu Nair958da932020-08-21 17:12:37 -07005868
Prabir Pradhan99987712020-11-10 18:43:05 -08005869void InputDispatcher::disablePointerCaptureForcedLocked() {
5870 if (!mFocusedWindowRequestedPointerCapture && !mWindowTokenWithPointerCapture) {
5871 return;
5872 }
5873
5874 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
5875
5876 if (mFocusedWindowRequestedPointerCapture) {
5877 mFocusedWindowRequestedPointerCapture = false;
5878 setPointerCaptureLocked(false);
5879 }
5880
5881 if (!mWindowTokenWithPointerCapture) {
5882 // No need to send capture changes because no window has capture.
5883 return;
5884 }
5885
5886 if (mPendingEvent != nullptr) {
5887 // Move the pending event to the front of the queue. This will give the chance
5888 // for the pending event to be dropped if it is a captured event.
5889 mInboundQueue.push_front(mPendingEvent);
5890 mPendingEvent = nullptr;
5891 }
5892
5893 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
5894 false /* hasCapture */);
5895 mInboundQueue.push_front(std::move(entry));
5896}
5897
Vishnu Nair958da932020-08-21 17:12:37 -07005898/**
5899 * Checks if the window token can be focused on a display. The token can be focused if there is
5900 * at least one window handle that is visible with the same token and all window handles with the
5901 * same token are focusable.
5902 *
5903 * In the case of mirroring, two windows may share the same window token and their visibility
5904 * might be different. Example, the mirrored window can cover the window its mirroring. However,
5905 * we expect the focusability of the windows to match since its hard to reason why one window can
5906 * receive focus events and the other cannot when both are backed by the same input channel.
5907 */
5908InputDispatcher::FocusResult InputDispatcher::checkTokenFocusableLocked(const sp<IBinder>& token,
5909 int32_t displayId) const {
5910 bool allWindowsAreFocusable = true;
5911 bool visibleWindowFound = false;
5912 bool windowFound = false;
5913 for (const sp<InputWindowHandle>& window : getWindowHandlesLocked(displayId)) {
5914 if (window->getToken() != token) {
5915 continue;
5916 }
5917 windowFound = true;
5918 if (window->getInfo()->visible) {
5919 // Check if at least a single window is visible.
5920 visibleWindowFound = true;
5921 }
5922 if (!window->getInfo()->focusable) {
5923 // Check if all windows with the window token are focusable.
5924 allWindowsAreFocusable = false;
5925 break;
5926 }
5927 }
5928
5929 if (!windowFound) {
5930 return FocusResult::NO_WINDOW;
5931 }
5932 if (!allWindowsAreFocusable) {
5933 return FocusResult::NOT_FOCUSABLE;
5934 }
5935 if (!visibleWindowFound) {
5936 return FocusResult::NOT_VISIBLE;
5937 }
5938
5939 return FocusResult::OK;
5940}
Prabir Pradhan99987712020-11-10 18:43:05 -08005941
5942void InputDispatcher::setPointerCaptureLocked(bool enabled) {
5943 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5944 &InputDispatcher::doSetPointerCaptureLockedInterruptible);
5945 commandEntry->enabled = enabled;
5946 postCommandLocked(std::move(commandEntry));
5947}
5948
5949void InputDispatcher::doSetPointerCaptureLockedInterruptible(
5950 android::inputdispatcher::CommandEntry* commandEntry) {
5951 mLock.unlock();
5952
5953 mPolicy->setPointerCapture(commandEntry->enabled);
5954
5955 mLock.lock();
5956}
5957
Garfield Tane84e6f92019-08-29 17:28:41 -07005958} // namespace android::inputdispatcher