blob: 284d0f1cb3ef032ef291253f05347f55225474d6 [file] [log] [blame]
Michael Wrightd02c5b62014-02-10 15:10:22 -08001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "InputDispatcher"
18#define ATRACE_TAG ATRACE_TAG_INPUT
19
John Recke0710582019-09-26 13:46:12 -070020#define LOG_NDEBUG 1
Michael Wrightd02c5b62014-02-10 15:10:22 -080021
22// Log detailed debug messages about each inbound event notification to the dispatcher.
23#define DEBUG_INBOUND_EVENT_DETAILS 0
24
25// Log detailed debug messages about each outbound event processed by the dispatcher.
26#define DEBUG_OUTBOUND_EVENT_DETAILS 0
27
28// Log debug messages about the dispatch cycle.
29#define DEBUG_DISPATCH_CYCLE 0
30
Garfield Tan15601662020-09-22 15:32:38 -070031// Log debug messages about channel creation
32#define DEBUG_CHANNEL_CREATION 0
Michael Wrightd02c5b62014-02-10 15:10:22 -080033
34// Log debug messages about input event injection.
35#define DEBUG_INJECTION 0
36
37// Log debug messages about input focus tracking.
Siarhei Vishniakou86587282019-09-09 18:20:15 +010038static constexpr bool DEBUG_FOCUS = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -080039
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +000040// Log debug messages about touch occlusion
41// STOPSHIP(b/169067926): Set to false
42static constexpr bool DEBUG_TOUCH_OCCLUSION = true;
43
Michael Wrightd02c5b62014-02-10 15:10:22 -080044// Log debug messages about the app switch latency optimization.
45#define DEBUG_APP_SWITCH 0
46
47// Log debug messages about hover events.
48#define DEBUG_HOVER 0
49
Michael Wright2b3c3302018-03-02 17:19:13 +000050#include <android-base/chrono_utils.h>
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080051#include <android-base/stringprintf.h>
Siarhei Vishniakou70622952020-07-30 11:17:23 -050052#include <android/os/IInputConstants.h>
Robert Carr4e670e52018-08-15 13:26:12 -070053#include <binder/Binder.h>
Siarhei Vishniakou2508b872020-12-03 16:33:53 -100054#include <binder/IServiceManager.h>
55#include <com/android/internal/compat/IPlatformCompatNative.h>
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -080056#include <input/InputDevice.h>
Michael Wright44753b12020-07-08 13:48:11 +010057#include <input/InputWindow.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070058#include <log/log.h>
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +000059#include <log/log_event_list.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070060#include <powermanager/PowerManager.h>
Michael Wright44753b12020-07-08 13:48:11 +010061#include <statslog.h>
62#include <unistd.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070063#include <utils/Trace.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080064
Michael Wright44753b12020-07-08 13:48:11 +010065#include <cerrno>
66#include <cinttypes>
67#include <climits>
68#include <cstddef>
69#include <ctime>
70#include <queue>
71#include <sstream>
72
73#include "Connection.h"
Chris Yef59a2f42020-10-16 12:55:26 -070074#include "InputDispatcher.h"
Michael Wright44753b12020-07-08 13:48:11 +010075
Michael Wrightd02c5b62014-02-10 15:10:22 -080076#define INDENT " "
77#define INDENT2 " "
78#define INDENT3 " "
79#define INDENT4 " "
80
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080081using android::base::StringPrintf;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -080082using android::os::BlockUntrustedTouchesMode;
Siarhei Vishniakou2508b872020-12-03 16:33:53 -100083using android::os::IInputConstants;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -080084using android::os::InputEventInjectionResult;
85using android::os::InputEventInjectionSync;
Siarhei Vishniakou2508b872020-12-03 16:33:53 -100086using com::android::internal::compat::IPlatformCompatNative;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080087
Garfield Tane84e6f92019-08-29 17:28:41 -070088namespace android::inputdispatcher {
Michael Wrightd02c5b62014-02-10 15:10:22 -080089
90// Default input dispatching timeout if there is no focused application or paused window
91// from which to determine an appropriate dispatching timeout.
Siarhei Vishniakou70622952020-07-30 11:17:23 -050092constexpr std::chrono::duration DEFAULT_INPUT_DISPATCHING_TIMEOUT =
93 std::chrono::milliseconds(android::os::IInputConstants::DEFAULT_DISPATCHING_TIMEOUT_MILLIS);
Michael Wrightd02c5b62014-02-10 15:10:22 -080094
95// Amount of time to allow for all pending events to be processed when an app switch
96// key is on the way. This is used to preempt input dispatch and drop input events
97// when an application takes too long to respond and the user has pressed an app switch key.
Michael Wright2b3c3302018-03-02 17:19:13 +000098constexpr nsecs_t APP_SWITCH_TIMEOUT = 500 * 1000000LL; // 0.5sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080099
100// Amount of time to allow for an event to be dispatched (measured since its eventTime)
101// before considering it stale and dropping it.
Michael Wright2b3c3302018-03-02 17:19:13 +0000102constexpr nsecs_t STALE_EVENT_TIMEOUT = 10000 * 1000000LL; // 10sec
Michael Wrightd02c5b62014-02-10 15:10:22 -0800103
Michael Wrightd02c5b62014-02-10 15:10:22 -0800104// Log a warning when an event takes longer than this to process, even if an ANR does not occur.
Michael Wright2b3c3302018-03-02 17:19:13 +0000105constexpr nsecs_t SLOW_EVENT_PROCESSING_WARNING_TIMEOUT = 2000 * 1000000LL; // 2sec
106
107// Log a warning when an interception call takes longer than this to process.
108constexpr std::chrono::milliseconds SLOW_INTERCEPTION_THRESHOLD = 50ms;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800109
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700110// Additional key latency in case a connection is still processing some motion events.
111// This will help with the case when a user touched a button that opens a new window,
112// and gives us the chance to dispatch the key to this new window.
113constexpr std::chrono::nanoseconds KEY_WAITING_FOR_EVENTS_TIMEOUT = 500ms;
114
Michael Wrightd02c5b62014-02-10 15:10:22 -0800115// Number of recent events to keep for debugging purposes.
Michael Wright2b3c3302018-03-02 17:19:13 +0000116constexpr size_t RECENT_QUEUE_MAX_SIZE = 10;
117
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +0000118// Event log tags. See EventLogTags.logtags for reference
119constexpr int LOGTAG_INPUT_INTERACTION = 62000;
120constexpr int LOGTAG_INPUT_FOCUS = 62001;
121
Michael Wrightd02c5b62014-02-10 15:10:22 -0800122static inline nsecs_t now() {
123 return systemTime(SYSTEM_TIME_MONOTONIC);
124}
125
126static inline const char* toString(bool value) {
127 return value ? "true" : "false";
128}
129
130static inline int32_t getMotionEventActionPointerIndex(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700131 return (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) >>
132 AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800133}
134
135static bool isValidKeyAction(int32_t action) {
136 switch (action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700137 case AKEY_EVENT_ACTION_DOWN:
138 case AKEY_EVENT_ACTION_UP:
139 return true;
140 default:
141 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800142 }
143}
144
145static bool validateKeyEvent(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700146 if (!isValidKeyAction(action)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800147 ALOGE("Key event has invalid action code 0x%x", action);
148 return false;
149 }
150 return true;
151}
152
Michael Wright7b159c92015-05-14 14:48:03 +0100153static bool isValidMotionAction(int32_t action, int32_t actionButton, int32_t pointerCount) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800154 switch (action & AMOTION_EVENT_ACTION_MASK) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700155 case AMOTION_EVENT_ACTION_DOWN:
156 case AMOTION_EVENT_ACTION_UP:
157 case AMOTION_EVENT_ACTION_CANCEL:
158 case AMOTION_EVENT_ACTION_MOVE:
159 case AMOTION_EVENT_ACTION_OUTSIDE:
160 case AMOTION_EVENT_ACTION_HOVER_ENTER:
161 case AMOTION_EVENT_ACTION_HOVER_MOVE:
162 case AMOTION_EVENT_ACTION_HOVER_EXIT:
163 case AMOTION_EVENT_ACTION_SCROLL:
164 return true;
165 case AMOTION_EVENT_ACTION_POINTER_DOWN:
166 case AMOTION_EVENT_ACTION_POINTER_UP: {
167 int32_t index = getMotionEventActionPointerIndex(action);
168 return index >= 0 && index < pointerCount;
169 }
170 case AMOTION_EVENT_ACTION_BUTTON_PRESS:
171 case AMOTION_EVENT_ACTION_BUTTON_RELEASE:
172 return actionButton != 0;
173 default:
174 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800175 }
176}
177
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -0500178static int64_t millis(std::chrono::nanoseconds t) {
179 return std::chrono::duration_cast<std::chrono::milliseconds>(t).count();
180}
181
Michael Wright7b159c92015-05-14 14:48:03 +0100182static bool validateMotionEvent(int32_t action, int32_t actionButton, size_t pointerCount,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700183 const PointerProperties* pointerProperties) {
184 if (!isValidMotionAction(action, actionButton, pointerCount)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800185 ALOGE("Motion event has invalid action code 0x%x", action);
186 return false;
187 }
188 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
Narayan Kamath37764c72014-03-27 14:21:09 +0000189 ALOGE("Motion event has invalid pointer count %zu; value must be between 1 and %d.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700190 pointerCount, MAX_POINTERS);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800191 return false;
192 }
193 BitSet32 pointerIdBits;
194 for (size_t i = 0; i < pointerCount; i++) {
195 int32_t id = pointerProperties[i].id;
196 if (id < 0 || id > MAX_POINTER_ID) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700197 ALOGE("Motion event has invalid pointer id %d; value must be between 0 and %d", id,
198 MAX_POINTER_ID);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800199 return false;
200 }
201 if (pointerIdBits.hasBit(id)) {
202 ALOGE("Motion event has duplicate pointer id %d", id);
203 return false;
204 }
205 pointerIdBits.markBit(id);
206 }
207 return true;
208}
209
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000210static std::string dumpRegion(const Region& region) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800211 if (region.isEmpty()) {
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000212 return "<empty>";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800213 }
214
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000215 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800216 bool first = true;
217 Region::const_iterator cur = region.begin();
218 Region::const_iterator const tail = region.end();
219 while (cur != tail) {
220 if (first) {
221 first = false;
222 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800223 dump += "|";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800224 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800225 dump += StringPrintf("[%d,%d][%d,%d]", cur->left, cur->top, cur->right, cur->bottom);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800226 cur++;
227 }
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000228 return dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800229}
230
Siarhei Vishniakou14411c92020-09-18 21:15:05 -0500231static std::string dumpQueue(const std::deque<DispatchEntry*>& queue, nsecs_t currentTime) {
232 constexpr size_t maxEntries = 50; // max events to print
233 constexpr size_t skipBegin = maxEntries / 2;
234 const size_t skipEnd = queue.size() - maxEntries / 2;
235 // skip from maxEntries / 2 ... size() - maxEntries/2
236 // only print from 0 .. skipBegin and then from skipEnd .. size()
237
238 std::string dump;
239 for (size_t i = 0; i < queue.size(); i++) {
240 const DispatchEntry& entry = *queue[i];
241 if (i >= skipBegin && i < skipEnd) {
242 dump += StringPrintf(INDENT4 "<skipped %zu entries>\n", skipEnd - skipBegin);
243 i = skipEnd - 1; // it will be incremented to "skipEnd" by 'continue'
244 continue;
245 }
246 dump.append(INDENT4);
247 dump += entry.eventEntry->getDescription();
248 dump += StringPrintf(", seq=%" PRIu32
249 ", targetFlags=0x%08x, resolvedAction=%d, age=%" PRId64 "ms",
250 entry.seq, entry.targetFlags, entry.resolvedAction,
251 ns2ms(currentTime - entry.eventEntry->eventTime));
252 if (entry.deliveryTime != 0) {
253 // This entry was delivered, so add information on how long we've been waiting
254 dump += StringPrintf(", wait=%" PRId64 "ms", ns2ms(currentTime - entry.deliveryTime));
255 }
256 dump.append("\n");
257 }
258 return dump;
259}
260
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700261/**
262 * Find the entry in std::unordered_map by key, and return it.
263 * If the entry is not found, return a default constructed entry.
264 *
265 * Useful when the entries are vectors, since an empty vector will be returned
266 * if the entry is not found.
267 * Also useful when the entries are sp<>. If an entry is not found, nullptr is returned.
268 */
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700269template <typename K, typename V>
270static V getValueByKey(const std::unordered_map<K, V>& map, K key) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700271 auto it = map.find(key);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700272 return it != map.end() ? it->second : V{};
Tiger Huang721e26f2018-07-24 22:26:19 +0800273}
274
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700275/**
276 * Find the entry in std::unordered_map by value, and remove it.
277 * If more than one entry has the same value, then all matching
278 * key-value pairs will be removed.
279 *
280 * Return true if at least one value has been removed.
281 */
282template <typename K, typename V>
283static bool removeByValue(std::unordered_map<K, V>& map, const V& value) {
284 bool removed = false;
285 for (auto it = map.begin(); it != map.end();) {
286 if (it->second == value) {
287 it = map.erase(it);
288 removed = true;
289 } else {
290 it++;
291 }
292 }
293 return removed;
294}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800295
Vishnu Nair958da932020-08-21 17:12:37 -0700296/**
297 * Find the entry in std::unordered_map by key and return the value as an optional.
298 */
299template <typename K, typename V>
300static std::optional<V> getOptionalValueByKey(const std::unordered_map<K, V>& map, K key) {
301 auto it = map.find(key);
302 return it != map.end() ? std::optional<V>{it->second} : std::nullopt;
303}
304
chaviwaf87b3e2019-10-01 16:59:28 -0700305static bool haveSameToken(const sp<InputWindowHandle>& first, const sp<InputWindowHandle>& second) {
306 if (first == second) {
307 return true;
308 }
309
310 if (first == nullptr || second == nullptr) {
311 return false;
312 }
313
314 return first->getToken() == second->getToken();
315}
316
Siarhei Vishniakouadfd4fa2019-12-20 11:02:58 -0800317static bool isStaleEvent(nsecs_t currentTime, const EventEntry& entry) {
318 return currentTime - entry.eventTime >= STALE_EVENT_TIMEOUT;
319}
320
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000321static std::unique_ptr<DispatchEntry> createDispatchEntry(const InputTarget& inputTarget,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700322 std::shared_ptr<EventEntry> eventEntry,
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000323 int32_t inputTargetFlags) {
chaviw1ff3d1e2020-07-01 15:53:47 -0700324 if (inputTarget.useDefaultPointerTransform()) {
325 const ui::Transform& transform = inputTarget.getDefaultPointerTransform();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700326 return std::make_unique<DispatchEntry>(eventEntry, inputTargetFlags, transform,
chaviw1ff3d1e2020-07-01 15:53:47 -0700327 inputTarget.globalScaleFactor);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000328 }
329
330 ALOG_ASSERT(eventEntry->type == EventEntry::Type::MOTION);
331 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
332
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700333 std::vector<PointerCoords> pointerCoords;
334 pointerCoords.resize(motionEntry.pointerCount);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000335
336 // Use the first pointer information to normalize all other pointers. This could be any pointer
337 // as long as all other pointers are normalized to the same value and the final DispatchEntry
chaviw1ff3d1e2020-07-01 15:53:47 -0700338 // uses the transform for the normalized pointer.
339 const ui::Transform& firstPointerTransform =
340 inputTarget.pointerTransforms[inputTarget.pointerIds.firstMarkedBit()];
341 ui::Transform inverseFirstTransform = firstPointerTransform.inverse();
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000342
343 // Iterate through all pointers in the event to normalize against the first.
344 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.pointerCount; pointerIndex++) {
345 const PointerProperties& pointerProperties = motionEntry.pointerProperties[pointerIndex];
346 uint32_t pointerId = uint32_t(pointerProperties.id);
chaviw1ff3d1e2020-07-01 15:53:47 -0700347 const ui::Transform& currTransform = inputTarget.pointerTransforms[pointerId];
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000348
349 pointerCoords[pointerIndex].copyFrom(motionEntry.pointerCoords[pointerIndex]);
chaviw1ff3d1e2020-07-01 15:53:47 -0700350 // First, apply the current pointer's transform to update the coordinates into
351 // window space.
352 pointerCoords[pointerIndex].transform(currTransform);
353 // Next, apply the inverse transform of the normalized coordinates so the
354 // current coordinates are transformed into the normalized coordinate space.
355 pointerCoords[pointerIndex].transform(inverseFirstTransform);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000356 }
357
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700358 std::unique_ptr<MotionEntry> combinedMotionEntry =
359 std::make_unique<MotionEntry>(motionEntry.id, motionEntry.eventTime,
360 motionEntry.deviceId, motionEntry.source,
361 motionEntry.displayId, motionEntry.policyFlags,
362 motionEntry.action, motionEntry.actionButton,
363 motionEntry.flags, motionEntry.metaState,
364 motionEntry.buttonState, motionEntry.classification,
365 motionEntry.edgeFlags, motionEntry.xPrecision,
366 motionEntry.yPrecision, motionEntry.xCursorPosition,
367 motionEntry.yCursorPosition, motionEntry.downTime,
368 motionEntry.pointerCount, motionEntry.pointerProperties,
369 pointerCoords.data(), 0 /* xOffset */, 0 /* yOffset */);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000370
371 if (motionEntry.injectionState) {
372 combinedMotionEntry->injectionState = motionEntry.injectionState;
373 combinedMotionEntry->injectionState->refCount += 1;
374 }
375
376 std::unique_ptr<DispatchEntry> dispatchEntry =
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700377 std::make_unique<DispatchEntry>(std::move(combinedMotionEntry), inputTargetFlags,
378 firstPointerTransform, inputTarget.globalScaleFactor);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000379 return dispatchEntry;
380}
381
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -0700382static void addGestureMonitors(const std::vector<Monitor>& monitors,
383 std::vector<TouchedMonitor>& outTouchedMonitors, float xOffset = 0,
384 float yOffset = 0) {
385 if (monitors.empty()) {
386 return;
387 }
388 outTouchedMonitors.reserve(monitors.size() + outTouchedMonitors.size());
389 for (const Monitor& monitor : monitors) {
390 outTouchedMonitors.emplace_back(monitor, xOffset, yOffset);
391 }
392}
393
Garfield Tan15601662020-09-22 15:32:38 -0700394static status_t openInputChannelPair(const std::string& name,
395 std::shared_ptr<InputChannel>& serverChannel,
396 std::unique_ptr<InputChannel>& clientChannel) {
397 std::unique_ptr<InputChannel> uniqueServerChannel;
398 status_t result = InputChannel::openInputChannelPair(name, uniqueServerChannel, clientChannel);
399
400 serverChannel = std::move(uniqueServerChannel);
401 return result;
402}
403
Vishnu Nair958da932020-08-21 17:12:37 -0700404const char* InputDispatcher::typeToString(InputDispatcher::FocusResult result) {
405 switch (result) {
406 case InputDispatcher::FocusResult::OK:
407 return "Ok";
408 case InputDispatcher::FocusResult::NO_WINDOW:
409 return "Window not found";
410 case InputDispatcher::FocusResult::NOT_FOCUSABLE:
411 return "Window not focusable";
412 case InputDispatcher::FocusResult::NOT_VISIBLE:
413 return "Window not visible";
414 }
415}
416
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500417template <typename T>
418static bool sharedPointersEqual(const std::shared_ptr<T>& lhs, const std::shared_ptr<T>& rhs) {
419 if (lhs == nullptr && rhs == nullptr) {
420 return true;
421 }
422 if (lhs == nullptr || rhs == nullptr) {
423 return false;
424 }
425 return *lhs == *rhs;
426}
427
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000428static sp<IPlatformCompatNative> getCompatService() {
429 sp<IBinder> service(defaultServiceManager()->getService(String16("platform_compat_native")));
430 if (service == nullptr) {
431 ALOGE("Failed to link to compat service");
432 return nullptr;
433 }
434 return interface_cast<IPlatformCompatNative>(service);
435}
436
Michael Wrightd02c5b62014-02-10 15:10:22 -0800437// --- InputDispatcher ---
438
Garfield Tan00f511d2019-06-12 16:55:40 -0700439InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy)
440 : mPolicy(policy),
441 mPendingEvent(nullptr),
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700442 mLastDropReason(DropReason::NOT_DROPPED),
Garfield Tanff1f1bb2020-01-28 13:24:04 -0800443 mIdGenerator(IdGenerator::Source::INPUT_DISPATCHER),
Garfield Tan00f511d2019-06-12 16:55:40 -0700444 mAppSwitchSawKeyDown(false),
445 mAppSwitchDueTime(LONG_LONG_MAX),
446 mNextUnblockedEvent(nullptr),
447 mDispatchEnabled(false),
448 mDispatchFrozen(false),
449 mInputFilterEnabled(false),
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -0800450 // mInTouchMode will be initialized by the WindowManager to the default device config.
451 // To avoid leaking stack in case that call never comes, and for tests,
452 // initialize it here anyways.
453 mInTouchMode(true),
Bernardo Rufinoea97d182020-08-19 14:43:14 +0100454 mMaximumObscuringOpacityForTouch(1.0f),
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000455 mFocusedDisplayId(ADISPLAY_ID_DEFAULT),
Prabir Pradhan99987712020-11-10 18:43:05 -0800456 mFocusedWindowRequestedPointerCapture(false),
457 mWindowTokenWithPointerCapture(nullptr),
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000458 mCompatService(getCompatService()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800459 mLooper = new Looper(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800460 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800461
Yi Kong9b14ac62018-07-17 13:48:38 -0700462 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800463
464 policy->getDispatcherConfiguration(&mConfig);
465}
466
467InputDispatcher::~InputDispatcher() {
468 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800469 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800470
471 resetKeyRepeatLocked();
472 releasePendingEventLocked();
473 drainInboundQueueLocked();
474 }
475
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700476 while (!mConnectionsByFd.empty()) {
477 sp<Connection> connection = mConnectionsByFd.begin()->second;
Garfield Tan15601662020-09-22 15:32:38 -0700478 removeInputChannel(connection->inputChannel->getConnectionToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800479 }
480}
481
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700482status_t InputDispatcher::start() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700483 if (mThread) {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700484 return ALREADY_EXISTS;
485 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700486 mThread = std::make_unique<InputThread>(
487 "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
488 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700489}
490
491status_t InputDispatcher::stop() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700492 if (mThread && mThread->isCallingThread()) {
493 ALOGE("InputDispatcher cannot be stopped from its own thread!");
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700494 return INVALID_OPERATION;
495 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700496 mThread.reset();
497 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700498}
499
Michael Wrightd02c5b62014-02-10 15:10:22 -0800500void InputDispatcher::dispatchOnce() {
501 nsecs_t nextWakeupTime = LONG_LONG_MAX;
502 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800503 std::scoped_lock _l(mLock);
504 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800505
506 // Run a dispatch loop if there are no pending commands.
507 // The dispatch loop might enqueue commands to run afterwards.
508 if (!haveCommandsLocked()) {
509 dispatchOnceInnerLocked(&nextWakeupTime);
510 }
511
512 // Run all pending commands if there are any.
513 // If any commands were run then force the next poll to wake up immediately.
514 if (runCommandsLockedInterruptible()) {
515 nextWakeupTime = LONG_LONG_MIN;
516 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800517
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700518 // If we are still waiting for ack on some events,
519 // we might have to wake up earlier to check if an app is anr'ing.
520 const nsecs_t nextAnrCheck = processAnrsLocked();
521 nextWakeupTime = std::min(nextWakeupTime, nextAnrCheck);
522
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800523 // We are about to enter an infinitely long sleep, because we have no commands or
524 // pending or queued events
525 if (nextWakeupTime == LONG_LONG_MAX) {
526 mDispatcherEnteredIdle.notify_all();
527 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800528 } // release lock
529
530 // Wait for callback or timeout or wake. (make sure we round up, not down)
531 nsecs_t currentTime = now();
532 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
533 mLooper->pollOnce(timeoutMillis);
534}
535
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700536/**
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500537 * Raise ANR if there is no focused window.
538 * Before the ANR is raised, do a final state check:
539 * 1. The currently focused application must be the same one we are waiting for.
540 * 2. Ensure we still don't have a focused window.
541 */
542void InputDispatcher::processNoFocusedWindowAnrLocked() {
543 // Check if the application that we are waiting for is still focused.
544 std::shared_ptr<InputApplicationHandle> focusedApplication =
545 getValueByKey(mFocusedApplicationHandlesByDisplay, mAwaitedApplicationDisplayId);
546 if (focusedApplication == nullptr ||
547 focusedApplication->getApplicationToken() !=
548 mAwaitedFocusedApplication->getApplicationToken()) {
549 // Unexpected because we should have reset the ANR timer when focused application changed
550 ALOGE("Waited for a focused window, but focused application has already changed to %s",
551 focusedApplication->getName().c_str());
552 return; // The focused application has changed.
553 }
554
555 const sp<InputWindowHandle>& focusedWindowHandle =
556 getFocusedWindowHandleLocked(mAwaitedApplicationDisplayId);
557 if (focusedWindowHandle != nullptr) {
558 return; // We now have a focused window. No need for ANR.
559 }
560 onAnrLocked(mAwaitedFocusedApplication);
561}
562
563/**
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700564 * Check if any of the connections' wait queues have events that are too old.
565 * If we waited for events to be ack'ed for more than the window timeout, raise an ANR.
566 * Return the time at which we should wake up next.
567 */
568nsecs_t InputDispatcher::processAnrsLocked() {
569 const nsecs_t currentTime = now();
570 nsecs_t nextAnrCheck = LONG_LONG_MAX;
571 // Check if we are waiting for a focused window to appear. Raise ANR if waited too long
572 if (mNoFocusedWindowTimeoutTime.has_value() && mAwaitedFocusedApplication != nullptr) {
573 if (currentTime >= *mNoFocusedWindowTimeoutTime) {
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500574 processNoFocusedWindowAnrLocked();
Chris Yea209fde2020-07-22 13:54:51 -0700575 mAwaitedFocusedApplication.reset();
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500576 mNoFocusedWindowTimeoutTime = std::nullopt;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700577 return LONG_LONG_MIN;
578 } else {
Siarhei Vishniakou38a6d272020-10-20 20:29:33 -0500579 // Keep waiting. We will drop the event when mNoFocusedWindowTimeoutTime comes.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700580 nextAnrCheck = *mNoFocusedWindowTimeoutTime;
581 }
582 }
583
584 // Check if any connection ANRs are due
585 nextAnrCheck = std::min(nextAnrCheck, mAnrTracker.firstTimeout());
586 if (currentTime < nextAnrCheck) { // most likely scenario
587 return nextAnrCheck; // everything is normal. Let's check again at nextAnrCheck
588 }
589
590 // If we reached here, we have an unresponsive connection.
591 sp<Connection> connection = getConnectionLocked(mAnrTracker.firstToken());
592 if (connection == nullptr) {
593 ALOGE("Could not find connection for entry %" PRId64, mAnrTracker.firstTimeout());
594 return nextAnrCheck;
595 }
596 connection->responsive = false;
597 // Stop waking up for this unresponsive connection
598 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -0500599 onAnrLocked(*connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700600 return LONG_LONG_MIN;
601}
602
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500603std::chrono::nanoseconds InputDispatcher::getDispatchingTimeoutLocked(const sp<IBinder>& token) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700604 sp<InputWindowHandle> window = getWindowHandleLocked(token);
605 if (window != nullptr) {
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500606 return window->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700607 }
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500608 return DEFAULT_INPUT_DISPATCHING_TIMEOUT;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700609}
610
Michael Wrightd02c5b62014-02-10 15:10:22 -0800611void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
612 nsecs_t currentTime = now();
613
Jeff Browndc5992e2014-04-11 01:27:26 -0700614 // Reset the key repeat timer whenever normal dispatch is suspended while the
615 // device is in a non-interactive state. This is to ensure that we abort a key
616 // repeat if the device is just coming out of sleep.
617 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800618 resetKeyRepeatLocked();
619 }
620
621 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
622 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +0100623 if (DEBUG_FOCUS) {
624 ALOGD("Dispatch frozen. Waiting some more.");
625 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800626 return;
627 }
628
629 // Optimize latency of app switches.
630 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
631 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
632 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
633 if (mAppSwitchDueTime < *nextWakeupTime) {
634 *nextWakeupTime = mAppSwitchDueTime;
635 }
636
637 // Ready to start a new event.
638 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700639 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700640 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800641 if (isAppSwitchDue) {
642 // The inbound queue is empty so the app switch key we were waiting
643 // for will never arrive. Stop waiting for it.
644 resetPendingAppSwitchLocked(false);
645 isAppSwitchDue = false;
646 }
647
648 // Synthesize a key repeat if appropriate.
649 if (mKeyRepeatState.lastKeyEntry) {
650 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
651 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
652 } else {
653 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
654 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
655 }
656 }
657 }
658
659 // Nothing to do if there is no pending event.
660 if (!mPendingEvent) {
661 return;
662 }
663 } else {
664 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700665 mPendingEvent = mInboundQueue.front();
666 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800667 traceInboundQueueLengthLocked();
668 }
669
670 // Poke user activity for this event.
671 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700672 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800673 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800674 }
675
676 // Now we have an event to dispatch.
677 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700678 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800679 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700680 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800681 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700682 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800683 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700684 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800685 }
686
687 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700688 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800689 }
690
691 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700692 case EventEntry::Type::CONFIGURATION_CHANGED: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700693 const ConfigurationChangedEntry& typedEntry =
694 static_cast<const ConfigurationChangedEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700695 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700696 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700697 break;
698 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800699
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700700 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700701 const DeviceResetEntry& typedEntry =
702 static_cast<const DeviceResetEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700703 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700704 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700705 break;
706 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800707
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100708 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700709 std::shared_ptr<FocusEntry> typedEntry =
710 std::static_pointer_cast<FocusEntry>(mPendingEvent);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100711 dispatchFocusLocked(currentTime, typedEntry);
712 done = true;
713 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
714 break;
715 }
716
Prabir Pradhan99987712020-11-10 18:43:05 -0800717 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
718 const auto typedEntry =
719 std::static_pointer_cast<PointerCaptureChangedEntry>(mPendingEvent);
720 dispatchPointerCaptureChangedLocked(currentTime, typedEntry, dropReason);
721 done = true;
722 break;
723 }
724
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700725 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700726 std::shared_ptr<KeyEntry> keyEntry = std::static_pointer_cast<KeyEntry>(mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700727 if (isAppSwitchDue) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700728 if (isAppSwitchKeyEvent(*keyEntry)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700729 resetPendingAppSwitchLocked(true);
730 isAppSwitchDue = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700731 } else if (dropReason == DropReason::NOT_DROPPED) {
732 dropReason = DropReason::APP_SWITCH;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700733 }
734 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700735 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *keyEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700736 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700737 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700738 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
739 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700740 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700741 done = dispatchKeyLocked(currentTime, keyEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700742 break;
743 }
744
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700745 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700746 std::shared_ptr<MotionEntry> motionEntry =
747 std::static_pointer_cast<MotionEntry>(mPendingEvent);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700748 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
749 dropReason = DropReason::APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800750 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700751 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *motionEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700752 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700753 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700754 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
755 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700756 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700757 done = dispatchMotionLocked(currentTime, motionEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700758 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800759 }
Chris Yef59a2f42020-10-16 12:55:26 -0700760
761 case EventEntry::Type::SENSOR: {
762 std::shared_ptr<SensorEntry> sensorEntry =
763 std::static_pointer_cast<SensorEntry>(mPendingEvent);
764 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
765 dropReason = DropReason::APP_SWITCH;
766 }
767 // Sensor timestamps use SYSTEM_TIME_BOOTTIME time base, so we can't use
768 // 'currentTime' here, get SYSTEM_TIME_BOOTTIME instead.
769 nsecs_t bootTime = systemTime(SYSTEM_TIME_BOOTTIME);
770 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(bootTime, *sensorEntry)) {
771 dropReason = DropReason::STALE;
772 }
773 dispatchSensorLocked(currentTime, sensorEntry, &dropReason, nextWakeupTime);
774 done = true;
775 break;
776 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800777 }
778
779 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700780 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700781 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800782 }
Michael Wright3a981722015-06-10 15:26:13 +0100783 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800784
785 releasePendingEventLocked();
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700786 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -0800787 }
788}
789
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700790/**
791 * Return true if the events preceding this incoming motion event should be dropped
792 * Return false otherwise (the default behaviour)
793 */
794bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700795 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700796 (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700797
798 // Optimize case where the current application is unresponsive and the user
799 // decides to touch a window in a different application.
800 // If the application takes too long to catch up then we drop all events preceding
801 // the touch into the other window.
802 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700803 int32_t displayId = motionEntry.displayId;
804 int32_t x = static_cast<int32_t>(
805 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
806 int32_t y = static_cast<int32_t>(
807 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
808 sp<InputWindowHandle> touchedWindowHandle =
809 findTouchedWindowAtLocked(displayId, x, y, nullptr);
810 if (touchedWindowHandle != nullptr &&
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700811 touchedWindowHandle->getApplicationToken() !=
812 mAwaitedFocusedApplication->getApplicationToken()) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700813 // User touched a different application than the one we are waiting on.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700814 ALOGI("Pruning input queue because user touched a different application while waiting "
815 "for %s",
816 mAwaitedFocusedApplication->getName().c_str());
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700817 return true;
818 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700819
820 // Alternatively, maybe there's a gesture monitor that could handle this event
821 std::vector<TouchedMonitor> gestureMonitors =
822 findTouchedGestureMonitorsLocked(displayId, {});
823 for (TouchedMonitor& gestureMonitor : gestureMonitors) {
824 sp<Connection> connection =
825 getConnectionLocked(gestureMonitor.monitor.inputChannel->getConnectionToken());
Siarhei Vishniakou34ed4d42020-06-18 00:43:02 +0000826 if (connection != nullptr && connection->responsive) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700827 // This monitor could take more input. Drop all events preceding this
828 // event, so that gesture monitor could get a chance to receive the stream
829 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
830 "responsive gesture monitor that may handle the event",
831 mAwaitedFocusedApplication->getName().c_str());
832 return true;
833 }
834 }
835 }
836
837 // Prevent getting stuck: if we have a pending key event, and some motion events that have not
838 // yet been processed by some connections, the dispatcher will wait for these motion
839 // events to be processed before dispatching the key event. This is because these motion events
840 // may cause a new window to be launched, which the user might expect to receive focus.
841 // To prevent waiting forever for such events, just send the key to the currently focused window
842 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
843 ALOGD("Received a new pointer down event, stop waiting for events to process and "
844 "just send the pending key event to the focused window.");
845 mKeyIsWaitingForEventsTimeout = now();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700846 }
847 return false;
848}
849
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700850bool InputDispatcher::enqueueInboundEventLocked(std::unique_ptr<EventEntry> newEntry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700851 bool needWake = mInboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700852 mInboundQueue.push_back(std::move(newEntry));
853 EventEntry& entry = *(mInboundQueue.back());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800854 traceInboundQueueLengthLocked();
855
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700856 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700857 case EventEntry::Type::KEY: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700858 // Optimize app switch latency.
859 // If the application takes too long to catch up then we drop all events preceding
860 // the app switch key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700861 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700862 if (isAppSwitchKeyEvent(keyEntry)) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700863 if (keyEntry.action == AKEY_EVENT_ACTION_DOWN) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700864 mAppSwitchSawKeyDown = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700865 } else if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700866 if (mAppSwitchSawKeyDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800867#if DEBUG_APP_SWITCH
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700868 ALOGD("App switch is pending!");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800869#endif
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700870 mAppSwitchDueTime = keyEntry.eventTime + APP_SWITCH_TIMEOUT;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700871 mAppSwitchSawKeyDown = false;
872 needWake = true;
873 }
874 }
875 }
876 break;
877 }
878
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700879 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700880 if (shouldPruneInboundQueueLocked(static_cast<MotionEntry&>(entry))) {
881 mNextUnblockedEvent = mInboundQueue.back();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700882 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800883 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700884 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800885 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100886 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700887 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
888 break;
889 }
890 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -0800891 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -0700892 case EventEntry::Type::SENSOR:
Prabir Pradhan99987712020-11-10 18:43:05 -0800893 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700894 // nothing to do
895 break;
896 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800897 }
898
899 return needWake;
900}
901
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700902void InputDispatcher::addRecentEventLocked(std::shared_ptr<EventEntry> entry) {
Chris Yef59a2f42020-10-16 12:55:26 -0700903 // Do not store sensor event in recent queue to avoid flooding the queue.
904 if (entry->type != EventEntry::Type::SENSOR) {
905 mRecentQueue.push_back(entry);
906 }
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700907 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700908 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800909 }
910}
911
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700912sp<InputWindowHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, int32_t x,
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700913 int32_t y, TouchState* touchState,
914 bool addOutsideTargets,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700915 bool addPortalWindows) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700916 if ((addPortalWindows || addOutsideTargets) && touchState == nullptr) {
917 LOG_ALWAYS_FATAL(
918 "Must provide a valid touch state if adding portal windows or outside targets");
919 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800920 // Traverse windows from front to back to find touched window.
Vishnu Nairad321cd2020-08-20 16:40:21 -0700921 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800922 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800923 const InputWindowInfo* windowInfo = windowHandle->getInfo();
924 if (windowInfo->displayId == displayId) {
Michael Wright44753b12020-07-08 13:48:11 +0100925 auto flags = windowInfo->flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800926
927 if (windowInfo->visible) {
Michael Wright44753b12020-07-08 13:48:11 +0100928 if (!flags.test(InputWindowInfo::Flag::NOT_TOUCHABLE)) {
929 bool isTouchModal = !flags.test(InputWindowInfo::Flag::NOT_FOCUSABLE) &&
930 !flags.test(InputWindowInfo::Flag::NOT_TOUCH_MODAL);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800931 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800932 int32_t portalToDisplayId = windowInfo->portalToDisplayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700933 if (portalToDisplayId != ADISPLAY_ID_NONE &&
934 portalToDisplayId != displayId) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800935 if (addPortalWindows) {
936 // For the monitoring channels of the display.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700937 touchState->addPortalWindow(windowHandle);
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800938 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700939 return findTouchedWindowAtLocked(portalToDisplayId, x, y, touchState,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700940 addOutsideTargets, addPortalWindows);
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800941 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800942 // Found window.
943 return windowHandle;
944 }
945 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800946
Michael Wright44753b12020-07-08 13:48:11 +0100947 if (addOutsideTargets && flags.test(InputWindowInfo::Flag::WATCH_OUTSIDE_TOUCH)) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700948 touchState->addOrUpdateWindow(windowHandle,
949 InputTarget::FLAG_DISPATCH_AS_OUTSIDE,
950 BitSet32(0));
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800951 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800952 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800953 }
954 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700955 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800956}
957
Garfield Tane84e6f92019-08-29 17:28:41 -0700958std::vector<TouchedMonitor> InputDispatcher::findTouchedGestureMonitorsLocked(
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -0700959 int32_t displayId, const std::vector<sp<InputWindowHandle>>& portalWindows) const {
Michael Wright3dd60e22019-03-27 22:06:44 +0000960 std::vector<TouchedMonitor> touchedMonitors;
961
962 std::vector<Monitor> monitors = getValueByKey(mGestureMonitorsByDisplay, displayId);
963 addGestureMonitors(monitors, touchedMonitors);
964 for (const sp<InputWindowHandle>& portalWindow : portalWindows) {
965 const InputWindowInfo* windowInfo = portalWindow->getInfo();
966 monitors = getValueByKey(mGestureMonitorsByDisplay, windowInfo->portalToDisplayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700967 addGestureMonitors(monitors, touchedMonitors, -windowInfo->frameLeft,
968 -windowInfo->frameTop);
Michael Wright3dd60e22019-03-27 22:06:44 +0000969 }
970 return touchedMonitors;
971}
972
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700973void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800974 const char* reason;
975 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700976 case DropReason::POLICY:
Michael Wrightd02c5b62014-02-10 15:10:22 -0800977#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700978 ALOGD("Dropped event because policy consumed it.");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800979#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700980 reason = "inbound event was dropped because the policy consumed it";
981 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700982 case DropReason::DISABLED:
983 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700984 ALOGI("Dropped event because input dispatch is disabled.");
985 }
986 reason = "inbound event was dropped because input dispatch is disabled";
987 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700988 case DropReason::APP_SWITCH:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700989 ALOGI("Dropped event because of pending overdue app switch.");
990 reason = "inbound event was dropped because of pending overdue app switch";
991 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700992 case DropReason::BLOCKED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700993 ALOGI("Dropped event because the current application is not responding and the user "
994 "has started interacting with a different application.");
995 reason = "inbound event was dropped because the current application is not responding "
996 "and the user has started interacting with a different application";
997 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700998 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700999 ALOGI("Dropped event because it is stale.");
1000 reason = "inbound event was dropped because it is stale";
1001 break;
Prabir Pradhan99987712020-11-10 18:43:05 -08001002 case DropReason::NO_POINTER_CAPTURE:
1003 ALOGI("Dropped event because there is no window with Pointer Capture.");
1004 reason = "inbound event was dropped because there is no window with Pointer Capture";
1005 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001006 case DropReason::NOT_DROPPED: {
1007 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001008 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001009 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001010 }
1011
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001012 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001013 case EventEntry::Type::KEY: {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001014 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
1015 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001016 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001017 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001018 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001019 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1020 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001021 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
1022 synthesizeCancelationEventsForAllConnectionsLocked(options);
1023 } else {
1024 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
1025 synthesizeCancelationEventsForAllConnectionsLocked(options);
1026 }
1027 break;
1028 }
Chris Yef59a2f42020-10-16 12:55:26 -07001029 case EventEntry::Type::SENSOR: {
1030 break;
1031 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001032 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
1033 break;
1034 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001035 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001036 case EventEntry::Type::CONFIGURATION_CHANGED:
1037 case EventEntry::Type::DEVICE_RESET: {
Chris Yef59a2f42020-10-16 12:55:26 -07001038 LOG_ALWAYS_FATAL("Should not drop %s events", NamedEnum::string(entry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001039 break;
1040 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001041 }
1042}
1043
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001044static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001045 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
1046 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001047}
1048
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001049bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
1050 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
1051 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
1052 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001053}
1054
1055bool InputDispatcher::isAppSwitchPendingLocked() {
1056 return mAppSwitchDueTime != LONG_LONG_MAX;
1057}
1058
1059void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
1060 mAppSwitchDueTime = LONG_LONG_MAX;
1061
1062#if DEBUG_APP_SWITCH
1063 if (handled) {
1064 ALOGD("App switch has arrived.");
1065 } else {
1066 ALOGD("App switch was abandoned.");
1067 }
1068#endif
1069}
1070
Michael Wrightd02c5b62014-02-10 15:10:22 -08001071bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001072 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001073}
1074
1075bool InputDispatcher::runCommandsLockedInterruptible() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001076 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001077 return false;
1078 }
1079
1080 do {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001081 std::unique_ptr<CommandEntry> commandEntry = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001082 mCommandQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001083 Command command = commandEntry->command;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001084 command(*this, commandEntry.get()); // commands are implicitly 'LockedInterruptible'
Michael Wrightd02c5b62014-02-10 15:10:22 -08001085
1086 commandEntry->connection.clear();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001087 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001088 return true;
1089}
1090
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001091void InputDispatcher::postCommandLocked(std::unique_ptr<CommandEntry> commandEntry) {
1092 mCommandQueue.push_back(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001093}
1094
1095void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001096 while (!mInboundQueue.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001097 std::shared_ptr<EventEntry> entry = mInboundQueue.front();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001098 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001099 releaseInboundEventLocked(entry);
1100 }
1101 traceInboundQueueLengthLocked();
1102}
1103
1104void InputDispatcher::releasePendingEventLocked() {
1105 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001106 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -07001107 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001108 }
1109}
1110
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001111void InputDispatcher::releaseInboundEventLocked(std::shared_ptr<EventEntry> entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001112 InjectionState* injectionState = entry->injectionState;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001113 if (injectionState && injectionState->injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001114#if DEBUG_DISPATCH_CYCLE
1115 ALOGD("Injected inbound event was dropped.");
1116#endif
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001117 setInjectionResult(*entry, InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001118 }
1119 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001120 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001121 }
1122 addRecentEventLocked(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001123}
1124
1125void InputDispatcher::resetKeyRepeatLocked() {
1126 if (mKeyRepeatState.lastKeyEntry) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001127 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001128 }
1129}
1130
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001131std::shared_ptr<KeyEntry> InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
1132 std::shared_ptr<KeyEntry> entry = mKeyRepeatState.lastKeyEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001133
Michael Wright2e732952014-09-24 13:26:59 -07001134 uint32_t policyFlags = entry->policyFlags &
1135 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001136
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001137 std::shared_ptr<KeyEntry> newEntry =
1138 std::make_unique<KeyEntry>(mIdGenerator.nextId(), currentTime, entry->deviceId,
1139 entry->source, entry->displayId, policyFlags, entry->action,
1140 entry->flags, entry->keyCode, entry->scanCode,
1141 entry->metaState, entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001142
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001143 newEntry->syntheticRepeat = true;
1144 mKeyRepeatState.lastKeyEntry = newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001145 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001146 return newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001147}
1148
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001149bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001150 const ConfigurationChangedEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001151#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001152 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry.eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001153#endif
1154
1155 // Reset key repeating in case a keyboard device was added or removed or something.
1156 resetKeyRepeatLocked();
1157
1158 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001159 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
1160 &InputDispatcher::doNotifyConfigurationChangedLockedInterruptible);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001161 commandEntry->eventTime = entry.eventTime;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001162 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001163 return true;
1164}
1165
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001166bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime,
1167 const DeviceResetEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001168#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001169 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry.eventTime,
1170 entry.deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001171#endif
1172
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001173 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, "device was reset");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001174 options.deviceId = entry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001175 synthesizeCancelationEventsForAllConnectionsLocked(options);
1176 return true;
1177}
1178
Vishnu Nairad321cd2020-08-20 16:40:21 -07001179void InputDispatcher::enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus,
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001180 std::string_view reason) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001181 if (mPendingEvent != nullptr) {
1182 // Move the pending event to the front of the queue. This will give the chance
1183 // for the pending event to get dispatched to the newly focused window
1184 mInboundQueue.push_front(mPendingEvent);
1185 mPendingEvent = nullptr;
1186 }
1187
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001188 std::unique_ptr<FocusEntry> focusEntry =
1189 std::make_unique<FocusEntry>(mIdGenerator.nextId(), now(), windowToken, hasFocus,
1190 reason);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001191
1192 // This event should go to the front of the queue, but behind all other focus events
1193 // Find the last focus event, and insert right after it
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001194 std::deque<std::shared_ptr<EventEntry>>::reverse_iterator it =
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001195 std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001196 [](const std::shared_ptr<EventEntry>& event) {
1197 return event->type == EventEntry::Type::FOCUS;
1198 });
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001199
1200 // Maintain the order of focus events. Insert the entry after all other focus events.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001201 mInboundQueue.insert(it.base(), std::move(focusEntry));
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001202}
1203
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001204void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime, std::shared_ptr<FocusEntry> entry) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05001205 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001206 if (channel == nullptr) {
1207 return; // Window has gone away
1208 }
1209 InputTarget target;
1210 target.inputChannel = channel;
1211 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1212 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001213 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
1214 channel->getName();
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001215 std::string reason = std::string("reason=").append(entry->reason);
1216 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001217 dispatchEventLocked(currentTime, entry, {target});
1218}
1219
Prabir Pradhan99987712020-11-10 18:43:05 -08001220void InputDispatcher::dispatchPointerCaptureChangedLocked(
1221 nsecs_t currentTime, const std::shared_ptr<PointerCaptureChangedEntry>& entry,
1222 DropReason& dropReason) {
1223 const bool haveWindowWithPointerCapture = mWindowTokenWithPointerCapture != nullptr;
1224 if (entry->pointerCaptureEnabled == haveWindowWithPointerCapture) {
1225 LOG_ALWAYS_FATAL_IF(mFocusedWindowRequestedPointerCapture,
1226 "The Pointer Capture state has already been dispatched to the window.");
1227 // Pointer capture was already forcefully disabled because of focus change.
1228 dropReason = DropReason::NOT_DROPPED;
1229 return;
1230 }
1231
1232 // Set drop reason for early returns
1233 dropReason = DropReason::NO_POINTER_CAPTURE;
1234
1235 sp<IBinder> token;
1236 if (entry->pointerCaptureEnabled) {
1237 // Enable Pointer Capture
1238 if (!mFocusedWindowRequestedPointerCapture) {
1239 // This can happen if a window requests capture and immediately releases capture.
1240 ALOGW("No window requested Pointer Capture.");
1241 return;
1242 }
1243 token = getValueByKey(mFocusedWindowTokenByDisplay, mFocusedDisplayId);
1244 LOG_ALWAYS_FATAL_IF(!token, "Cannot find focused window for Pointer Capture.");
1245 mWindowTokenWithPointerCapture = token;
1246 } else {
1247 // Disable Pointer Capture
1248 token = mWindowTokenWithPointerCapture;
1249 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan7d030382020-12-21 07:58:35 -08001250 if (mFocusedWindowRequestedPointerCapture) {
1251 mFocusedWindowRequestedPointerCapture = false;
1252 setPointerCaptureLocked(false);
1253 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001254 }
1255
1256 auto channel = getInputChannelLocked(token);
1257 if (channel == nullptr) {
1258 // Window has gone away, clean up Pointer Capture state.
1259 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan7d030382020-12-21 07:58:35 -08001260 if (mFocusedWindowRequestedPointerCapture) {
1261 mFocusedWindowRequestedPointerCapture = false;
1262 setPointerCaptureLocked(false);
1263 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001264 return;
1265 }
1266 InputTarget target;
1267 target.inputChannel = channel;
1268 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1269 entry->dispatchInProgress = true;
1270 dispatchEventLocked(currentTime, entry, {target});
1271
1272 dropReason = DropReason::NOT_DROPPED;
1273}
1274
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001275bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, std::shared_ptr<KeyEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001276 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001277 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001278 if (!entry->dispatchInProgress) {
1279 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1280 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1281 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1282 if (mKeyRepeatState.lastKeyEntry &&
Chris Ye2ad95392020-09-01 13:44:44 -07001283 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode &&
Michael Wrightd02c5b62014-02-10 15:10:22 -08001284 // We have seen two identical key downs in a row which indicates that the device
1285 // driver is automatically generating key repeats itself. We take note of the
1286 // repeat here, but we disable our own next key repeat timer since it is clear that
1287 // we will not need to synthesize key repeats ourselves.
Chris Ye2ad95392020-09-01 13:44:44 -07001288 mKeyRepeatState.lastKeyEntry->deviceId == entry->deviceId) {
1289 // Make sure we don't get key down from a different device. If a different
1290 // device Id has same key pressed down, the new device Id will replace the
1291 // current one to hold the key repeat with repeat count reset.
1292 // In the future when got a KEY_UP on the device id, drop it and do not
1293 // stop the key repeat on current device.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001294 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1295 resetKeyRepeatLocked();
1296 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
1297 } else {
1298 // Not a repeat. Save key down state in case we do see a repeat later.
1299 resetKeyRepeatLocked();
1300 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1301 }
1302 mKeyRepeatState.lastKeyEntry = entry;
Chris Ye2ad95392020-09-01 13:44:44 -07001303 } else if (entry->action == AKEY_EVENT_ACTION_UP && mKeyRepeatState.lastKeyEntry &&
1304 mKeyRepeatState.lastKeyEntry->deviceId != entry->deviceId) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001305 // The key on device 'deviceId' is still down, do not stop key repeat
Chris Ye2ad95392020-09-01 13:44:44 -07001306#if DEBUG_INBOUND_EVENT_DETAILS
1307 ALOGD("deviceId=%d got KEY_UP as stale", entry->deviceId);
1308#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001309 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001310 resetKeyRepeatLocked();
1311 }
1312
1313 if (entry->repeatCount == 1) {
1314 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1315 } else {
1316 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1317 }
1318
1319 entry->dispatchInProgress = true;
1320
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001321 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001322 }
1323
1324 // Handle case where the policy asked us to try again later last time.
1325 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
1326 if (currentTime < entry->interceptKeyWakeupTime) {
1327 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1328 *nextWakeupTime = entry->interceptKeyWakeupTime;
1329 }
1330 return false; // wait until next wakeup
1331 }
1332 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
1333 entry->interceptKeyWakeupTime = 0;
1334 }
1335
1336 // Give the policy a chance to intercept the key.
1337 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
1338 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001339 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
Siarhei Vishniakou49a350a2019-07-26 18:44:23 -07001340 &InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible);
Vishnu Nairad321cd2020-08-20 16:40:21 -07001341 sp<IBinder> focusedWindowToken =
1342 getValueByKey(mFocusedWindowTokenByDisplay, getTargetDisplayId(*entry));
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06001343 commandEntry->connectionToken = focusedWindowToken;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001344 commandEntry->keyEntry = entry;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001345 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001346 return false; // wait for the command to run
1347 } else {
1348 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
1349 }
1350 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001351 if (*dropReason == DropReason::NOT_DROPPED) {
1352 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001353 }
1354 }
1355
1356 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001357 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001358 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001359 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1360 : InputEventInjectionResult::FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001361 mReporter->reportDroppedKey(entry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001362 return true;
1363 }
1364
1365 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001366 std::vector<InputTarget> inputTargets;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001367 InputEventInjectionResult injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001368 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001369 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001370 return false;
1371 }
1372
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001373 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001374 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001375 return true;
1376 }
1377
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001378 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001379 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001380
1381 // Dispatch the key.
1382 dispatchEventLocked(currentTime, entry, inputTargets);
1383 return true;
1384}
1385
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001386void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001387#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01001388 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001389 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1390 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001391 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1392 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
1393 entry.repeatCount, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001394#endif
1395}
1396
Chris Yef59a2f42020-10-16 12:55:26 -07001397void InputDispatcher::doNotifySensorLockedInterruptible(CommandEntry* commandEntry) {
1398 mLock.unlock();
1399
1400 const std::shared_ptr<SensorEntry>& entry = commandEntry->sensorEntry;
1401 if (entry->accuracyChanged) {
1402 mPolicy->notifySensorAccuracy(entry->deviceId, entry->sensorType, entry->accuracy);
1403 }
1404 mPolicy->notifySensorEvent(entry->deviceId, entry->sensorType, entry->accuracy,
1405 entry->hwTimestamp, entry->values);
1406 mLock.lock();
1407}
1408
1409void InputDispatcher::dispatchSensorLocked(nsecs_t currentTime, std::shared_ptr<SensorEntry> entry,
1410 DropReason* dropReason, nsecs_t* nextWakeupTime) {
1411#if DEBUG_OUTBOUND_EVENT_DETAILS
1412 ALOGD("notifySensorEvent eventTime=%" PRId64 ", hwTimestamp=%" PRId64 ", deviceId=%d, "
1413 "source=0x%x, sensorType=%s",
1414 entry->eventTime, entry->hwTimestamp, entry->deviceId, entry->source,
1415 NamedEnum::string(sensorType).c_str());
1416#endif
1417 std::unique_ptr<CommandEntry> commandEntry =
1418 std::make_unique<CommandEntry>(&InputDispatcher::doNotifySensorLockedInterruptible);
1419 commandEntry->sensorEntry = entry;
1420 postCommandLocked(std::move(commandEntry));
1421}
1422
1423bool InputDispatcher::flushSensor(int deviceId, InputDeviceSensorType sensorType) {
1424#if DEBUG_OUTBOUND_EVENT_DETAILS
1425 ALOGD("flushSensor deviceId=%d, sensorType=%s", deviceId,
1426 NamedEnum::string(sensorType).c_str());
1427#endif
1428 { // acquire lock
1429 std::scoped_lock _l(mLock);
1430
1431 for (auto it = mInboundQueue.begin(); it != mInboundQueue.end(); it++) {
1432 std::shared_ptr<EventEntry> entry = *it;
1433 if (entry->type == EventEntry::Type::SENSOR) {
1434 it = mInboundQueue.erase(it);
1435 releaseInboundEventLocked(entry);
1436 }
1437 }
1438 }
1439 return true;
1440}
1441
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001442bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, std::shared_ptr<MotionEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001443 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001444 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001445 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001446 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001447 entry->dispatchInProgress = true;
1448
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001449 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001450 }
1451
1452 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001453 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001454 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001455 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1456 : InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001457 return true;
1458 }
1459
1460 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
1461
1462 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001463 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001464
1465 bool conflictingPointerActions = false;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001466 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001467 if (isPointerEvent) {
1468 // Pointer event. (eg. touchscreen)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001469 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001470 findTouchedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001471 &conflictingPointerActions);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001472 } else {
1473 // Non touch event. (eg. trackball)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001474 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001475 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001476 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001477 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001478 return false;
1479 }
1480
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001481 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001482 if (injectionResult == InputEventInjectionResult::PERMISSION_DENIED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001483 ALOGW("Permission denied, dropping the motion (isPointer=%s)", toString(isPointerEvent));
1484 return true;
1485 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001486 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001487 CancelationOptions::Mode mode(isPointerEvent
1488 ? CancelationOptions::CANCEL_POINTER_EVENTS
1489 : CancelationOptions::CANCEL_NON_POINTER_EVENTS);
1490 CancelationOptions options(mode, "input event injection failed");
1491 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001492 return true;
1493 }
1494
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001495 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001496 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001497
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001498 if (isPointerEvent) {
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07001499 std::unordered_map<int32_t, TouchState>::iterator it =
1500 mTouchStatesByDisplay.find(entry->displayId);
1501 if (it != mTouchStatesByDisplay.end()) {
1502 const TouchState& state = it->second;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001503 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001504 // The event has gone through these portal windows, so we add monitoring targets of
1505 // the corresponding displays as well.
1506 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001507 const InputWindowInfo* windowInfo = state.portalWindows[i]->getInfo();
Michael Wright3dd60e22019-03-27 22:06:44 +00001508 addGlobalMonitoringTargetsLocked(inputTargets, windowInfo->portalToDisplayId,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001509 -windowInfo->frameLeft, -windowInfo->frameTop);
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001510 }
1511 }
1512 }
1513 }
1514
Michael Wrightd02c5b62014-02-10 15:10:22 -08001515 // Dispatch the motion.
1516 if (conflictingPointerActions) {
1517 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001518 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001519 synthesizeCancelationEventsForAllConnectionsLocked(options);
1520 }
1521 dispatchEventLocked(currentTime, entry, inputTargets);
1522 return true;
1523}
1524
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001525void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001526#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08001527 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001528 ", policyFlags=0x%x, "
1529 "action=0x%x, actionButton=0x%x, flags=0x%x, "
1530 "metaState=0x%x, buttonState=0x%x,"
1531 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001532 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1533 entry.action, entry.actionButton, entry.flags, entry.metaState, entry.buttonState,
1534 entry.edgeFlags, entry.xPrecision, entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001535
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001536 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001537 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001538 "x=%f, y=%f, pressure=%f, size=%f, "
1539 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1540 "orientation=%f",
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001541 i, entry.pointerProperties[i].id, entry.pointerProperties[i].toolType,
1542 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1543 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1544 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1545 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1546 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1547 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1548 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1549 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1550 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001551 }
1552#endif
1553}
1554
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001555void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
1556 std::shared_ptr<EventEntry> eventEntry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001557 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001558 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001559#if DEBUG_DISPATCH_CYCLE
1560 ALOGD("dispatchEventToCurrentInputTargets");
1561#endif
1562
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001563 updateInteractionTokensLocked(*eventEntry, inputTargets);
1564
Michael Wrightd02c5b62014-02-10 15:10:22 -08001565 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1566
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001567 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001568
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001569 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001570 sp<Connection> connection =
1571 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001572 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08001573 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001574 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001575 if (DEBUG_FOCUS) {
1576 ALOGD("Dropping event delivery to target with channel '%s' because it "
1577 "is no longer registered with the input dispatcher.",
1578 inputTarget.inputChannel->getName().c_str());
1579 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001580 }
1581 }
1582}
1583
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001584void InputDispatcher::cancelEventsForAnrLocked(const sp<Connection>& connection) {
1585 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
1586 // If the policy decides to close the app, we will get a channel removal event via
1587 // unregisterInputChannel, and will clean up the connection that way. We are already not
1588 // sending new pointers to the connection when it blocked, but focused events will continue to
1589 // pile up.
1590 ALOGW("Canceling events for %s because it is unresponsive",
1591 connection->inputChannel->getName().c_str());
1592 if (connection->status == Connection::STATUS_NORMAL) {
1593 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1594 "application not responding");
1595 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001596 }
1597}
1598
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001599void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001600 if (DEBUG_FOCUS) {
1601 ALOGD("Resetting ANR timeouts.");
1602 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001603
1604 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001605 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07001606 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001607}
1608
Tiger Huang721e26f2018-07-24 22:26:19 +08001609/**
1610 * Get the display id that the given event should go to. If this event specifies a valid display id,
1611 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1612 * Focused display is the display that the user most recently interacted with.
1613 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001614int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001615 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001616 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001617 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001618 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1619 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001620 break;
1621 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001622 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001623 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1624 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001625 break;
1626 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001627 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001628 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001629 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07001630 case EventEntry::Type::DEVICE_RESET:
1631 case EventEntry::Type::SENSOR: {
1632 ALOGE("%s events do not have a target display", NamedEnum::string(entry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001633 return ADISPLAY_ID_NONE;
1634 }
Tiger Huang721e26f2018-07-24 22:26:19 +08001635 }
1636 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1637}
1638
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001639bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
1640 const char* focusedWindowName) {
1641 if (mAnrTracker.empty()) {
1642 // already processed all events that we waited for
1643 mKeyIsWaitingForEventsTimeout = std::nullopt;
1644 return false;
1645 }
1646
1647 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
1648 // Start the timer
1649 ALOGD("Waiting to send key to %s because there are unprocessed events that may cause "
1650 "focus to change",
1651 focusedWindowName);
Siarhei Vishniakou70622952020-07-30 11:17:23 -05001652 mKeyIsWaitingForEventsTimeout = currentTime +
1653 std::chrono::duration_cast<std::chrono::nanoseconds>(KEY_WAITING_FOR_EVENTS_TIMEOUT)
1654 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001655 return true;
1656 }
1657
1658 // We still have pending events, and already started the timer
1659 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
1660 return true; // Still waiting
1661 }
1662
1663 // Waited too long, and some connection still hasn't processed all motions
1664 // Just send the key to the focused window
1665 ALOGW("Dispatching key to %s even though there are other unprocessed events",
1666 focusedWindowName);
1667 mKeyIsWaitingForEventsTimeout = std::nullopt;
1668 return false;
1669}
1670
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001671InputEventInjectionResult InputDispatcher::findFocusedWindowTargetsLocked(
1672 nsecs_t currentTime, const EventEntry& entry, std::vector<InputTarget>& inputTargets,
1673 nsecs_t* nextWakeupTime) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001674 std::string reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001675
Tiger Huang721e26f2018-07-24 22:26:19 +08001676 int32_t displayId = getTargetDisplayId(entry);
Vishnu Nairad321cd2020-08-20 16:40:21 -07001677 sp<InputWindowHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07001678 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08001679 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1680
Michael Wrightd02c5b62014-02-10 15:10:22 -08001681 // If there is no currently focused window and no focused application
1682 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001683 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
1684 ALOGI("Dropping %s event because there is no focused window or focused application in "
1685 "display %" PRId32 ".",
Chris Yef59a2f42020-10-16 12:55:26 -07001686 NamedEnum::string(entry.type).c_str(), displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001687 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001688 }
1689
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001690 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
1691 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
1692 // start interacting with another application via touch (app switch). This code can be removed
1693 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
1694 // an app is expected to have a focused window.
1695 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
1696 if (!mNoFocusedWindowTimeoutTime.has_value()) {
1697 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001698 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
1699 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
1700 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001701 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05001702 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001703 ALOGW("Waiting because no window has focus but %s may eventually add a "
1704 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001705 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001706 *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001707 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001708 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
1709 // Already raised ANR. Drop the event
1710 ALOGE("Dropping %s event because there is no focused window",
Chris Yef59a2f42020-10-16 12:55:26 -07001711 NamedEnum::string(entry.type).c_str());
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001712 return InputEventInjectionResult::FAILED;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001713 } else {
1714 // Still waiting for the focused window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001715 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001716 }
1717 }
1718
1719 // we have a valid, non-null focused window
1720 resetNoFocusedWindowTimeoutLocked();
1721
Michael Wrightd02c5b62014-02-10 15:10:22 -08001722 // Check permissions.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001723 if (!checkInjectionPermission(focusedWindowHandle, entry.injectionState)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001724 return InputEventInjectionResult::PERMISSION_DENIED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001725 }
1726
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001727 if (focusedWindowHandle->getInfo()->paused) {
1728 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001729 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001730 }
1731
1732 // If the event is a key event, then we must wait for all previous events to
1733 // complete before delivering it because previous events may have the
1734 // side-effect of transferring focus to a different window and we want to
1735 // ensure that the following keys are sent to the new window.
1736 //
1737 // Suppose the user touches a button in a window then immediately presses "A".
1738 // If the button causes a pop-up window to appear then we want to ensure that
1739 // the "A" key is delivered to the new pop-up window. This is because users
1740 // often anticipate pending UI changes when typing on a keyboard.
1741 // To obtain this behavior, we must serialize key events with respect to all
1742 // prior input events.
1743 if (entry.type == EventEntry::Type::KEY) {
1744 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
1745 *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001746 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001747 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001748 }
1749
1750 // Success! Output targets.
Tiger Huang721e26f2018-07-24 22:26:19 +08001751 addWindowTargetLocked(focusedWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001752 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS,
1753 BitSet32(0), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001754
1755 // Done.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001756 return InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001757}
1758
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001759/**
1760 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
1761 * that are currently unresponsive.
1762 */
1763std::vector<TouchedMonitor> InputDispatcher::selectResponsiveMonitorsLocked(
1764 const std::vector<TouchedMonitor>& monitors) const {
1765 std::vector<TouchedMonitor> responsiveMonitors;
1766 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
1767 [this](const TouchedMonitor& monitor) REQUIRES(mLock) {
1768 sp<Connection> connection = getConnectionLocked(
1769 monitor.monitor.inputChannel->getConnectionToken());
1770 if (connection == nullptr) {
1771 ALOGE("Could not find connection for monitor %s",
1772 monitor.monitor.inputChannel->getName().c_str());
1773 return false;
1774 }
1775 if (!connection->responsive) {
1776 ALOGW("Unresponsive monitor %s will not get the new gesture",
1777 connection->inputChannel->getName().c_str());
1778 return false;
1779 }
1780 return true;
1781 });
1782 return responsiveMonitors;
1783}
1784
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001785InputEventInjectionResult InputDispatcher::findTouchedWindowTargetsLocked(
1786 nsecs_t currentTime, const MotionEntry& entry, std::vector<InputTarget>& inputTargets,
1787 nsecs_t* nextWakeupTime, bool* outConflictingPointerActions) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001788 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001789 enum InjectionPermission {
1790 INJECTION_PERMISSION_UNKNOWN,
1791 INJECTION_PERMISSION_GRANTED,
1792 INJECTION_PERMISSION_DENIED
1793 };
1794
Michael Wrightd02c5b62014-02-10 15:10:22 -08001795 // For security reasons, we defer updating the touch state until we are sure that
1796 // event injection will be allowed.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001797 int32_t displayId = entry.displayId;
1798 int32_t action = entry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001799 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
1800
1801 // Update the touch state as needed based on the properties of the touch event.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001802 InputEventInjectionResult injectionResult = InputEventInjectionResult::PENDING;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001803 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
Garfield Tandf26e862020-07-01 20:18:19 -07001804 sp<InputWindowHandle> newHoverWindowHandle(mLastHoverWindowHandle);
1805 sp<InputWindowHandle> newTouchedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001806
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001807 // Copy current touch state into tempTouchState.
1808 // This state will be used to update mTouchStatesByDisplay at the end of this function.
1809 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07001810 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001811 TouchState tempTouchState;
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07001812 std::unordered_map<int32_t, TouchState>::iterator oldStateIt =
1813 mTouchStatesByDisplay.find(displayId);
1814 if (oldStateIt != mTouchStatesByDisplay.end()) {
1815 oldState = &(oldStateIt->second);
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001816 tempTouchState.copyFrom(*oldState);
Jeff Brownf086ddb2014-02-11 14:28:48 -08001817 }
1818
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001819 bool isSplit = tempTouchState.split;
1820 bool switchedDevice = tempTouchState.deviceId >= 0 && tempTouchState.displayId >= 0 &&
1821 (tempTouchState.deviceId != entry.deviceId || tempTouchState.source != entry.source ||
1822 tempTouchState.displayId != displayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001823 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
1824 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
1825 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
1826 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN ||
1827 maskedAction == AMOTION_EVENT_ACTION_SCROLL || isHoverAction);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001828 const bool isFromMouse = entry.source == AINPUT_SOURCE_MOUSE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001829 bool wrongDevice = false;
1830 if (newGesture) {
1831 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001832 if (switchedDevice && tempTouchState.down && !down && !isHoverAction) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001833 ALOGI("Dropping event because a pointer for a different device is already down "
1834 "in display %" PRId32,
1835 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001836 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001837 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001838 switchedDevice = false;
1839 wrongDevice = true;
1840 goto Failed;
1841 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001842 tempTouchState.reset();
1843 tempTouchState.down = down;
1844 tempTouchState.deviceId = entry.deviceId;
1845 tempTouchState.source = entry.source;
1846 tempTouchState.displayId = displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001847 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001848 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001849 ALOGI("Dropping move event because a pointer for a different device is already active "
1850 "in display %" PRId32,
1851 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001852 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001853 injectionResult = InputEventInjectionResult::PERMISSION_DENIED;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001854 switchedDevice = false;
1855 wrongDevice = true;
1856 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001857 }
1858
1859 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
1860 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
1861
Garfield Tan00f511d2019-06-12 16:55:40 -07001862 int32_t x;
1863 int32_t y;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001864 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Garfield Tan00f511d2019-06-12 16:55:40 -07001865 // Always dispatch mouse events to cursor position.
1866 if (isFromMouse) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001867 x = int32_t(entry.xCursorPosition);
1868 y = int32_t(entry.yCursorPosition);
Garfield Tan00f511d2019-06-12 16:55:40 -07001869 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001870 x = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X));
1871 y = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y));
Garfield Tan00f511d2019-06-12 16:55:40 -07001872 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001873 bool isDown = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Garfield Tandf26e862020-07-01 20:18:19 -07001874 newTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001875 findTouchedWindowAtLocked(displayId, x, y, &tempTouchState,
1876 isDown /*addOutsideTargets*/, true /*addPortalWindows*/);
Michael Wright3dd60e22019-03-27 22:06:44 +00001877
1878 std::vector<TouchedMonitor> newGestureMonitors = isDown
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001879 ? findTouchedGestureMonitorsLocked(displayId, tempTouchState.portalWindows)
Michael Wright3dd60e22019-03-27 22:06:44 +00001880 : std::vector<TouchedMonitor>{};
Michael Wrightd02c5b62014-02-10 15:10:22 -08001881
Michael Wrightd02c5b62014-02-10 15:10:22 -08001882 // Figure out whether splitting will be allowed for this window.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001883 if (newTouchedWindowHandle != nullptr &&
1884 newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Garfield Tanaddb02b2019-06-25 16:36:13 -07001885 // New window supports splitting, but we should never split mouse events.
1886 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001887 } else if (isSplit) {
1888 // New window does not support splitting but we have already split events.
1889 // Ignore the new window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001890 newTouchedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001891 }
1892
1893 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001894 if (newTouchedWindowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001895 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001896 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001897 }
1898
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001899 if (newTouchedWindowHandle != nullptr && newTouchedWindowHandle->getInfo()->paused) {
1900 ALOGI("Not sending touch event to %s because it is paused",
1901 newTouchedWindowHandle->getName().c_str());
1902 newTouchedWindowHandle = nullptr;
1903 }
1904
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001905 // Ensure the window has a connection and the connection is responsive
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001906 if (newTouchedWindowHandle != nullptr) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001907 const bool isResponsive = hasResponsiveConnectionLocked(*newTouchedWindowHandle);
1908 if (!isResponsive) {
1909 ALOGW("%s will not receive the new gesture at %" PRIu64,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001910 newTouchedWindowHandle->getName().c_str(), entry.eventTime);
1911 newTouchedWindowHandle = nullptr;
1912 }
1913 }
1914
Bernardo Rufinoea97d182020-08-19 14:43:14 +01001915 // Drop events that can't be trusted due to occlusion
1916 if (newTouchedWindowHandle != nullptr &&
1917 mBlockUntrustedTouchesMode != BlockUntrustedTouchesMode::DISABLED) {
1918 TouchOcclusionInfo occlusionInfo =
1919 computeTouchOcclusionInfoLocked(newTouchedWindowHandle, x, y);
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00001920 if (!isTouchTrustedLocked(occlusionInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00001921 if (DEBUG_TOUCH_OCCLUSION) {
1922 ALOGD("Stack of obscuring windows during untrusted touch (%d, %d):", x, y);
1923 for (const auto& log : occlusionInfo.debugInfo) {
1924 ALOGD("%s", log.c_str());
1925 }
1926 }
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00001927 onUntrustedTouchLocked(occlusionInfo.obscuringPackage);
1928 if (mBlockUntrustedTouchesMode == BlockUntrustedTouchesMode::BLOCK) {
1929 ALOGW("Dropping untrusted touch event due to %s/%d",
1930 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid);
1931 newTouchedWindowHandle = nullptr;
1932 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01001933 }
1934 }
1935
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001936 // Also don't send the new touch event to unresponsive gesture monitors
1937 newGestureMonitors = selectResponsiveMonitorsLocked(newGestureMonitors);
1938
Michael Wright3dd60e22019-03-27 22:06:44 +00001939 if (newTouchedWindowHandle == nullptr && newGestureMonitors.empty()) {
1940 ALOGI("Dropping event because there is no touchable window or gesture monitor at "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001941 "(%d, %d) in display %" PRId32 ".",
1942 x, y, displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001943 injectionResult = InputEventInjectionResult::FAILED;
Michael Wright3dd60e22019-03-27 22:06:44 +00001944 goto Failed;
1945 }
1946
1947 if (newTouchedWindowHandle != nullptr) {
1948 // Set target flags.
1949 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
1950 if (isSplit) {
1951 targetFlags |= InputTarget::FLAG_SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001952 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001953 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1954 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1955 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
1956 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1957 }
1958
1959 // Update hover state.
Garfield Tandf26e862020-07-01 20:18:19 -07001960 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
1961 newHoverWindowHandle = nullptr;
1962 } else if (isHoverAction) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001963 newHoverWindowHandle = newTouchedWindowHandle;
Michael Wright3dd60e22019-03-27 22:06:44 +00001964 }
1965
1966 // Update the temporary touch state.
1967 BitSet32 pointerIds;
1968 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001969 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wright3dd60e22019-03-27 22:06:44 +00001970 pointerIds.markBit(pointerId);
1971 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001972 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001973 }
1974
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001975 tempTouchState.addGestureMonitors(newGestureMonitors);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001976 } else {
1977 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
1978
1979 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001980 if (!tempTouchState.down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001981 if (DEBUG_FOCUS) {
1982 ALOGD("Dropping event because the pointer is not down or we previously "
1983 "dropped the pointer down event in display %" PRId32,
1984 displayId);
1985 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001986 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001987 goto Failed;
1988 }
1989
1990 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001991 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001992 tempTouchState.isSlippery()) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001993 int32_t x = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
1994 int32_t y = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001995
1996 sp<InputWindowHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001997 tempTouchState.getFirstForegroundWindowHandle();
Garfield Tandf26e862020-07-01 20:18:19 -07001998 newTouchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y, &tempTouchState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001999 if (oldTouchedWindowHandle != newTouchedWindowHandle &&
2000 oldTouchedWindowHandle != nullptr && newTouchedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002001 if (DEBUG_FOCUS) {
2002 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
2003 oldTouchedWindowHandle->getName().c_str(),
2004 newTouchedWindowHandle->getName().c_str(), displayId);
2005 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002006 // Make a slippery exit from the old window.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002007 tempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
2008 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT,
2009 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002010
2011 // Make a slippery entrance into the new window.
2012 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
2013 isSplit = true;
2014 }
2015
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002016 int32_t targetFlags =
2017 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002018 if (isSplit) {
2019 targetFlags |= InputTarget::FLAG_SPLIT;
2020 }
2021 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
2022 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002023 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
2024 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002025 }
2026
2027 BitSet32 pointerIds;
2028 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002029 pointerIds.markBit(entry.pointerProperties[0].id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002030 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002031 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002032 }
2033 }
2034 }
2035
2036 if (newHoverWindowHandle != mLastHoverWindowHandle) {
Garfield Tandf26e862020-07-01 20:18:19 -07002037 // Let the previous window know that the hover sequence is over, unless we already did it
2038 // when dispatching it as is to newTouchedWindowHandle.
2039 if (mLastHoverWindowHandle != nullptr &&
2040 (maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT ||
2041 mLastHoverWindowHandle != newTouchedWindowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002042#if DEBUG_HOVER
2043 ALOGD("Sending hover exit event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002044 mLastHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002045#endif
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002046 tempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
2047 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002048 }
2049
Garfield Tandf26e862020-07-01 20:18:19 -07002050 // Let the new window know that the hover sequence is starting, unless we already did it
2051 // when dispatching it as is to newTouchedWindowHandle.
2052 if (newHoverWindowHandle != nullptr &&
2053 (maskedAction != AMOTION_EVENT_ACTION_HOVER_ENTER ||
2054 newHoverWindowHandle != newTouchedWindowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002055#if DEBUG_HOVER
2056 ALOGD("Sending hover enter event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002057 newHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002058#endif
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002059 tempTouchState.addOrUpdateWindow(newHoverWindowHandle,
2060 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER,
2061 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002062 }
2063 }
2064
2065 // Check permission to inject into all touched foreground windows and ensure there
2066 // is at least one touched foreground window.
2067 {
2068 bool haveForegroundWindow = false;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002069 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002070 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
2071 haveForegroundWindow = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002072 if (!checkInjectionPermission(touchedWindow.windowHandle, entry.injectionState)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002073 injectionResult = InputEventInjectionResult::PERMISSION_DENIED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002074 injectionPermission = INJECTION_PERMISSION_DENIED;
2075 goto Failed;
2076 }
2077 }
2078 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002079 bool hasGestureMonitor = !tempTouchState.gestureMonitors.empty();
Michael Wright3dd60e22019-03-27 22:06:44 +00002080 if (!haveForegroundWindow && !hasGestureMonitor) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002081 ALOGI("Dropping event because there is no touched foreground window in display "
2082 "%" PRId32 " or gesture monitor to receive it.",
2083 displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002084 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002085 goto Failed;
2086 }
2087
2088 // Permission granted to injection into all touched foreground windows.
2089 injectionPermission = INJECTION_PERMISSION_GRANTED;
2090 }
2091
2092 // Check whether windows listening for outside touches are owned by the same UID. If it is
2093 // set the policy flag that we will not reveal coordinate information to this window.
2094 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2095 sp<InputWindowHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002096 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002097 if (foregroundWindowHandle) {
2098 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002099 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002100 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2101 sp<InputWindowHandle> inputWindowHandle = touchedWindow.windowHandle;
2102 if (inputWindowHandle->getInfo()->ownerUid != foregroundWindowUid) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002103 tempTouchState.addOrUpdateWindow(inputWindowHandle,
2104 InputTarget::FLAG_ZERO_COORDS,
2105 BitSet32(0));
Michael Wright3dd60e22019-03-27 22:06:44 +00002106 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002107 }
2108 }
2109 }
2110 }
2111
Michael Wrightd02c5b62014-02-10 15:10:22 -08002112 // If this is the first pointer going down and the touched window has a wallpaper
2113 // then also add the touched wallpaper windows so they are locked in for the duration
2114 // of the touch gesture.
2115 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
2116 // engine only supports touch events. We would need to add a mechanism similar
2117 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
2118 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2119 sp<InputWindowHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002120 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002121 if (foregroundWindowHandle && foregroundWindowHandle->getInfo()->hasWallpaper) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07002122 const std::vector<sp<InputWindowHandle>>& windowHandles =
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002123 getWindowHandlesLocked(displayId);
2124 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002125 const InputWindowInfo* info = windowHandle->getInfo();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002126 if (info->displayId == displayId &&
Michael Wright44753b12020-07-08 13:48:11 +01002127 windowHandle->getInfo()->type == InputWindowInfo::Type::WALLPAPER) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002128 tempTouchState
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002129 .addOrUpdateWindow(windowHandle,
2130 InputTarget::FLAG_WINDOW_IS_OBSCURED |
2131 InputTarget::
2132 FLAG_WINDOW_IS_PARTIALLY_OBSCURED |
2133 InputTarget::FLAG_DISPATCH_AS_IS,
2134 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002135 }
2136 }
2137 }
2138 }
2139
2140 // Success! Output targets.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002141 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002142
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002143 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002144 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002145 touchedWindow.pointerIds, inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002146 }
2147
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002148 for (const TouchedMonitor& touchedMonitor : tempTouchState.gestureMonitors) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002149 addMonitoringTargetLocked(touchedMonitor.monitor, touchedMonitor.xOffset,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002150 touchedMonitor.yOffset, inputTargets);
Michael Wright3dd60e22019-03-27 22:06:44 +00002151 }
2152
Michael Wrightd02c5b62014-02-10 15:10:22 -08002153 // Drop the outside or hover touch windows since we will not care about them
2154 // in the next iteration.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002155 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002156
2157Failed:
2158 // Check injection permission once and for all.
2159 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002160 if (checkInjectionPermission(nullptr, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002161 injectionPermission = INJECTION_PERMISSION_GRANTED;
2162 } else {
2163 injectionPermission = INJECTION_PERMISSION_DENIED;
2164 }
2165 }
2166
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002167 if (injectionPermission != INJECTION_PERMISSION_GRANTED) {
2168 return injectionResult;
2169 }
2170
Michael Wrightd02c5b62014-02-10 15:10:22 -08002171 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002172 if (!wrongDevice) {
2173 if (switchedDevice) {
2174 if (DEBUG_FOCUS) {
2175 ALOGD("Conflicting pointer actions: Switched to a different device.");
2176 }
2177 *outConflictingPointerActions = true;
2178 }
2179
2180 if (isHoverAction) {
2181 // Started hovering, therefore no longer down.
2182 if (oldState && oldState->down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002183 if (DEBUG_FOCUS) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002184 ALOGD("Conflicting pointer actions: Hover received while pointer was "
2185 "down.");
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002186 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002187 *outConflictingPointerActions = true;
2188 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002189 tempTouchState.reset();
2190 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2191 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
2192 tempTouchState.deviceId = entry.deviceId;
2193 tempTouchState.source = entry.source;
2194 tempTouchState.displayId = displayId;
2195 }
2196 } else if (maskedAction == AMOTION_EVENT_ACTION_UP ||
2197 maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
2198 // All pointers up or canceled.
2199 tempTouchState.reset();
2200 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2201 // First pointer went down.
2202 if (oldState && oldState->down) {
2203 if (DEBUG_FOCUS) {
2204 ALOGD("Conflicting pointer actions: Down received while already down.");
2205 }
2206 *outConflictingPointerActions = true;
2207 }
2208 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2209 // One pointer went up.
2210 if (isSplit) {
2211 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2212 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002213
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002214 for (size_t i = 0; i < tempTouchState.windows.size();) {
2215 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2216 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
2217 touchedWindow.pointerIds.clearBit(pointerId);
2218 if (touchedWindow.pointerIds.isEmpty()) {
2219 tempTouchState.windows.erase(tempTouchState.windows.begin() + i);
2220 continue;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002221 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002222 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002223 i += 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002224 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002225 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002226 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002227
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002228 // Save changes unless the action was scroll in which case the temporary touch
2229 // state was only valid for this one action.
2230 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
2231 if (tempTouchState.displayId >= 0) {
2232 mTouchStatesByDisplay[displayId] = tempTouchState;
2233 } else {
2234 mTouchStatesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002235 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002236 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002237
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002238 // Update hover state.
2239 mLastHoverWindowHandle = newHoverWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002240 }
2241
Michael Wrightd02c5b62014-02-10 15:10:22 -08002242 return injectionResult;
2243}
2244
2245void InputDispatcher::addWindowTargetLocked(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002246 int32_t targetFlags, BitSet32 pointerIds,
2247 std::vector<InputTarget>& inputTargets) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002248 std::vector<InputTarget>::iterator it =
2249 std::find_if(inputTargets.begin(), inputTargets.end(),
2250 [&windowHandle](const InputTarget& inputTarget) {
2251 return inputTarget.inputChannel->getConnectionToken() ==
2252 windowHandle->getToken();
2253 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002254
Chavi Weingarten114b77f2020-01-15 22:35:10 +00002255 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002256
2257 if (it == inputTargets.end()) {
2258 InputTarget inputTarget;
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05002259 std::shared_ptr<InputChannel> inputChannel =
2260 getInputChannelLocked(windowHandle->getToken());
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002261 if (inputChannel == nullptr) {
2262 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
2263 return;
2264 }
2265 inputTarget.inputChannel = inputChannel;
2266 inputTarget.flags = targetFlags;
2267 inputTarget.globalScaleFactor = windowInfo->globalScaleFactor;
2268 inputTargets.push_back(inputTarget);
2269 it = inputTargets.end() - 1;
2270 }
2271
2272 ALOG_ASSERT(it->flags == targetFlags);
2273 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
2274
chaviw1ff3d1e2020-07-01 15:53:47 -07002275 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002276}
2277
Michael Wright3dd60e22019-03-27 22:06:44 +00002278void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002279 int32_t displayId, float xOffset,
2280 float yOffset) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002281 std::unordered_map<int32_t, std::vector<Monitor>>::const_iterator it =
2282 mGlobalMonitorsByDisplay.find(displayId);
2283
2284 if (it != mGlobalMonitorsByDisplay.end()) {
2285 const std::vector<Monitor>& monitors = it->second;
2286 for (const Monitor& monitor : monitors) {
2287 addMonitoringTargetLocked(monitor, xOffset, yOffset, inputTargets);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002288 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002289 }
2290}
2291
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002292void InputDispatcher::addMonitoringTargetLocked(const Monitor& monitor, float xOffset,
2293 float yOffset,
2294 std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002295 InputTarget target;
2296 target.inputChannel = monitor.inputChannel;
2297 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
chaviw1ff3d1e2020-07-01 15:53:47 -07002298 ui::Transform t;
2299 t.set(xOffset, yOffset);
2300 target.setDefaultPointerTransform(t);
Michael Wright3dd60e22019-03-27 22:06:44 +00002301 inputTargets.push_back(target);
2302}
2303
Michael Wrightd02c5b62014-02-10 15:10:22 -08002304bool InputDispatcher::checkInjectionPermission(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002305 const InjectionState* injectionState) {
2306 if (injectionState &&
2307 (windowHandle == nullptr ||
2308 windowHandle->getInfo()->ownerUid != injectionState->injectorUid) &&
2309 !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002310 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002311 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002312 "owned by uid %d",
2313 injectionState->injectorPid, injectionState->injectorUid,
2314 windowHandle->getName().c_str(), windowHandle->getInfo()->ownerUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002315 } else {
2316 ALOGW("Permission denied: injecting event from pid %d uid %d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002317 injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002318 }
2319 return false;
2320 }
2321 return true;
2322}
2323
Robert Carrc9bf1d32020-04-13 17:21:08 -07002324/**
2325 * Indicate whether one window handle should be considered as obscuring
2326 * another window handle. We only check a few preconditions. Actually
2327 * checking the bounds is left to the caller.
2328 */
2329static bool canBeObscuredBy(const sp<InputWindowHandle>& windowHandle,
2330 const sp<InputWindowHandle>& otherHandle) {
2331 // Compare by token so cloned layers aren't counted
2332 if (haveSameToken(windowHandle, otherHandle)) {
2333 return false;
2334 }
2335 auto info = windowHandle->getInfo();
2336 auto otherInfo = otherHandle->getInfo();
2337 if (!otherInfo->visible) {
2338 return false;
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002339 } else if (otherInfo->alpha == 0 &&
2340 otherInfo->flags.test(InputWindowInfo::Flag::NOT_TOUCHABLE)) {
2341 // Those act as if they were invisible, so we don't need to flag them.
2342 // We do want to potentially flag touchable windows even if they have 0
2343 // opacity, since they can consume touches and alter the effects of the
2344 // user interaction (eg. apps that rely on
2345 // FLAG_WINDOW_IS_PARTIALLY_OBSCURED should still be told about those
2346 // windows), hence we also check for FLAG_NOT_TOUCHABLE.
2347 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00002348 } else if (info->ownerUid == otherInfo->ownerUid) {
2349 // If ownerUid is the same we don't generate occlusion events as there
2350 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002351 return false;
Chris Yefcdff3e2020-05-10 15:16:04 -07002352 } else if (otherInfo->trustedOverlay) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002353 return false;
2354 } else if (otherInfo->displayId != info->displayId) {
2355 return false;
2356 }
2357 return true;
2358}
2359
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002360/**
2361 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
2362 * untrusted, one should check:
2363 *
2364 * 1. If result.hasBlockingOcclusion is true.
2365 * If it's, it means the touch should be blocked due to a window with occlusion mode of
2366 * BLOCK_UNTRUSTED.
2367 *
2368 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
2369 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
2370 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
2371 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
2372 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
2373 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
2374 *
2375 * If neither of those is true, then it means the touch can be allowed.
2376 */
2377InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
2378 const sp<InputWindowHandle>& windowHandle, int32_t x, int32_t y) const {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002379 const InputWindowInfo* windowInfo = windowHandle->getInfo();
2380 int32_t displayId = windowInfo->displayId;
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002381 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2382 TouchOcclusionInfo info;
2383 info.hasBlockingOcclusion = false;
2384 info.obscuringOpacity = 0;
2385 info.obscuringUid = -1;
2386 std::map<int32_t, float> opacityByUid;
2387 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
2388 if (windowHandle == otherHandle) {
2389 break; // All future windows are below us. Exit early.
2390 }
2391 const InputWindowInfo* otherInfo = otherHandle->getInfo();
2392 if (canBeObscuredBy(windowHandle, otherHandle) &&
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002393 windowInfo->ownerUid != otherInfo->ownerUid && otherInfo->frameContainsPoint(x, y)) {
2394 if (DEBUG_TOUCH_OCCLUSION) {
2395 info.debugInfo.push_back(
2396 dumpWindowForTouchOcclusion(otherInfo, /* isTouchedWindow */ false));
2397 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002398 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
2399 // we perform the checks below to see if the touch can be propagated or not based on the
2400 // window's touch occlusion mode
2401 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
2402 info.hasBlockingOcclusion = true;
2403 info.obscuringUid = otherInfo->ownerUid;
2404 info.obscuringPackage = otherInfo->packageName;
2405 break;
2406 }
2407 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
2408 uint32_t uid = otherInfo->ownerUid;
2409 float opacity =
2410 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
2411 // Given windows A and B:
2412 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
2413 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
2414 opacityByUid[uid] = opacity;
2415 if (opacity > info.obscuringOpacity) {
2416 info.obscuringOpacity = opacity;
2417 info.obscuringUid = uid;
2418 info.obscuringPackage = otherInfo->packageName;
2419 }
2420 }
2421 }
2422 }
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002423 if (DEBUG_TOUCH_OCCLUSION) {
2424 info.debugInfo.push_back(
2425 dumpWindowForTouchOcclusion(windowInfo, /* isTouchedWindow */ true));
2426 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002427 return info;
2428}
2429
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002430std::string InputDispatcher::dumpWindowForTouchOcclusion(const InputWindowInfo* info,
2431 bool isTouchedWindow) const {
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00002432 return StringPrintf(INDENT2 "* %stype=%s, package=%s/%" PRId32 ", id=%" PRId32
2433 ", mode=%s, alpha=%.2f, "
Bernardo Rufinoc2f1fad2020-11-04 17:30:57 +00002434 "frame=[%" PRId32 ",%" PRId32 "][%" PRId32 ",%" PRId32
2435 "], touchableRegion=%s, window={%s}, applicationInfo=%s, "
2436 "flags={%s}, inputFeatures={%s}, hasToken=%s\n",
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002437 (isTouchedWindow) ? "[TOUCHED] " : "",
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00002438 NamedEnum::string(info->type, "%" PRId32).c_str(),
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00002439 info->packageName.c_str(), info->ownerUid, info->id,
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00002440 toString(info->touchOcclusionMode).c_str(), info->alpha, info->frameLeft,
2441 info->frameTop, info->frameRight, info->frameBottom,
2442 dumpRegion(info->touchableRegion).c_str(), info->name.c_str(),
Bernardo Rufinoc2f1fad2020-11-04 17:30:57 +00002443 info->applicationInfo.name.c_str(), info->flags.string().c_str(),
2444 info->inputFeatures.string().c_str(), toString(info->token != nullptr));
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002445}
2446
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002447bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
2448 if (occlusionInfo.hasBlockingOcclusion) {
2449 ALOGW("Untrusted touch due to occlusion by %s/%d", occlusionInfo.obscuringPackage.c_str(),
2450 occlusionInfo.obscuringUid);
2451 return false;
2452 }
2453 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
2454 ALOGW("Untrusted touch due to occlusion by %s/%d (obscuring opacity = "
2455 "%.2f, maximum allowed = %.2f)",
2456 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid,
2457 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
2458 return false;
2459 }
2460 return true;
2461}
2462
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002463bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<InputWindowHandle>& windowHandle,
2464 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002465 int32_t displayId = windowHandle->getInfo()->displayId;
Vishnu Nairad321cd2020-08-20 16:40:21 -07002466 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002467 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002468 if (windowHandle == otherHandle) {
2469 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002470 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002471 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002472 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002473 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002474 return true;
2475 }
2476 }
2477 return false;
2478}
2479
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002480bool InputDispatcher::isWindowObscuredLocked(const sp<InputWindowHandle>& windowHandle) const {
2481 int32_t displayId = windowHandle->getInfo()->displayId;
Vishnu Nairad321cd2020-08-20 16:40:21 -07002482 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002483 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002484 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002485 if (windowHandle == otherHandle) {
2486 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002487 }
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002488 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002489 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002490 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002491 return true;
2492 }
2493 }
2494 return false;
2495}
2496
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002497std::string InputDispatcher::getApplicationWindowLabel(
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05002498 const InputApplicationHandle* applicationHandle,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002499 const sp<InputWindowHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002500 if (applicationHandle != nullptr) {
2501 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002502 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002503 } else {
2504 return applicationHandle->getName();
2505 }
Yi Kong9b14ac62018-07-17 13:48:38 -07002506 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002507 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002508 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002509 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002510 }
2511}
2512
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002513void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Prabir Pradhan99987712020-11-10 18:43:05 -08002514 if (eventEntry.type == EventEntry::Type::FOCUS ||
2515 eventEntry.type == EventEntry::Type::POINTER_CAPTURE_CHANGED) {
2516 // Focus or pointer capture changed events are passed to apps, but do not represent user
2517 // activity.
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002518 return;
2519 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002520 int32_t displayId = getTargetDisplayId(eventEntry);
Vishnu Nairad321cd2020-08-20 16:40:21 -07002521 sp<InputWindowHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Tiger Huang721e26f2018-07-24 22:26:19 +08002522 if (focusedWindowHandle != nullptr) {
2523 const InputWindowInfo* info = focusedWindowHandle->getInfo();
Michael Wright44753b12020-07-08 13:48:11 +01002524 if (info->inputFeatures.test(InputWindowInfo::Feature::DISABLE_USER_ACTIVITY)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002525#if DEBUG_DISPATCH_CYCLE
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002526 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002527#endif
2528 return;
2529 }
2530 }
2531
2532 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002533 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002534 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002535 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
2536 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002537 return;
2538 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002539
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002540 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002541 eventType = USER_ACTIVITY_EVENT_TOUCH;
2542 }
2543 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002544 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002545 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002546 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
2547 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002548 return;
2549 }
2550 eventType = USER_ACTIVITY_EVENT_BUTTON;
2551 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002552 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002553 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002554 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08002555 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07002556 case EventEntry::Type::SENSOR:
Prabir Pradhan99987712020-11-10 18:43:05 -08002557 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002558 LOG_ALWAYS_FATAL("%s events are not user activity",
Chris Yef59a2f42020-10-16 12:55:26 -07002559 NamedEnum::string(eventEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002560 break;
2561 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002562 }
2563
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002564 std::unique_ptr<CommandEntry> commandEntry =
2565 std::make_unique<CommandEntry>(&InputDispatcher::doPokeUserActivityLockedInterruptible);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002566 commandEntry->eventTime = eventEntry.eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002567 commandEntry->userActivityEventType = eventType;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002568 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002569}
2570
2571void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002572 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002573 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002574 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002575 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002576 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002577 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002578 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002579 ATRACE_NAME(message.c_str());
2580 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002581#if DEBUG_DISPATCH_CYCLE
2582 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002583 "globalScaleFactor=%f, pointerIds=0x%x %s",
2584 connection->getInputChannelName().c_str(), inputTarget.flags,
2585 inputTarget.globalScaleFactor, inputTarget.pointerIds.value,
2586 inputTarget.getPointerInfoString().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002587#endif
2588
2589 // Skip this event if the connection status is not normal.
2590 // We don't want to enqueue additional outbound events if the connection is broken.
2591 if (connection->status != Connection::STATUS_NORMAL) {
2592#if DEBUG_DISPATCH_CYCLE
2593 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002594 connection->getInputChannelName().c_str(), connection->getStatusLabel());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002595#endif
2596 return;
2597 }
2598
2599 // Split a motion event if needed.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002600 if (inputTarget.flags & InputTarget::FLAG_SPLIT) {
2601 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
2602 "Entry type %s should not have FLAG_SPLIT",
Chris Yef59a2f42020-10-16 12:55:26 -07002603 NamedEnum::string(eventEntry->type).c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002604
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002605 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002606 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002607 std::unique_ptr<MotionEntry> splitMotionEntry =
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002608 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002609 if (!splitMotionEntry) {
2610 return; // split event was dropped
2611 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002612 if (DEBUG_FOCUS) {
2613 ALOGD("channel '%s' ~ Split motion event.",
2614 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002615 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002616 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002617 enqueueDispatchEntriesLocked(currentTime, connection, std::move(splitMotionEntry),
2618 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002619 return;
2620 }
2621 }
2622
2623 // Not splitting. Enqueue dispatch entries for the event as is.
2624 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
2625}
2626
2627void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002628 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002629 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002630 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002631 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002632 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002633 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002634 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002635 ATRACE_NAME(message.c_str());
2636 }
2637
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002638 bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002639
2640 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07002641 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002642 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002643 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002644 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07002645 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002646 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07002647 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002648 InputTarget::FLAG_DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07002649 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002650 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002651 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002652 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002653
2654 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002655 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002656 startDispatchCycleLocked(currentTime, connection);
2657 }
2658}
2659
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002660void InputDispatcher::enqueueDispatchEntryLocked(const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002661 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002662 const InputTarget& inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002663 int32_t dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002664 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002665 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
2666 connection->getInputChannelName().c_str(),
2667 dispatchModeToString(dispatchMode).c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002668 ATRACE_NAME(message.c_str());
2669 }
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002670 int32_t inputTargetFlags = inputTarget.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002671 if (!(inputTargetFlags & dispatchMode)) {
2672 return;
2673 }
2674 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
2675
2676 // This is a new event.
2677 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002678 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002679 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002680
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002681 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
2682 // different EventEntry than what was passed in.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002683 EventEntry& newEntry = *(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002684 // Apply target flags and update the connection's input state.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002685 switch (newEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002686 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002687 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002688 dispatchEntry->resolvedEventId = keyEntry.id;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002689 dispatchEntry->resolvedAction = keyEntry.action;
2690 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002691
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002692 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
2693 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002694#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002695 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key event",
2696 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002697#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002698 return; // skip the inconsistent event
2699 }
2700 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002701 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002702
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002703 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002704 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002705 // Assign a default value to dispatchEntry that will never be generated by InputReader,
2706 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
2707 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
2708 static_cast<int32_t>(IdGenerator::Source::OTHER);
2709 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002710 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2711 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
2712 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
2713 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
2714 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
2715 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2716 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
2717 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
2718 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
2719 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
2720 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002721 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002722 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002723 }
2724 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002725 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
2726 motionEntry.displayId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002727#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002728 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover enter "
2729 "event",
2730 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002731#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002732 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2733 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002734
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002735 dispatchEntry->resolvedFlags = motionEntry.flags;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002736 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
2737 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
2738 }
2739 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
2740 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2741 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002742
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002743 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
2744 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002745#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002746 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
2747 "event",
2748 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002749#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002750 return; // skip the inconsistent event
2751 }
2752
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002753 dispatchEntry->resolvedEventId =
2754 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
2755 ? mIdGenerator.nextId()
2756 : motionEntry.id;
2757 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
2758 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
2759 ") to MotionEvent(id=0x%" PRIx32 ").",
2760 motionEntry.id, dispatchEntry->resolvedEventId);
2761 ATRACE_NAME(message.c_str());
2762 }
2763
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002764 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002765 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002766
2767 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002768 }
Prabir Pradhan99987712020-11-10 18:43:05 -08002769 case EventEntry::Type::FOCUS:
2770 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002771 break;
2772 }
Chris Yef59a2f42020-10-16 12:55:26 -07002773 case EventEntry::Type::SENSOR: {
2774 LOG_ALWAYS_FATAL("SENSOR events should not go to apps via input channel");
2775 break;
2776 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002777 case EventEntry::Type::CONFIGURATION_CHANGED:
2778 case EventEntry::Type::DEVICE_RESET: {
2779 LOG_ALWAYS_FATAL("%s events should not go to apps",
Chris Yef59a2f42020-10-16 12:55:26 -07002780 NamedEnum::string(newEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002781 break;
2782 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002783 }
2784
2785 // Remember that we are waiting for this dispatch to complete.
2786 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002787 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002788 }
2789
2790 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002791 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002792 traceOutboundQueueLength(connection);
chaviw8c9cf542019-03-25 13:02:48 -07002793}
2794
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00002795/**
2796 * This function is purely for debugging. It helps us understand where the user interaction
2797 * was taking place. For example, if user is touching launcher, we will see a log that user
2798 * started interacting with launcher. In that example, the event would go to the wallpaper as well.
2799 * We will see both launcher and wallpaper in that list.
2800 * Once the interaction with a particular set of connections starts, no new logs will be printed
2801 * until the set of interacted connections changes.
2802 *
2803 * The following items are skipped, to reduce the logspam:
2804 * ACTION_OUTSIDE: any windows that are receiving ACTION_OUTSIDE are not logged
2805 * ACTION_UP: any windows that receive ACTION_UP are not logged (for both keys and motions).
2806 * This includes situations like the soft BACK button key. When the user releases (lifts up the
2807 * finger) the back button, then navigation bar will inject KEYCODE_BACK with ACTION_UP.
2808 * Both of those ACTION_UP events would not be logged
2809 * Monitors (both gesture and global): any gesture monitors or global monitors receiving events
2810 * will not be logged. This is omitted to reduce the amount of data printed.
2811 * If you see <none>, it's likely that one of the gesture monitors pilfered the event, and therefore
2812 * gesture monitor is the only connection receiving the remainder of the gesture.
2813 */
2814void InputDispatcher::updateInteractionTokensLocked(const EventEntry& entry,
2815 const std::vector<InputTarget>& targets) {
2816 // Skip ACTION_UP events, and all events other than keys and motions
2817 if (entry.type == EventEntry::Type::KEY) {
2818 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
2819 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
2820 return;
2821 }
2822 } else if (entry.type == EventEntry::Type::MOTION) {
2823 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
2824 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
2825 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
2826 return;
2827 }
2828 } else {
2829 return; // Not a key or a motion
2830 }
2831
2832 std::unordered_set<sp<IBinder>, IBinderHash> newConnectionTokens;
2833 std::vector<sp<Connection>> newConnections;
2834 for (const InputTarget& target : targets) {
2835 if ((target.flags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) ==
2836 InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2837 continue; // Skip windows that receive ACTION_OUTSIDE
2838 }
2839
2840 sp<IBinder> token = target.inputChannel->getConnectionToken();
2841 sp<Connection> connection = getConnectionLocked(token);
2842 if (connection == nullptr || connection->monitor) {
2843 continue; // We only need to keep track of the non-monitor connections.
2844 }
2845 newConnectionTokens.insert(std::move(token));
2846 newConnections.emplace_back(connection);
2847 }
2848 if (newConnectionTokens == mInteractionConnectionTokens) {
2849 return; // no change
2850 }
2851 mInteractionConnectionTokens = newConnectionTokens;
2852
2853 std::string windowList;
2854 for (const sp<Connection>& connection : newConnections) {
2855 windowList += connection->getWindowName() + ", ";
2856 }
2857 std::string message = "Interaction with windows: " + windowList;
2858 if (windowList.empty()) {
2859 message += "<none>";
2860 }
2861 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
2862}
2863
chaviwfd6d3512019-03-25 13:23:49 -07002864void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07002865 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07002866 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07002867 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
2868 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07002869 return;
2870 }
2871
Vishnu Nairad321cd2020-08-20 16:40:21 -07002872 sp<IBinder> focusedToken = getValueByKey(mFocusedWindowTokenByDisplay, mFocusedDisplayId);
2873 if (focusedToken == token) {
2874 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07002875 return;
2876 }
2877
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002878 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
2879 &InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible);
Vishnu Nairad321cd2020-08-20 16:40:21 -07002880 commandEntry->newToken = token;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002881 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002882}
2883
2884void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002885 const sp<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002886 if (ATRACE_ENABLED()) {
2887 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002888 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002889 ATRACE_NAME(message.c_str());
2890 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002891#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002892 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002893#endif
2894
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002895 while (connection->status == Connection::STATUS_NORMAL && !connection->outboundQueue.empty()) {
2896 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002897 dispatchEntry->deliveryTime = currentTime;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05002898 const std::chrono::nanoseconds timeout =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002899 getDispatchingTimeoutLocked(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou70622952020-07-30 11:17:23 -05002900 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002901
2902 // Publish the event.
2903 status_t status;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002904 const EventEntry& eventEntry = *(dispatchEntry->eventEntry);
2905 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002906 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002907 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
2908 std::array<uint8_t, 32> hmac = getSignature(keyEntry, *dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002909
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002910 // Publish the key event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002911 status = connection->inputPublisher
2912 .publishKeyEvent(dispatchEntry->seq,
2913 dispatchEntry->resolvedEventId, keyEntry.deviceId,
2914 keyEntry.source, keyEntry.displayId,
2915 std::move(hmac), dispatchEntry->resolvedAction,
2916 dispatchEntry->resolvedFlags, keyEntry.keyCode,
2917 keyEntry.scanCode, keyEntry.metaState,
2918 keyEntry.repeatCount, keyEntry.downTime,
2919 keyEntry.eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002920 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002921 }
2922
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002923 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002924 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002925
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002926 PointerCoords scaledCoords[MAX_POINTERS];
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002927 const PointerCoords* usingCoords = motionEntry.pointerCoords;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002928
chaviw82357092020-01-28 13:13:06 -08002929 // Set the X and Y offset and X and Y scale depending on the input source.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002930 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) &&
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002931 !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
2932 float globalScaleFactor = dispatchEntry->globalScaleFactor;
chaviw82357092020-01-28 13:13:06 -08002933 if (globalScaleFactor != 1.0f) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002934 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
2935 scaledCoords[i] = motionEntry.pointerCoords[i];
chaviw82357092020-01-28 13:13:06 -08002936 // Don't apply window scale here since we don't want scale to affect raw
2937 // coordinates. The scale will be sent back to the client and applied
2938 // later when requesting relative coordinates.
2939 scaledCoords[i].scale(globalScaleFactor, 1 /* windowXScale */,
2940 1 /* windowYScale */);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002941 }
2942 usingCoords = scaledCoords;
2943 }
2944 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002945 // We don't want the dispatch target to know.
2946 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002947 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002948 scaledCoords[i].clear();
2949 }
2950 usingCoords = scaledCoords;
2951 }
2952 }
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07002953
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002954 std::array<uint8_t, 32> hmac = getSignature(motionEntry, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002955
2956 // Publish the motion event.
2957 status = connection->inputPublisher
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002958 .publishMotionEvent(dispatchEntry->seq,
2959 dispatchEntry->resolvedEventId,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002960 motionEntry.deviceId, motionEntry.source,
2961 motionEntry.displayId, std::move(hmac),
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002962 dispatchEntry->resolvedAction,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002963 motionEntry.actionButton,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002964 dispatchEntry->resolvedFlags,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002965 motionEntry.edgeFlags, motionEntry.metaState,
2966 motionEntry.buttonState,
2967 motionEntry.classification,
chaviw9eaa22c2020-07-01 16:21:27 -07002968 dispatchEntry->transform,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002969 motionEntry.xPrecision, motionEntry.yPrecision,
2970 motionEntry.xCursorPosition,
2971 motionEntry.yCursorPosition,
2972 motionEntry.downTime, motionEntry.eventTime,
2973 motionEntry.pointerCount,
2974 motionEntry.pointerProperties, usingCoords);
2975 reportTouchEventForStatistics(motionEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002976 break;
2977 }
Prabir Pradhan99987712020-11-10 18:43:05 -08002978
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002979 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002980 const FocusEntry& focusEntry = static_cast<const FocusEntry&>(eventEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002981 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002982 focusEntry.id,
2983 focusEntry.hasFocus,
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002984 mInTouchMode);
2985 break;
2986 }
2987
Prabir Pradhan99987712020-11-10 18:43:05 -08002988 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
2989 const auto& captureEntry =
2990 static_cast<const PointerCaptureChangedEntry&>(eventEntry);
2991 status = connection->inputPublisher
2992 .publishCaptureEvent(dispatchEntry->seq, captureEntry.id,
2993 captureEntry.pointerCaptureEnabled);
2994 break;
2995 }
2996
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08002997 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07002998 case EventEntry::Type::DEVICE_RESET:
2999 case EventEntry::Type::SENSOR: {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003000 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
Chris Yef59a2f42020-10-16 12:55:26 -07003001 NamedEnum::string(eventEntry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003002 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003003 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003004 }
3005
3006 // Check the result.
3007 if (status) {
3008 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003009 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003010 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003011 "This is unexpected because the wait queue is empty, so the pipe "
3012 "should be empty and we shouldn't have any problems writing an "
3013 "event to it, status=%d",
3014 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003015 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3016 } else {
3017 // Pipe is full and we are waiting for the app to finish process some events
3018 // before sending more events to it.
3019#if DEBUG_DISPATCH_CYCLE
3020 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003021 "waiting for the application to catch up",
3022 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003023#endif
Michael Wrightd02c5b62014-02-10 15:10:22 -08003024 }
3025 } else {
3026 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003027 "status=%d",
3028 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003029 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3030 }
3031 return;
3032 }
3033
3034 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003035 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
3036 connection->outboundQueue.end(),
3037 dispatchEntry));
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003038 traceOutboundQueueLength(connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003039 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003040 if (connection->responsive) {
3041 mAnrTracker.insert(dispatchEntry->timeoutTime,
3042 connection->inputChannel->getConnectionToken());
3043 }
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003044 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003045 }
3046}
3047
chaviw09c8d2d2020-08-24 15:48:26 -07003048std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
3049 size_t size;
3050 switch (event.type) {
3051 case VerifiedInputEvent::Type::KEY: {
3052 size = sizeof(VerifiedKeyEvent);
3053 break;
3054 }
3055 case VerifiedInputEvent::Type::MOTION: {
3056 size = sizeof(VerifiedMotionEvent);
3057 break;
3058 }
3059 }
3060 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
3061 return mHmacKeyManager.sign(start, size);
3062}
3063
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003064const std::array<uint8_t, 32> InputDispatcher::getSignature(
3065 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
3066 int32_t actionMasked = dispatchEntry.resolvedAction & AMOTION_EVENT_ACTION_MASK;
3067 if ((actionMasked == AMOTION_EVENT_ACTION_UP) || (actionMasked == AMOTION_EVENT_ACTION_DOWN)) {
3068 // Only sign events up and down events as the purely move events
3069 // are tied to their up/down counterparts so signing would be redundant.
3070 VerifiedMotionEvent verifiedEvent = verifiedMotionEventFromMotionEntry(motionEntry);
3071 verifiedEvent.actionMasked = actionMasked;
3072 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
chaviw09c8d2d2020-08-24 15:48:26 -07003073 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003074 }
3075 return INVALID_HMAC;
3076}
3077
3078const std::array<uint8_t, 32> InputDispatcher::getSignature(
3079 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
3080 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
3081 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
3082 verifiedEvent.action = dispatchEntry.resolvedAction;
chaviw09c8d2d2020-08-24 15:48:26 -07003083 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003084}
3085
Michael Wrightd02c5b62014-02-10 15:10:22 -08003086void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003087 const sp<Connection>& connection, uint32_t seq,
3088 bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003089#if DEBUG_DISPATCH_CYCLE
3090 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003091 connection->getInputChannelName().c_str(), seq, toString(handled));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003092#endif
3093
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003094 if (connection->status == Connection::STATUS_BROKEN ||
3095 connection->status == Connection::STATUS_ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003096 return;
3097 }
3098
3099 // Notify other system components and prepare to start the next dispatch cycle.
3100 onDispatchCycleFinishedLocked(currentTime, connection, seq, handled);
3101}
3102
3103void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003104 const sp<Connection>& connection,
3105 bool notify) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003106#if DEBUG_DISPATCH_CYCLE
3107 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003108 connection->getInputChannelName().c_str(), toString(notify));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003109#endif
3110
3111 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003112 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003113 traceOutboundQueueLength(connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003114 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003115 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003116
3117 // The connection appears to be unrecoverably broken.
3118 // Ignore already broken or zombie connections.
3119 if (connection->status == Connection::STATUS_NORMAL) {
3120 connection->status = Connection::STATUS_BROKEN;
3121
3122 if (notify) {
3123 // Notify other system components.
3124 onDispatchCycleBrokenLocked(currentTime, connection);
3125 }
3126 }
3127}
3128
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003129void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
3130 while (!queue.empty()) {
3131 DispatchEntry* dispatchEntry = queue.front();
3132 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003133 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003134 }
3135}
3136
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003137void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003138 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003139 decrementPendingForegroundDispatches(*(dispatchEntry->eventEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003140 }
3141 delete dispatchEntry;
3142}
3143
3144int InputDispatcher::handleReceiveCallback(int fd, int events, void* data) {
3145 InputDispatcher* d = static_cast<InputDispatcher*>(data);
3146
3147 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003148 std::scoped_lock _l(d->mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003149
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003150 if (d->mConnectionsByFd.find(fd) == d->mConnectionsByFd.end()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003151 ALOGE("Received spurious receive callback for unknown input channel. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003152 "fd=%d, events=0x%x",
3153 fd, events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003154 return 0; // remove the callback
3155 }
3156
3157 bool notify;
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003158 sp<Connection> connection = d->mConnectionsByFd[fd];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003159 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
3160 if (!(events & ALOOPER_EVENT_INPUT)) {
3161 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003162 "events=0x%x",
3163 connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003164 return 1;
3165 }
3166
3167 nsecs_t currentTime = now();
3168 bool gotOne = false;
3169 status_t status;
3170 for (;;) {
3171 uint32_t seq;
3172 bool handled;
3173 status = connection->inputPublisher.receiveFinishedSignal(&seq, &handled);
3174 if (status) {
3175 break;
3176 }
3177 d->finishDispatchCycleLocked(currentTime, connection, seq, handled);
3178 gotOne = true;
3179 }
3180 if (gotOne) {
3181 d->runCommandsLockedInterruptible();
3182 if (status == WOULD_BLOCK) {
3183 return 1;
3184 }
3185 }
3186
3187 notify = status != DEAD_OBJECT || !connection->monitor;
3188 if (notify) {
3189 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003190 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003191 }
3192 } else {
3193 // Monitor channels are never explicitly unregistered.
3194 // We do it automatically when the remote endpoint is closed so don't warn
3195 // about them.
arthurhungd352cb32020-04-28 17:09:28 +08003196 const bool stillHaveWindowHandle =
3197 d->getWindowHandleLocked(connection->inputChannel->getConnectionToken()) !=
3198 nullptr;
3199 notify = !connection->monitor && stillHaveWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003200 if (notify) {
3201 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003202 "events=0x%x",
3203 connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003204 }
3205 }
3206
Garfield Tan15601662020-09-22 15:32:38 -07003207 // Remove the channel.
3208 d->removeInputChannelLocked(connection->inputChannel->getConnectionToken(), notify);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003209 return 0; // remove the callback
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003210 } // release lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08003211}
3212
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003213void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08003214 const CancelationOptions& options) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003215 for (const auto& pair : mConnectionsByFd) {
3216 synthesizeCancelationEventsForConnectionLocked(pair.second, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003217 }
3218}
3219
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003220void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003221 const CancelationOptions& options) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003222 synthesizeCancelationEventsForMonitorsLocked(options, mGlobalMonitorsByDisplay);
3223 synthesizeCancelationEventsForMonitorsLocked(options, mGestureMonitorsByDisplay);
3224}
3225
3226void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
3227 const CancelationOptions& options,
3228 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
3229 for (const auto& it : monitorsByDisplay) {
3230 const std::vector<Monitor>& monitors = it.second;
3231 for (const Monitor& monitor : monitors) {
3232 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003233 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003234 }
3235}
3236
Michael Wrightd02c5b62014-02-10 15:10:22 -08003237void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003238 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07003239 sp<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003240 if (connection == nullptr) {
3241 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003242 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003243
3244 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003245}
3246
3247void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
3248 const sp<Connection>& connection, const CancelationOptions& options) {
3249 if (connection->status == Connection::STATUS_BROKEN) {
3250 return;
3251 }
3252
3253 nsecs_t currentTime = now();
3254
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003255 std::vector<std::unique_ptr<EventEntry>> cancelationEvents =
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07003256 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003257
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003258 if (cancelationEvents.empty()) {
3259 return;
3260 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003261#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003262 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
3263 "with reality: %s, mode=%d.",
3264 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
3265 options.mode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003266#endif
Svet Ganov5d3bc372020-01-26 23:11:07 -08003267
3268 InputTarget target;
3269 sp<InputWindowHandle> windowHandle =
3270 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3271 if (windowHandle != nullptr) {
3272 const InputWindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003273 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003274 target.globalScaleFactor = windowInfo->globalScaleFactor;
3275 }
3276 target.inputChannel = connection->inputChannel;
3277 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3278
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003279 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003280 std::unique_ptr<EventEntry> cancelationEventEntry = std::move(cancelationEvents[i]);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003281 switch (cancelationEventEntry->type) {
3282 case EventEntry::Type::KEY: {
3283 logOutboundKeyDetails("cancel - ",
3284 static_cast<const KeyEntry&>(*cancelationEventEntry));
3285 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003286 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003287 case EventEntry::Type::MOTION: {
3288 logOutboundMotionDetails("cancel - ",
3289 static_cast<const MotionEntry&>(*cancelationEventEntry));
3290 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003291 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003292 case EventEntry::Type::FOCUS:
3293 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3294 LOG_ALWAYS_FATAL("Canceling %s events is not supported",
Chris Yef59a2f42020-10-16 12:55:26 -07003295 NamedEnum::string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003296 break;
3297 }
3298 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003299 case EventEntry::Type::DEVICE_RESET:
3300 case EventEntry::Type::SENSOR: {
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003301 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Chris Yef59a2f42020-10-16 12:55:26 -07003302 NamedEnum::string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003303 break;
3304 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003305 }
3306
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003307 enqueueDispatchEntryLocked(connection, std::move(cancelationEventEntry), target,
3308 InputTarget::FLAG_DISPATCH_AS_IS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003309 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003310
3311 startDispatchCycleLocked(currentTime, connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003312}
3313
Svet Ganov5d3bc372020-01-26 23:11:07 -08003314void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
3315 const sp<Connection>& connection) {
3316 if (connection->status == Connection::STATUS_BROKEN) {
3317 return;
3318 }
3319
3320 nsecs_t currentTime = now();
3321
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003322 std::vector<std::unique_ptr<EventEntry>> downEvents =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003323 connection->inputState.synthesizePointerDownEvents(currentTime);
3324
3325 if (downEvents.empty()) {
3326 return;
3327 }
3328
3329#if DEBUG_OUTBOUND_EVENT_DETAILS
3330 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
3331 connection->getInputChannelName().c_str(), downEvents.size());
3332#endif
3333
3334 InputTarget target;
3335 sp<InputWindowHandle> windowHandle =
3336 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3337 if (windowHandle != nullptr) {
3338 const InputWindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003339 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003340 target.globalScaleFactor = windowInfo->globalScaleFactor;
3341 }
3342 target.inputChannel = connection->inputChannel;
3343 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3344
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003345 for (std::unique_ptr<EventEntry>& downEventEntry : downEvents) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003346 switch (downEventEntry->type) {
3347 case EventEntry::Type::MOTION: {
3348 logOutboundMotionDetails("down - ",
3349 static_cast<const MotionEntry&>(*downEventEntry));
3350 break;
3351 }
3352
3353 case EventEntry::Type::KEY:
3354 case EventEntry::Type::FOCUS:
3355 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08003356 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07003357 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3358 case EventEntry::Type::SENSOR: {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003359 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Chris Yef59a2f42020-10-16 12:55:26 -07003360 NamedEnum::string(downEventEntry->type).c_str());
Svet Ganov5d3bc372020-01-26 23:11:07 -08003361 break;
3362 }
3363 }
3364
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003365 enqueueDispatchEntryLocked(connection, std::move(downEventEntry), target,
3366 InputTarget::FLAG_DISPATCH_AS_IS);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003367 }
3368
3369 startDispatchCycleLocked(currentTime, connection);
3370}
3371
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003372std::unique_ptr<MotionEntry> InputDispatcher::splitMotionEvent(
3373 const MotionEntry& originalMotionEntry, BitSet32 pointerIds) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003374 ALOG_ASSERT(pointerIds.value != 0);
3375
3376 uint32_t splitPointerIndexMap[MAX_POINTERS];
3377 PointerProperties splitPointerProperties[MAX_POINTERS];
3378 PointerCoords splitPointerCoords[MAX_POINTERS];
3379
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003380 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003381 uint32_t splitPointerCount = 0;
3382
3383 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003384 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003385 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003386 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003387 uint32_t pointerId = uint32_t(pointerProperties.id);
3388 if (pointerIds.hasBit(pointerId)) {
3389 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
3390 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
3391 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003392 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003393 splitPointerCount += 1;
3394 }
3395 }
3396
3397 if (splitPointerCount != pointerIds.count()) {
3398 // This is bad. We are missing some of the pointers that we expected to deliver.
3399 // Most likely this indicates that we received an ACTION_MOVE events that has
3400 // different pointer ids than we expected based on the previous ACTION_DOWN
3401 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
3402 // in this way.
3403 ALOGW("Dropping split motion event because the pointer count is %d but "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003404 "we expected there to be %d pointers. This probably means we received "
3405 "a broken sequence of pointer ids from the input device.",
3406 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07003407 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003408 }
3409
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003410 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003411 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003412 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
3413 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003414 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
3415 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003416 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003417 uint32_t pointerId = uint32_t(pointerProperties.id);
3418 if (pointerIds.hasBit(pointerId)) {
3419 if (pointerIds.count() == 1) {
3420 // The first/last pointer went down/up.
3421 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003422 ? AMOTION_EVENT_ACTION_DOWN
3423 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003424 } else {
3425 // A secondary pointer went down/up.
3426 uint32_t splitPointerIndex = 0;
3427 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
3428 splitPointerIndex += 1;
3429 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003430 action = maskedAction |
3431 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003432 }
3433 } else {
3434 // An unrelated pointer changed.
3435 action = AMOTION_EVENT_ACTION_MOVE;
3436 }
3437 }
3438
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003439 int32_t newId = mIdGenerator.nextId();
3440 if (ATRACE_ENABLED()) {
3441 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
3442 ") to MotionEvent(id=0x%" PRIx32 ").",
3443 originalMotionEntry.id, newId);
3444 ATRACE_NAME(message.c_str());
3445 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003446 std::unique_ptr<MotionEntry> splitMotionEntry =
3447 std::make_unique<MotionEntry>(newId, originalMotionEntry.eventTime,
3448 originalMotionEntry.deviceId, originalMotionEntry.source,
3449 originalMotionEntry.displayId,
3450 originalMotionEntry.policyFlags, action,
3451 originalMotionEntry.actionButton,
3452 originalMotionEntry.flags, originalMotionEntry.metaState,
3453 originalMotionEntry.buttonState,
3454 originalMotionEntry.classification,
3455 originalMotionEntry.edgeFlags,
3456 originalMotionEntry.xPrecision,
3457 originalMotionEntry.yPrecision,
3458 originalMotionEntry.xCursorPosition,
3459 originalMotionEntry.yCursorPosition,
3460 originalMotionEntry.downTime, splitPointerCount,
3461 splitPointerProperties, splitPointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003462
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003463 if (originalMotionEntry.injectionState) {
3464 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003465 splitMotionEntry->injectionState->refCount += 1;
3466 }
3467
3468 return splitMotionEntry;
3469}
3470
3471void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
3472#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003473 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003474#endif
3475
3476 bool needWake;
3477 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003478 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003479
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003480 std::unique_ptr<ConfigurationChangedEntry> newEntry =
3481 std::make_unique<ConfigurationChangedEntry>(args->id, args->eventTime);
3482 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003483 } // release lock
3484
3485 if (needWake) {
3486 mLooper->wake();
3487 }
3488}
3489
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003490/**
3491 * If one of the meta shortcuts is detected, process them here:
3492 * Meta + Backspace -> generate BACK
3493 * Meta + Enter -> generate HOME
3494 * This will potentially overwrite keyCode and metaState.
3495 */
3496void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003497 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003498 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
3499 int32_t newKeyCode = AKEYCODE_UNKNOWN;
3500 if (keyCode == AKEYCODE_DEL) {
3501 newKeyCode = AKEYCODE_BACK;
3502 } else if (keyCode == AKEYCODE_ENTER) {
3503 newKeyCode = AKEYCODE_HOME;
3504 }
3505 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003506 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003507 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003508 mReplacedKeys[replacement] = newKeyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003509 keyCode = newKeyCode;
3510 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3511 }
3512 } else if (action == AKEY_EVENT_ACTION_UP) {
3513 // In order to maintain a consistent stream of up and down events, check to see if the key
3514 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
3515 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003516 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003517 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003518 auto replacementIt = mReplacedKeys.find(replacement);
3519 if (replacementIt != mReplacedKeys.end()) {
3520 keyCode = replacementIt->second;
3521 mReplacedKeys.erase(replacementIt);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003522 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3523 }
3524 }
3525}
3526
Michael Wrightd02c5b62014-02-10 15:10:22 -08003527void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
3528#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003529 ALOGD("notifyKey - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
3530 "policyFlags=0x%x, action=0x%x, "
3531 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
3532 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
3533 args->action, args->flags, args->keyCode, args->scanCode, args->metaState,
3534 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003535#endif
3536 if (!validateKeyEvent(args->action)) {
3537 return;
3538 }
3539
3540 uint32_t policyFlags = args->policyFlags;
3541 int32_t flags = args->flags;
3542 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07003543 // InputDispatcher tracks and generates key repeats on behalf of
3544 // whatever notifies it, so repeatCount should always be set to 0
3545 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003546 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
3547 policyFlags |= POLICY_FLAG_VIRTUAL;
3548 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
3549 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003550 if (policyFlags & POLICY_FLAG_FUNCTION) {
3551 metaState |= AMETA_FUNCTION_ON;
3552 }
3553
3554 policyFlags |= POLICY_FLAG_TRUSTED;
3555
Michael Wright78f24442014-08-06 15:55:28 -07003556 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003557 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07003558
Michael Wrightd02c5b62014-02-10 15:10:22 -08003559 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003560 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08003561 args->action, flags, keyCode, args->scanCode, metaState, repeatCount,
3562 args->downTime, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003563
Michael Wright2b3c3302018-03-02 17:19:13 +00003564 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003565 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003566 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3567 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003568 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003569 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003570
Michael Wrightd02c5b62014-02-10 15:10:22 -08003571 bool needWake;
3572 { // acquire lock
3573 mLock.lock();
3574
3575 if (shouldSendKeyToInputFilterLocked(args)) {
3576 mLock.unlock();
3577
3578 policyFlags |= POLICY_FLAG_FILTERED;
3579 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3580 return; // event was consumed by the filter
3581 }
3582
3583 mLock.lock();
3584 }
3585
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003586 std::unique_ptr<KeyEntry> newEntry =
3587 std::make_unique<KeyEntry>(args->id, args->eventTime, args->deviceId, args->source,
3588 args->displayId, policyFlags, args->action, flags,
3589 keyCode, args->scanCode, metaState, repeatCount,
3590 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003591
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003592 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003593 mLock.unlock();
3594 } // release lock
3595
3596 if (needWake) {
3597 mLooper->wake();
3598 }
3599}
3600
3601bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
3602 return mInputFilterEnabled;
3603}
3604
3605void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
3606#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003607 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
3608 "displayId=%" PRId32 ", policyFlags=0x%x, "
Garfield Tan00f511d2019-06-12 16:55:40 -07003609 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
3610 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
Garfield Tanab0ab9c2019-07-10 18:58:28 -07003611 "yCursorPosition=%f, downTime=%" PRId64,
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003612 args->id, args->eventTime, args->deviceId, args->source, args->displayId,
3613 args->policyFlags, args->action, args->actionButton, args->flags, args->metaState,
3614 args->buttonState, args->edgeFlags, args->xPrecision, args->yPrecision,
3615 args->xCursorPosition, args->yCursorPosition, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003616 for (uint32_t i = 0; i < args->pointerCount; i++) {
3617 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003618 "x=%f, y=%f, pressure=%f, size=%f, "
3619 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
3620 "orientation=%f",
3621 i, args->pointerProperties[i].id, args->pointerProperties[i].toolType,
3622 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
3623 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
3624 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
3625 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
3626 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
3627 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
3628 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
3629 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
3630 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003631 }
3632#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003633 if (!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
3634 args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003635 return;
3636 }
3637
3638 uint32_t policyFlags = args->policyFlags;
3639 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003640
3641 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08003642 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003643 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3644 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003645 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003646 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003647
3648 bool needWake;
3649 { // acquire lock
3650 mLock.lock();
3651
3652 if (shouldSendMotionToInputFilterLocked(args)) {
3653 mLock.unlock();
3654
3655 MotionEvent event;
chaviw9eaa22c2020-07-01 16:21:27 -07003656 ui::Transform transform;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003657 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
3658 args->action, args->actionButton, args->flags, args->edgeFlags,
chaviw9eaa22c2020-07-01 16:21:27 -07003659 args->metaState, args->buttonState, args->classification, transform,
3660 args->xPrecision, args->yPrecision, args->xCursorPosition,
3661 args->yCursorPosition, args->downTime, args->eventTime,
3662 args->pointerCount, args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003663
3664 policyFlags |= POLICY_FLAG_FILTERED;
3665 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3666 return; // event was consumed by the filter
3667 }
3668
3669 mLock.lock();
3670 }
3671
3672 // Just enqueue a new motion event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003673 std::unique_ptr<MotionEntry> newEntry =
3674 std::make_unique<MotionEntry>(args->id, args->eventTime, args->deviceId,
3675 args->source, args->displayId, policyFlags,
3676 args->action, args->actionButton, args->flags,
3677 args->metaState, args->buttonState,
3678 args->classification, args->edgeFlags,
3679 args->xPrecision, args->yPrecision,
3680 args->xCursorPosition, args->yCursorPosition,
3681 args->downTime, args->pointerCount,
3682 args->pointerProperties, args->pointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003683
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003684 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003685 mLock.unlock();
3686 } // release lock
3687
3688 if (needWake) {
3689 mLooper->wake();
3690 }
3691}
3692
Chris Yef59a2f42020-10-16 12:55:26 -07003693void InputDispatcher::notifySensor(const NotifySensorArgs* args) {
3694#if DEBUG_INBOUND_EVENT_DETAILS
3695 ALOGD("notifySensor - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
3696 " sensorType=%s",
3697 args->id, args->eventTime, args->deviceId, args->source,
3698 NamedEnum::string(args->sensorType).c_str());
3699#endif
3700
3701 bool needWake;
3702 { // acquire lock
3703 mLock.lock();
3704
3705 // Just enqueue a new sensor event.
3706 std::unique_ptr<SensorEntry> newEntry =
3707 std::make_unique<SensorEntry>(args->id, args->eventTime, args->deviceId,
3708 args->source, 0 /* policyFlags*/, args->hwTimestamp,
3709 args->sensorType, args->accuracy,
3710 args->accuracyChanged, args->values);
3711
3712 needWake = enqueueInboundEventLocked(std::move(newEntry));
3713 mLock.unlock();
3714 } // release lock
3715
3716 if (needWake) {
3717 mLooper->wake();
3718 }
3719}
3720
Michael Wrightd02c5b62014-02-10 15:10:22 -08003721bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08003722 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003723}
3724
3725void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
3726#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003727 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003728 "switchMask=0x%08x",
3729 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003730#endif
3731
3732 uint32_t policyFlags = args->policyFlags;
3733 policyFlags |= POLICY_FLAG_TRUSTED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003734 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003735}
3736
3737void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
3738#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003739 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
3740 args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003741#endif
3742
3743 bool needWake;
3744 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003745 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003746
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003747 std::unique_ptr<DeviceResetEntry> newEntry =
3748 std::make_unique<DeviceResetEntry>(args->id, args->eventTime, args->deviceId);
3749 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003750 } // release lock
3751
3752 if (needWake) {
3753 mLooper->wake();
3754 }
3755}
3756
Prabir Pradhan7e186182020-11-10 13:56:45 -08003757void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs* args) {
3758#if DEBUG_INBOUND_EVENT_DETAILS
3759 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args->eventTime,
3760 args->enabled ? "true" : "false");
3761#endif
3762
Prabir Pradhan99987712020-11-10 18:43:05 -08003763 bool needWake;
3764 { // acquire lock
3765 std::scoped_lock _l(mLock);
3766 auto entry = std::make_unique<PointerCaptureChangedEntry>(args->id, args->eventTime,
3767 args->enabled);
3768 needWake = enqueueInboundEventLocked(std::move(entry));
3769 } // release lock
3770
3771 if (needWake) {
3772 mLooper->wake();
3773 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08003774}
3775
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003776InputEventInjectionResult InputDispatcher::injectInputEvent(
3777 const InputEvent* event, int32_t injectorPid, int32_t injectorUid,
3778 InputEventInjectionSync syncMode, std::chrono::milliseconds timeout, uint32_t policyFlags) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003779#if DEBUG_INBOUND_EVENT_DETAILS
3780 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003781 "syncMode=%d, timeout=%lld, policyFlags=0x%08x",
3782 event->getType(), injectorPid, injectorUid, syncMode, timeout.count(), policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003783#endif
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003784 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003785
3786 policyFlags |= POLICY_FLAG_INJECTED;
3787 if (hasInjectionPermission(injectorPid, injectorUid)) {
3788 policyFlags |= POLICY_FLAG_TRUSTED;
3789 }
3790
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003791 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003792 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003793 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003794 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
3795 int32_t action = incomingKey.getAction();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003796 if (!validateKeyEvent(action)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003797 return InputEventInjectionResult::FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003798 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003799
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003800 int32_t flags = incomingKey.getFlags();
3801 int32_t keyCode = incomingKey.getKeyCode();
3802 int32_t metaState = incomingKey.getMetaState();
3803 accelerateMetaShortcuts(VIRTUAL_KEYBOARD_ID, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003804 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003805 KeyEvent keyEvent;
Garfield Tan4cc839f2020-01-24 11:26:14 -08003806 keyEvent.initialize(incomingKey.getId(), VIRTUAL_KEYBOARD_ID, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003807 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
3808 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
3809 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003810
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003811 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
3812 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00003813 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003814
3815 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
3816 android::base::Timer t;
3817 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
3818 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3819 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
3820 std::to_string(t.duration().count()).c_str());
3821 }
3822 }
3823
3824 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003825 std::unique_ptr<KeyEntry> injectedEntry =
3826 std::make_unique<KeyEntry>(incomingKey.getId(), incomingKey.getEventTime(),
3827 VIRTUAL_KEYBOARD_ID, incomingKey.getSource(),
3828 incomingKey.getDisplayId(), policyFlags, action,
3829 flags, keyCode, incomingKey.getScanCode(), metaState,
3830 incomingKey.getRepeatCount(),
3831 incomingKey.getDownTime());
3832 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003833 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003834 }
3835
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003836 case AINPUT_EVENT_TYPE_MOTION: {
3837 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
3838 int32_t action = motionEvent->getAction();
3839 size_t pointerCount = motionEvent->getPointerCount();
3840 const PointerProperties* pointerProperties = motionEvent->getPointerProperties();
3841 int32_t actionButton = motionEvent->getActionButton();
3842 int32_t displayId = motionEvent->getDisplayId();
3843 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003844 return InputEventInjectionResult::FAILED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003845 }
3846
3847 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
3848 nsecs_t eventTime = motionEvent->getEventTime();
3849 android::base::Timer t;
3850 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
3851 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3852 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
3853 std::to_string(t.duration().count()).c_str());
3854 }
3855 }
3856
3857 mLock.lock();
3858 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
3859 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003860 std::unique_ptr<MotionEntry> injectedEntry =
3861 std::make_unique<MotionEntry>(motionEvent->getId(), *sampleEventTimes,
3862 VIRTUAL_KEYBOARD_ID, motionEvent->getSource(),
3863 motionEvent->getDisplayId(), policyFlags, action,
3864 actionButton, motionEvent->getFlags(),
3865 motionEvent->getMetaState(),
3866 motionEvent->getButtonState(),
3867 motionEvent->getClassification(),
3868 motionEvent->getEdgeFlags(),
3869 motionEvent->getXPrecision(),
3870 motionEvent->getYPrecision(),
3871 motionEvent->getRawXCursorPosition(),
3872 motionEvent->getRawYCursorPosition(),
3873 motionEvent->getDownTime(),
3874 uint32_t(pointerCount), pointerProperties,
3875 samplePointerCoords, motionEvent->getXOffset(),
3876 motionEvent->getYOffset());
3877 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003878 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
3879 sampleEventTimes += 1;
3880 samplePointerCoords += pointerCount;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003881 std::unique_ptr<MotionEntry> nextInjectedEntry =
3882 std::make_unique<MotionEntry>(motionEvent->getId(), *sampleEventTimes,
3883 VIRTUAL_KEYBOARD_ID, motionEvent->getSource(),
3884 motionEvent->getDisplayId(), policyFlags,
3885 action, 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,
3897 motionEvent->getXOffset(),
3898 motionEvent->getYOffset());
3899 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003900 }
3901 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003902 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003903
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003904 default:
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08003905 ALOGW("Cannot inject %s events", inputEventTypeToString(event->getType()));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003906 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003907 }
3908
3909 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003910 if (syncMode == InputEventInjectionSync::NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003911 injectionState->injectionIsAsync = true;
3912 }
3913
3914 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003915 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003916
3917 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003918 while (!injectedEntries.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003919 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003920 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003921 }
3922
3923 mLock.unlock();
3924
3925 if (needWake) {
3926 mLooper->wake();
3927 }
3928
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003929 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003930 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003931 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003932
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003933 if (syncMode == InputEventInjectionSync::NONE) {
3934 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003935 } else {
3936 for (;;) {
3937 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003938 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003939 break;
3940 }
3941
3942 nsecs_t remainingTimeout = endTime - now();
3943 if (remainingTimeout <= 0) {
3944#if DEBUG_INJECTION
3945 ALOGD("injectInputEvent - Timed out waiting for injection result "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003946 "to become available.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003947#endif
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003948 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003949 break;
3950 }
3951
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003952 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003953 }
3954
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003955 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
3956 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003957 while (injectionState->pendingForegroundDispatches != 0) {
3958#if DEBUG_INJECTION
3959 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003960 injectionState->pendingForegroundDispatches);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003961#endif
3962 nsecs_t remainingTimeout = endTime - now();
3963 if (remainingTimeout <= 0) {
3964#if DEBUG_INJECTION
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003965 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
3966 "dispatches to finish.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003967#endif
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003968 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003969 break;
3970 }
3971
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003972 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003973 }
3974 }
3975 }
3976
3977 injectionState->release();
3978 } // release lock
3979
3980#if DEBUG_INJECTION
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003981 ALOGD("injectInputEvent - Finished with result %d. injectorPid=%d, injectorUid=%d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003982 injectionResult, injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003983#endif
3984
3985 return injectionResult;
3986}
3987
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08003988std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05003989 std::array<uint8_t, 32> calculatedHmac;
3990 std::unique_ptr<VerifiedInputEvent> result;
3991 switch (event.getType()) {
3992 case AINPUT_EVENT_TYPE_KEY: {
3993 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
3994 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
3995 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07003996 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05003997 break;
3998 }
3999 case AINPUT_EVENT_TYPE_MOTION: {
4000 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
4001 VerifiedMotionEvent verifiedMotionEvent =
4002 verifiedMotionEventFromMotionEvent(motionEvent);
4003 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004004 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05004005 break;
4006 }
4007 default: {
4008 ALOGE("Cannot verify events of type %" PRId32, event.getType());
4009 return nullptr;
4010 }
4011 }
4012 if (calculatedHmac == INVALID_HMAC) {
4013 return nullptr;
4014 }
4015 if (calculatedHmac != event.getHmac()) {
4016 return nullptr;
4017 }
4018 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004019}
4020
Michael Wrightd02c5b62014-02-10 15:10:22 -08004021bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004022 return injectorUid == 0 ||
4023 mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004024}
4025
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004026void InputDispatcher::setInjectionResult(EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004027 InputEventInjectionResult injectionResult) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004028 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004029 if (injectionState) {
4030#if DEBUG_INJECTION
4031 ALOGD("Setting input event injection result to %d. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004032 "injectorPid=%d, injectorUid=%d",
4033 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004034#endif
4035
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004036 if (injectionState->injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004037 // Log the outcome since the injector did not wait for the injection result.
4038 switch (injectionResult) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004039 case InputEventInjectionResult::SUCCEEDED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004040 ALOGV("Asynchronous input event injection succeeded.");
4041 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004042 case InputEventInjectionResult::FAILED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004043 ALOGW("Asynchronous input event injection failed.");
4044 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004045 case InputEventInjectionResult::PERMISSION_DENIED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004046 ALOGW("Asynchronous input event injection permission denied.");
4047 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004048 case InputEventInjectionResult::TIMED_OUT:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004049 ALOGW("Asynchronous input event injection timed out.");
4050 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004051 case InputEventInjectionResult::PENDING:
4052 ALOGE("Setting result to 'PENDING' for asynchronous injection");
4053 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004054 }
4055 }
4056
4057 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004058 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004059 }
4060}
4061
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004062void InputDispatcher::incrementPendingForegroundDispatches(EventEntry& entry) {
4063 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004064 if (injectionState) {
4065 injectionState->pendingForegroundDispatches += 1;
4066 }
4067}
4068
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004069void InputDispatcher::decrementPendingForegroundDispatches(EventEntry& entry) {
4070 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004071 if (injectionState) {
4072 injectionState->pendingForegroundDispatches -= 1;
4073
4074 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004075 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004076 }
4077 }
4078}
4079
Vishnu Nairad321cd2020-08-20 16:40:21 -07004080const std::vector<sp<InputWindowHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004081 int32_t displayId) const {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004082 static const std::vector<sp<InputWindowHandle>> EMPTY_WINDOW_HANDLES;
4083 auto it = mWindowHandlesByDisplay.find(displayId);
4084 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08004085}
4086
Michael Wrightd02c5b62014-02-10 15:10:22 -08004087sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08004088 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08004089 if (windowHandleToken == nullptr) {
4090 return nullptr;
4091 }
4092
Arthur Hungb92218b2018-08-14 12:00:21 +08004093 for (auto& it : mWindowHandlesByDisplay) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004094 const std::vector<sp<InputWindowHandle>>& windowHandles = it.second;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004095 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004096 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004097 return windowHandle;
4098 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004099 }
4100 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004101 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004102}
4103
Vishnu Nairad321cd2020-08-20 16:40:21 -07004104sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(const sp<IBinder>& windowHandleToken,
4105 int displayId) const {
4106 if (windowHandleToken == nullptr) {
4107 return nullptr;
4108 }
4109
4110 for (const sp<InputWindowHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
4111 if (windowHandle->getToken() == windowHandleToken) {
4112 return windowHandle;
4113 }
4114 }
4115 return nullptr;
4116}
4117
4118sp<InputWindowHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
4119 sp<IBinder> focusedToken = getValueByKey(mFocusedWindowTokenByDisplay, displayId);
4120 return getWindowHandleLocked(focusedToken, displayId);
4121}
4122
Mady Mellor017bcd12020-06-23 19:12:00 +00004123bool InputDispatcher::hasWindowHandleLocked(const sp<InputWindowHandle>& windowHandle) const {
4124 for (auto& it : mWindowHandlesByDisplay) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004125 const std::vector<sp<InputWindowHandle>>& windowHandles = it.second;
Mady Mellor017bcd12020-06-23 19:12:00 +00004126 for (const sp<InputWindowHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08004127 if (handle->getId() == windowHandle->getId() &&
4128 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004129 if (windowHandle->getInfo()->displayId != it.first) {
4130 ALOGE("Found window %s in display %" PRId32
4131 ", but it should belong to display %" PRId32,
4132 windowHandle->getName().c_str(), it.first,
4133 windowHandle->getInfo()->displayId);
4134 }
4135 return true;
Arthur Hungb92218b2018-08-14 12:00:21 +08004136 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004137 }
4138 }
4139 return false;
4140}
4141
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004142bool InputDispatcher::hasResponsiveConnectionLocked(InputWindowHandle& windowHandle) const {
4143 sp<Connection> connection = getConnectionLocked(windowHandle.getToken());
4144 const bool noInputChannel =
4145 windowHandle.getInfo()->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
4146 if (connection != nullptr && noInputChannel) {
4147 ALOGW("%s has feature NO_INPUT_CHANNEL, but it matched to connection %s",
4148 windowHandle.getName().c_str(), connection->inputChannel->getName().c_str());
4149 return false;
4150 }
4151
4152 if (connection == nullptr) {
4153 if (!noInputChannel) {
4154 ALOGI("Could not find connection for %s", windowHandle.getName().c_str());
4155 }
4156 return false;
4157 }
4158 if (!connection->responsive) {
4159 ALOGW("Window %s is not responsive", windowHandle.getName().c_str());
4160 return false;
4161 }
4162 return true;
4163}
4164
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004165std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
4166 const sp<IBinder>& token) const {
Robert Carr5c8a0262018-10-03 16:30:44 -07004167 size_t count = mInputChannelsByToken.count(token);
4168 if (count == 0) {
4169 return nullptr;
4170 }
4171 return mInputChannelsByToken.at(token);
4172}
4173
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004174void InputDispatcher::updateWindowHandlesForDisplayLocked(
4175 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
4176 if (inputWindowHandles.empty()) {
4177 // Remove all handles on a display if there are no windows left.
4178 mWindowHandlesByDisplay.erase(displayId);
4179 return;
4180 }
4181
4182 // Since we compare the pointer of input window handles across window updates, we need
4183 // to make sure the handle object for the same window stays unchanged across updates.
4184 const std::vector<sp<InputWindowHandle>>& oldHandles = getWindowHandlesLocked(displayId);
chaviwaf87b3e2019-10-01 16:59:28 -07004185 std::unordered_map<int32_t /*id*/, sp<InputWindowHandle>> oldHandlesById;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004186 for (const sp<InputWindowHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07004187 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004188 }
4189
4190 std::vector<sp<InputWindowHandle>> newHandles;
4191 for (const sp<InputWindowHandle>& handle : inputWindowHandles) {
4192 if (!handle->updateInfo()) {
4193 // handle no longer valid
4194 continue;
4195 }
4196
4197 const InputWindowInfo* info = handle->getInfo();
4198 if ((getInputChannelLocked(handle->getToken()) == nullptr &&
4199 info->portalToDisplayId == ADISPLAY_ID_NONE)) {
4200 const bool noInputChannel =
Michael Wright44753b12020-07-08 13:48:11 +01004201 info->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
4202 const bool canReceiveInput = !info->flags.test(InputWindowInfo::Flag::NOT_TOUCHABLE) ||
4203 !info->flags.test(InputWindowInfo::Flag::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004204 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07004205 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004206 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07004207 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004208 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004209 }
4210
4211 if (info->displayId != displayId) {
4212 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
4213 handle->getName().c_str(), displayId, info->displayId);
4214 continue;
4215 }
4216
Robert Carredd13602020-04-13 17:24:34 -07004217 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
4218 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviwaf87b3e2019-10-01 16:59:28 -07004219 const sp<InputWindowHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004220 oldHandle->updateFrom(handle);
4221 newHandles.push_back(oldHandle);
4222 } else {
4223 newHandles.push_back(handle);
4224 }
4225 }
4226
4227 // Insert or replace
4228 mWindowHandlesByDisplay[displayId] = newHandles;
4229}
4230
Arthur Hung72d8dc32020-03-28 00:48:39 +00004231void InputDispatcher::setInputWindows(
4232 const std::unordered_map<int32_t, std::vector<sp<InputWindowHandle>>>& handlesPerDisplay) {
4233 { // acquire lock
4234 std::scoped_lock _l(mLock);
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004235 for (const auto& [displayId, handles] : handlesPerDisplay) {
4236 setInputWindowsLocked(handles, displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004237 }
4238 }
4239 // Wake up poll loop since it may need to make new input dispatching choices.
4240 mLooper->wake();
4241}
4242
Arthur Hungb92218b2018-08-14 12:00:21 +08004243/**
4244 * Called from InputManagerService, update window handle list by displayId that can receive input.
4245 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
4246 * If set an empty list, remove all handles from the specific display.
4247 * For focused handle, check if need to change and send a cancel event to previous one.
4248 * For removed handle, check if need to send a cancel event if already in touch.
4249 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00004250void InputDispatcher::setInputWindowsLocked(
4251 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004252 if (DEBUG_FOCUS) {
4253 std::string windowList;
4254 for (const sp<InputWindowHandle>& iwh : inputWindowHandles) {
4255 windowList += iwh->getName() + " ";
4256 }
4257 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
4258 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004259
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004260 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
4261 for (const sp<InputWindowHandle>& window : inputWindowHandles) {
4262 const bool noInputWindow =
4263 window->getInfo()->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
4264 if (noInputWindow && window->getToken() != nullptr) {
4265 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
4266 window->getName().c_str());
4267 window->releaseChannel();
4268 }
4269 }
4270
Arthur Hung72d8dc32020-03-28 00:48:39 +00004271 // Copy old handles for release if they are no longer present.
4272 const std::vector<sp<InputWindowHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004273
Arthur Hung72d8dc32020-03-28 00:48:39 +00004274 updateWindowHandlesForDisplayLocked(inputWindowHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004275
Vishnu Nair958da932020-08-21 17:12:37 -07004276 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
4277 if (mLastHoverWindowHandle &&
4278 std::find(windowHandles.begin(), windowHandles.end(), mLastHoverWindowHandle) ==
4279 windowHandles.end()) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004280 mLastHoverWindowHandle = nullptr;
4281 }
4282
Vishnu Nair958da932020-08-21 17:12:37 -07004283 sp<IBinder> focusedToken = getValueByKey(mFocusedWindowTokenByDisplay, displayId);
4284 if (focusedToken) {
4285 FocusResult result = checkTokenFocusableLocked(focusedToken, displayId);
4286 if (result != FocusResult::OK) {
4287 onFocusChangedLocked(focusedToken, nullptr, displayId, typeToString(result));
4288 }
4289 }
4290
4291 std::optional<FocusRequest> focusRequest =
4292 getOptionalValueByKey(mPendingFocusRequests, displayId);
4293 if (focusRequest) {
4294 // If the window from the pending request is now visible, provide it focus.
4295 FocusResult result = handleFocusRequestLocked(*focusRequest);
4296 if (result != FocusResult::NOT_VISIBLE) {
4297 // Drop the request if we were able to change the focus or we cannot change
4298 // it for another reason.
4299 mPendingFocusRequests.erase(displayId);
4300 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004301 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004302
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004303 std::unordered_map<int32_t, TouchState>::iterator stateIt =
4304 mTouchStatesByDisplay.find(displayId);
4305 if (stateIt != mTouchStatesByDisplay.end()) {
4306 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00004307 for (size_t i = 0; i < state.windows.size();) {
4308 TouchedWindow& touchedWindow = state.windows[i];
Mady Mellor017bcd12020-06-23 19:12:00 +00004309 if (!hasWindowHandleLocked(touchedWindow.windowHandle)) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004310 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004311 ALOGD("Touched window was removed: %s in display %" PRId32,
4312 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004313 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004314 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00004315 getInputChannelLocked(touchedWindow.windowHandle->getToken());
4316 if (touchedInputChannel != nullptr) {
4317 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4318 "touched window was removed");
4319 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004320 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004321 state.windows.erase(state.windows.begin() + i);
4322 } else {
4323 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004324 }
4325 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004326 }
Arthur Hung25e2af12020-03-26 12:58:37 +00004327
Arthur Hung72d8dc32020-03-28 00:48:39 +00004328 // Release information for windows that are no longer present.
4329 // This ensures that unused input channels are released promptly.
4330 // Otherwise, they might stick around until the window handle is destroyed
4331 // which might not happen until the next GC.
4332 for (const sp<InputWindowHandle>& oldWindowHandle : oldWindowHandles) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004333 if (!hasWindowHandleLocked(oldWindowHandle)) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004334 if (DEBUG_FOCUS) {
4335 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00004336 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004337 oldWindowHandle->releaseChannel();
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004338 // To avoid making too many calls into the compat framework, only
4339 // check for window flags when windows are going away.
4340 // TODO(b/157929241) : delete this. This is only needed temporarily
4341 // in order to gather some data about the flag usage
4342 if (oldWindowHandle->getInfo()->flags.test(InputWindowInfo::Flag::SLIPPERY)) {
4343 ALOGW("%s has FLAG_SLIPPERY. Please report this in b/157929241",
4344 oldWindowHandle->getName().c_str());
4345 if (mCompatService != nullptr) {
4346 mCompatService->reportChangeByUid(IInputConstants::BLOCK_FLAG_SLIPPERY,
4347 oldWindowHandle->getInfo()->ownerUid);
4348 }
4349 }
Arthur Hung25e2af12020-03-26 12:58:37 +00004350 }
chaviw291d88a2019-02-14 10:33:58 -08004351 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004352}
4353
4354void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07004355 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004356 if (DEBUG_FOCUS) {
4357 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
4358 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
4359 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004360 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004361 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004362
Chris Yea209fde2020-07-22 13:54:51 -07004363 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08004364 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004365
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004366 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
4367 return; // This application is already focused. No need to wake up or change anything.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004368 }
4369
Chris Yea209fde2020-07-22 13:54:51 -07004370 // Set the new application handle.
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004371 if (inputApplicationHandle != nullptr) {
4372 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
4373 } else {
4374 mFocusedApplicationHandlesByDisplay.erase(displayId);
4375 }
4376
4377 // No matter what the old focused application was, stop waiting on it because it is
4378 // no longer focused.
4379 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004380 } // release lock
4381
4382 // Wake up poll loop since it may need to make new input dispatching choices.
4383 mLooper->wake();
4384}
4385
Tiger Huang721e26f2018-07-24 22:26:19 +08004386/**
4387 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
4388 * the display not specified.
4389 *
4390 * We track any unreleased events for each window. If a window loses the ability to receive the
4391 * released event, we will send a cancel event to it. So when the focused display is changed, we
4392 * cancel all the unreleased display-unspecified events for the focused window on the old focused
4393 * display. The display-specified events won't be affected.
4394 */
4395void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004396 if (DEBUG_FOCUS) {
4397 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
4398 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004399 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004400 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08004401
4402 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004403 sp<IBinder> oldFocusedWindowToken =
4404 getValueByKey(mFocusedWindowTokenByDisplay, mFocusedDisplayId);
4405 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004406 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07004407 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08004408 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004409 CancelationOptions
4410 options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
4411 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004412 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08004413 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
4414 }
4415 }
4416 mFocusedDisplayId = displayId;
4417
Chris Ye3c2d6f52020-08-09 10:39:48 -07004418 // Find new focused window and validate
Vishnu Nairad321cd2020-08-20 16:40:21 -07004419 sp<IBinder> newFocusedWindowToken =
4420 getValueByKey(mFocusedWindowTokenByDisplay, displayId);
4421 notifyFocusChangedLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08004422
Vishnu Nairad321cd2020-08-20 16:40:21 -07004423 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08004424 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07004425 if (!mFocusedWindowTokenByDisplay.empty()) {
4426 ALOGE("But another display has a focused window\n%s",
4427 dumpFocusedWindowsLocked().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08004428 }
4429 }
4430 }
4431
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004432 if (DEBUG_FOCUS) {
4433 logDispatchStateLocked();
4434 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004435 } // release lock
4436
4437 // Wake up poll loop since it may need to make new input dispatching choices.
4438 mLooper->wake();
4439}
4440
Michael Wrightd02c5b62014-02-10 15:10:22 -08004441void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004442 if (DEBUG_FOCUS) {
4443 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
4444 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004445
4446 bool changed;
4447 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004448 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004449
4450 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
4451 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004452 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004453 }
4454
4455 if (mDispatchEnabled && !enabled) {
4456 resetAndDropEverythingLocked("dispatcher is being disabled");
4457 }
4458
4459 mDispatchEnabled = enabled;
4460 mDispatchFrozen = frozen;
4461 changed = true;
4462 } else {
4463 changed = false;
4464 }
4465
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004466 if (DEBUG_FOCUS) {
4467 logDispatchStateLocked();
4468 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004469 } // release lock
4470
4471 if (changed) {
4472 // Wake up poll loop since it may need to make new input dispatching choices.
4473 mLooper->wake();
4474 }
4475}
4476
4477void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004478 if (DEBUG_FOCUS) {
4479 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
4480 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004481
4482 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004483 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004484
4485 if (mInputFilterEnabled == enabled) {
4486 return;
4487 }
4488
4489 mInputFilterEnabled = enabled;
4490 resetAndDropEverythingLocked("input filter is being enabled or disabled");
4491 } // release lock
4492
4493 // Wake up poll loop since there might be work to do to drop everything.
4494 mLooper->wake();
4495}
4496
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08004497void InputDispatcher::setInTouchMode(bool inTouchMode) {
4498 std::scoped_lock lock(mLock);
4499 mInTouchMode = inTouchMode;
4500}
4501
Bernardo Rufinoea97d182020-08-19 14:43:14 +01004502void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
4503 if (opacity < 0 || opacity > 1) {
4504 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
4505 return;
4506 }
4507
4508 std::scoped_lock lock(mLock);
4509 mMaximumObscuringOpacityForTouch = opacity;
4510}
4511
4512void InputDispatcher::setBlockUntrustedTouchesMode(BlockUntrustedTouchesMode mode) {
4513 std::scoped_lock lock(mLock);
4514 mBlockUntrustedTouchesMode = mode;
4515}
4516
chaviwfbe5d9c2018-12-26 12:23:37 -08004517bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken) {
4518 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004519 if (DEBUG_FOCUS) {
4520 ALOGD("Trivial transfer to same window.");
4521 }
chaviwfbe5d9c2018-12-26 12:23:37 -08004522 return true;
4523 }
4524
Michael Wrightd02c5b62014-02-10 15:10:22 -08004525 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004526 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004527
chaviwfbe5d9c2018-12-26 12:23:37 -08004528 sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromToken);
4529 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toToken);
Yi Kong9b14ac62018-07-17 13:48:38 -07004530 if (fromWindowHandle == nullptr || toWindowHandle == nullptr) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004531 ALOGW("Cannot transfer focus because from or to window not found.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004532 return false;
4533 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004534 if (DEBUG_FOCUS) {
4535 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
4536 fromWindowHandle->getName().c_str(), toWindowHandle->getName().c_str());
4537 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004538 if (fromWindowHandle->getInfo()->displayId != toWindowHandle->getInfo()->displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004539 if (DEBUG_FOCUS) {
4540 ALOGD("Cannot transfer focus because windows are on different displays.");
4541 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004542 return false;
4543 }
4544
4545 bool found = false;
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004546 for (std::pair<const int32_t, TouchState>& pair : mTouchStatesByDisplay) {
4547 TouchState& state = pair.second;
Jeff Brownf086ddb2014-02-11 14:28:48 -08004548 for (size_t i = 0; i < state.windows.size(); i++) {
4549 const TouchedWindow& touchedWindow = state.windows[i];
4550 if (touchedWindow.windowHandle == fromWindowHandle) {
4551 int32_t oldTargetFlags = touchedWindow.targetFlags;
4552 BitSet32 pointerIds = touchedWindow.pointerIds;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004553
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004554 state.windows.erase(state.windows.begin() + i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004555
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004556 int32_t newTargetFlags = oldTargetFlags &
4557 (InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_SPLIT |
4558 InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004559 state.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004560
Jeff Brownf086ddb2014-02-11 14:28:48 -08004561 found = true;
4562 goto Found;
4563 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004564 }
4565 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004566 Found:
Michael Wrightd02c5b62014-02-10 15:10:22 -08004567
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004568 if (!found) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004569 if (DEBUG_FOCUS) {
4570 ALOGD("Focus transfer failed because from window did not have focus.");
4571 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004572 return false;
4573 }
4574
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004575 sp<Connection> fromConnection = getConnectionLocked(fromToken);
4576 sp<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004577 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004578 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004579 CancelationOptions
4580 options(CancelationOptions::CANCEL_POINTER_EVENTS,
4581 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004582 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004583 synthesizePointerDownEventsForConnectionLocked(toConnection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004584 }
4585
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004586 if (DEBUG_FOCUS) {
4587 logDispatchStateLocked();
4588 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004589 } // release lock
4590
4591 // Wake up poll loop since it may need to make new input dispatching choices.
4592 mLooper->wake();
4593 return true;
4594}
4595
4596void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004597 if (DEBUG_FOCUS) {
4598 ALOGD("Resetting and dropping all events (%s).", reason);
4599 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004600
4601 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
4602 synthesizeCancelationEventsForAllConnectionsLocked(options);
4603
4604 resetKeyRepeatLocked();
4605 releasePendingEventLocked();
4606 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004607 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004608
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004609 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08004610 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004611 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07004612 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004613}
4614
4615void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004616 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004617 dumpDispatchStateLocked(dump);
4618
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004619 std::istringstream stream(dump);
4620 std::string line;
4621
4622 while (std::getline(stream, line, '\n')) {
4623 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004624 }
4625}
4626
Vishnu Nairad321cd2020-08-20 16:40:21 -07004627std::string InputDispatcher::dumpFocusedWindowsLocked() {
4628 if (mFocusedWindowTokenByDisplay.empty()) {
4629 return INDENT "FocusedWindows: <none>\n";
4630 }
4631
4632 std::string dump;
4633 dump += INDENT "FocusedWindows:\n";
4634 for (auto& it : mFocusedWindowTokenByDisplay) {
4635 const int32_t displayId = it.first;
4636 const sp<InputWindowHandle> windowHandle = getFocusedWindowHandleLocked(displayId);
4637 if (windowHandle) {
4638 dump += StringPrintf(INDENT2 "displayId=%" PRId32 ", name='%s'\n", displayId,
4639 windowHandle->getName().c_str());
4640 } else {
4641 dump += StringPrintf(INDENT2 "displayId=%" PRId32
4642 " has focused token without a window'\n",
4643 displayId);
4644 }
4645 }
4646 return dump;
4647}
4648
Siarhei Vishniakouad991402020-10-28 11:40:09 -05004649std::string InputDispatcher::dumpPendingFocusRequestsLocked() {
4650 if (mPendingFocusRequests.empty()) {
4651 return INDENT "mPendingFocusRequests: <none>\n";
4652 }
4653
4654 std::string dump;
4655 dump += INDENT "mPendingFocusRequests:\n";
4656 for (const auto& [displayId, focusRequest] : mPendingFocusRequests) {
4657 // Rather than printing raw values for focusRequest.token and focusRequest.focusedToken,
4658 // try to resolve them to actual windows.
4659 std::string windowName = getConnectionNameLocked(focusRequest.token);
4660 std::string focusedWindowName = getConnectionNameLocked(focusRequest.focusedToken);
4661 dump += StringPrintf(INDENT2 "displayId=%" PRId32 ", token->%s, focusedToken->%s\n",
4662 displayId, windowName.c_str(), focusedWindowName.c_str());
4663 }
4664 return dump;
4665}
4666
Prabir Pradhan99987712020-11-10 18:43:05 -08004667std::string InputDispatcher::dumpPointerCaptureStateLocked() {
4668 std::string dump;
4669
4670 dump += StringPrintf(INDENT "FocusedWindowRequestedPointerCapture: %s\n",
4671 toString(mFocusedWindowRequestedPointerCapture));
4672
4673 std::string windowName = "None";
4674 if (mWindowTokenWithPointerCapture) {
4675 const sp<InputWindowHandle> captureWindowHandle =
4676 getWindowHandleLocked(mWindowTokenWithPointerCapture);
4677 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
4678 : "token has capture without window";
4679 }
4680 dump += StringPrintf(INDENT "CurrentWindowWithPointerCapture: %s\n", windowName.c_str());
4681
4682 return dump;
4683}
4684
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004685void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07004686 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
4687 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
4688 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08004689 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004690
Tiger Huang721e26f2018-07-24 22:26:19 +08004691 if (!mFocusedApplicationHandlesByDisplay.empty()) {
4692 dump += StringPrintf(INDENT "FocusedApplications:\n");
4693 for (auto& it : mFocusedApplicationHandlesByDisplay) {
4694 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07004695 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05004696 const std::chrono::duration timeout =
4697 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004698 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004699 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05004700 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08004701 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004702 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08004703 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004704 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004705
Vishnu Nairad321cd2020-08-20 16:40:21 -07004706 dump += dumpFocusedWindowsLocked();
Siarhei Vishniakouad991402020-10-28 11:40:09 -05004707 dump += dumpPendingFocusRequestsLocked();
Prabir Pradhan99987712020-11-10 18:43:05 -08004708 dump += dumpPointerCaptureStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004709
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004710 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004711 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004712 for (const std::pair<int32_t, TouchState>& pair : mTouchStatesByDisplay) {
4713 const TouchState& state = pair.second;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004714 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004715 state.displayId, toString(state.down), toString(state.split),
4716 state.deviceId, state.source);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004717 if (!state.windows.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004718 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004719 for (size_t i = 0; i < state.windows.size(); i++) {
4720 const TouchedWindow& touchedWindow = state.windows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004721 dump += StringPrintf(INDENT4
4722 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
4723 i, touchedWindow.windowHandle->getName().c_str(),
4724 touchedWindow.pointerIds.value, touchedWindow.targetFlags);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004725 }
4726 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004727 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004728 }
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004729 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004730 dump += INDENT3 "Portal windows:\n";
4731 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004732 const sp<InputWindowHandle> portalWindowHandle = state.portalWindows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004733 dump += StringPrintf(INDENT4 "%zu: name='%s'\n", i,
4734 portalWindowHandle->getName().c_str());
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004735 }
4736 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004737 }
4738 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004739 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004740 }
4741
Arthur Hungb92218b2018-08-14 12:00:21 +08004742 if (!mWindowHandlesByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004743 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004744 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
Arthur Hung3b413f22018-10-26 18:05:34 +08004745 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", it.first);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004746 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004747 dump += INDENT2 "Windows:\n";
4748 for (size_t i = 0; i < windowHandles.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004749 const sp<InputWindowHandle>& windowHandle = windowHandles[i];
Arthur Hungb92218b2018-08-14 12:00:21 +08004750 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004751
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00004752 dump += StringPrintf(INDENT3 "%zu: name='%s', id=%" PRId32 ", displayId=%d, "
Vishnu Nair47074b82020-08-14 11:54:47 -07004753 "portalToDisplayId=%d, paused=%s, focusable=%s, "
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00004754 "hasWallpaper=%s, visible=%s, alpha=%.2f, "
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00004755 "flags=%s, type=%s, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004756 "frame=[%d,%d][%d,%d], globalScale=%f, "
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004757 "applicationInfo=%s, "
chaviw1ff3d1e2020-07-01 15:53:47 -07004758 "touchableRegion=",
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00004759 i, windowInfo->name.c_str(), windowInfo->id,
4760 windowInfo->displayId, windowInfo->portalToDisplayId,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004761 toString(windowInfo->paused),
Vishnu Nair47074b82020-08-14 11:54:47 -07004762 toString(windowInfo->focusable),
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004763 toString(windowInfo->hasWallpaper),
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00004764 toString(windowInfo->visible), windowInfo->alpha,
Michael Wright8759d672020-07-21 00:46:45 +01004765 windowInfo->flags.string().c_str(),
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00004766 NamedEnum::string(windowInfo->type).c_str(),
Michael Wright44753b12020-07-08 13:48:11 +01004767 windowInfo->frameLeft, windowInfo->frameTop,
4768 windowInfo->frameRight, windowInfo->frameBottom,
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004769 windowInfo->globalScaleFactor,
4770 windowInfo->applicationInfo.name.c_str());
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00004771 dump += dumpRegion(windowInfo->touchableRegion);
Michael Wright44753b12020-07-08 13:48:11 +01004772 dump += StringPrintf(", inputFeatures=%s",
4773 windowInfo->inputFeatures.string().c_str());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004774 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%" PRId64
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00004775 "ms, trustedOverlay=%s, hasToken=%s, "
4776 "touchOcclusionMode=%s\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004777 windowInfo->ownerPid, windowInfo->ownerUid,
Bernardo Rufinoc2f1fad2020-11-04 17:30:57 +00004778 millis(windowInfo->dispatchingTimeout),
4779 toString(windowInfo->trustedOverlay),
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00004780 toString(windowInfo->token != nullptr),
4781 toString(windowInfo->touchOcclusionMode).c_str());
chaviw85b44202020-07-24 11:46:21 -07004782 windowInfo->transform.dump(dump, "transform", INDENT4);
Arthur Hungb92218b2018-08-14 12:00:21 +08004783 }
4784 } else {
4785 dump += INDENT2 "Windows: <none>\n";
4786 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004787 }
4788 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08004789 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004790 }
4791
Michael Wright3dd60e22019-03-27 22:06:44 +00004792 if (!mGlobalMonitorsByDisplay.empty() || !mGestureMonitorsByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004793 for (auto& it : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004794 const std::vector<Monitor>& monitors = it.second;
4795 dump += StringPrintf(INDENT "Global monitors in display %" PRId32 ":\n", it.first);
4796 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004797 }
4798 for (auto& it : mGestureMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004799 const std::vector<Monitor>& monitors = it.second;
4800 dump += StringPrintf(INDENT "Gesture monitors in display %" PRId32 ":\n", it.first);
4801 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004802 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004803 } else {
Michael Wright3dd60e22019-03-27 22:06:44 +00004804 dump += INDENT "Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004805 }
4806
4807 nsecs_t currentTime = now();
4808
4809 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004810 if (!mRecentQueue.empty()) {
4811 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004812 for (std::shared_ptr<EventEntry>& entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004813 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05004814 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004815 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004816 }
4817 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004818 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004819 }
4820
4821 // Dump event currently being dispatched.
4822 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004823 dump += INDENT "PendingEvent:\n";
4824 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05004825 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004826 dump += StringPrintf(", age=%" PRId64 "ms\n",
4827 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004828 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004829 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004830 }
4831
4832 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004833 if (!mInboundQueue.empty()) {
4834 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004835 for (std::shared_ptr<EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004836 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05004837 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004838 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004839 }
4840 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004841 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004842 }
4843
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004844 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004845 dump += INDENT "ReplacedKeys:\n";
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004846 for (const std::pair<KeyReplacement, int32_t>& pair : mReplacedKeys) {
4847 const KeyReplacement& replacement = pair.first;
4848 int32_t newKeyCode = pair.second;
4849 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004850 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07004851 }
4852 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004853 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07004854 }
4855
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004856 if (!mConnectionsByFd.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004857 dump += INDENT "Connections:\n";
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004858 for (const auto& pair : mConnectionsByFd) {
4859 const sp<Connection>& connection = pair.second;
4860 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004861 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004862 pair.first, connection->getInputChannelName().c_str(),
4863 connection->getWindowName().c_str(), connection->getStatusLabel(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004864 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004865
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004866 if (!connection->outboundQueue.empty()) {
4867 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
4868 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05004869 dump += dumpQueue(connection->outboundQueue, currentTime);
4870
Michael Wrightd02c5b62014-02-10 15:10:22 -08004871 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004872 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004873 }
4874
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004875 if (!connection->waitQueue.empty()) {
4876 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
4877 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05004878 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004879 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004880 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004881 }
4882 }
4883 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004884 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004885 }
4886
4887 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004888 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
4889 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004890 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004891 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004892 }
4893
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004894 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004895 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
4896 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
4897 ns2ms(mConfig.keyRepeatTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004898}
4899
Michael Wright3dd60e22019-03-27 22:06:44 +00004900void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
4901 const size_t numMonitors = monitors.size();
4902 for (size_t i = 0; i < numMonitors; i++) {
4903 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004904 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00004905 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
4906 dump += "\n";
4907 }
4908}
4909
Garfield Tan15601662020-09-22 15:32:38 -07004910base::Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(
4911 const std::string& name) {
4912#if DEBUG_CHANNEL_CREATION
4913 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004914#endif
4915
Garfield Tan15601662020-09-22 15:32:38 -07004916 std::shared_ptr<InputChannel> serverChannel;
4917 std::unique_ptr<InputChannel> clientChannel;
4918 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
4919
4920 if (result) {
4921 return base::Error(result) << "Failed to open input channel pair with name " << name;
4922 }
4923
Michael Wrightd02c5b62014-02-10 15:10:22 -08004924 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004925 std::scoped_lock _l(mLock);
Garfield Tan15601662020-09-22 15:32:38 -07004926 sp<Connection> connection = new Connection(serverChannel, false /*monitor*/, mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004927
Garfield Tan15601662020-09-22 15:32:38 -07004928 int fd = serverChannel->getFd();
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004929 mConnectionsByFd[fd] = connection;
Garfield Tan15601662020-09-22 15:32:38 -07004930 mInputChannelsByToken[serverChannel->getConnectionToken()] = serverChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004931
Michael Wrightd02c5b62014-02-10 15:10:22 -08004932 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
4933 } // release lock
4934
4935 // Wake the looper because some connections have changed.
4936 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07004937 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004938}
4939
Garfield Tan15601662020-09-22 15:32:38 -07004940base::Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(
Siarhei Vishniakou58cfc602020-12-14 23:21:30 +00004941 int32_t displayId, bool isGestureMonitor, const std::string& name, int32_t pid) {
Garfield Tan15601662020-09-22 15:32:38 -07004942 std::shared_ptr<InputChannel> serverChannel;
4943 std::unique_ptr<InputChannel> clientChannel;
4944 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
4945 if (result) {
4946 return base::Error(result) << "Failed to open input channel pair with name " << name;
4947 }
4948
Michael Wright3dd60e22019-03-27 22:06:44 +00004949 { // acquire lock
4950 std::scoped_lock _l(mLock);
4951
4952 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07004953 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
4954 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00004955 }
4956
Garfield Tan15601662020-09-22 15:32:38 -07004957 sp<Connection> connection = new Connection(serverChannel, true /*monitor*/, mIdGenerator);
Michael Wright3dd60e22019-03-27 22:06:44 +00004958
Garfield Tan15601662020-09-22 15:32:38 -07004959 const int fd = serverChannel->getFd();
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004960 mConnectionsByFd[fd] = connection;
Garfield Tan15601662020-09-22 15:32:38 -07004961 mInputChannelsByToken[serverChannel->getConnectionToken()] = serverChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00004962
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004963 auto& monitorsByDisplay =
4964 isGestureMonitor ? mGestureMonitorsByDisplay : mGlobalMonitorsByDisplay;
Siarhei Vishniakou58cfc602020-12-14 23:21:30 +00004965 monitorsByDisplay[displayId].emplace_back(serverChannel, pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00004966
4967 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
Michael Wright3dd60e22019-03-27 22:06:44 +00004968 }
Garfield Tan15601662020-09-22 15:32:38 -07004969
Michael Wright3dd60e22019-03-27 22:06:44 +00004970 // Wake the looper because some connections have changed.
4971 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07004972 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00004973}
4974
Garfield Tan15601662020-09-22 15:32:38 -07004975status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004976 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004977 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004978
Garfield Tan15601662020-09-22 15:32:38 -07004979 status_t status = removeInputChannelLocked(connectionToken, false /*notify*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004980 if (status) {
4981 return status;
4982 }
4983 } // release lock
4984
4985 // Wake the poll loop because removing the connection may have changed the current
4986 // synchronization state.
4987 mLooper->wake();
4988 return OK;
4989}
4990
Garfield Tan15601662020-09-22 15:32:38 -07004991status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
4992 bool notify) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004993 sp<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004994 if (connection == nullptr) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004995 ALOGW("Attempted to unregister already unregistered input channel");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004996 return BAD_VALUE;
4997 }
4998
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004999 removeConnectionLocked(connection);
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005000 mInputChannelsByToken.erase(connectionToken);
Robert Carr5c8a0262018-10-03 16:30:44 -07005001
Michael Wrightd02c5b62014-02-10 15:10:22 -08005002 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005003 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005004 }
5005
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005006 mLooper->removeFd(connection->inputChannel->getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005007
5008 nsecs_t currentTime = now();
5009 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
5010
5011 connection->status = Connection::STATUS_ZOMBIE;
5012 return OK;
5013}
5014
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005015void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
5016 removeMonitorChannelLocked(connectionToken, mGlobalMonitorsByDisplay);
5017 removeMonitorChannelLocked(connectionToken, mGestureMonitorsByDisplay);
Michael Wright3dd60e22019-03-27 22:06:44 +00005018}
5019
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005020void InputDispatcher::removeMonitorChannelLocked(
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005021 const sp<IBinder>& connectionToken,
Michael Wright3dd60e22019-03-27 22:06:44 +00005022 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005023 for (auto it = monitorsByDisplay.begin(); it != monitorsByDisplay.end();) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005024 std::vector<Monitor>& monitors = it->second;
5025 const size_t numMonitors = monitors.size();
5026 for (size_t i = 0; i < numMonitors; i++) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005027 if (monitors[i].inputChannel->getConnectionToken() == connectionToken) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005028 monitors.erase(monitors.begin() + i);
5029 break;
5030 }
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005031 }
Michael Wright3dd60e22019-03-27 22:06:44 +00005032 if (monitors.empty()) {
5033 it = monitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005034 } else {
5035 ++it;
5036 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005037 }
5038}
5039
Michael Wright3dd60e22019-03-27 22:06:44 +00005040status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
5041 { // acquire lock
5042 std::scoped_lock _l(mLock);
5043 std::optional<int32_t> foundDisplayId = findGestureMonitorDisplayByTokenLocked(token);
5044
5045 if (!foundDisplayId) {
5046 ALOGW("Attempted to pilfer pointers from an un-registered monitor or invalid token");
5047 return BAD_VALUE;
5048 }
5049 int32_t displayId = foundDisplayId.value();
5050
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005051 std::unordered_map<int32_t, TouchState>::iterator stateIt =
5052 mTouchStatesByDisplay.find(displayId);
5053 if (stateIt == mTouchStatesByDisplay.end()) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005054 ALOGW("Failed to pilfer pointers: no pointers on display %" PRId32 ".", displayId);
5055 return BAD_VALUE;
5056 }
5057
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005058 TouchState& state = stateIt->second;
Michael Wright3dd60e22019-03-27 22:06:44 +00005059 std::optional<int32_t> foundDeviceId;
5060 for (const TouchedMonitor& touchedMonitor : state.gestureMonitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005061 if (touchedMonitor.monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005062 foundDeviceId = state.deviceId;
5063 }
5064 }
5065 if (!foundDeviceId || !state.down) {
5066 ALOGW("Attempted to pilfer points from a monitor without any on-going pointer streams."
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005067 " Ignoring.");
Michael Wright3dd60e22019-03-27 22:06:44 +00005068 return BAD_VALUE;
5069 }
5070 int32_t deviceId = foundDeviceId.value();
5071
5072 // Send cancel events to all the input channels we're stealing from.
5073 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005074 "gesture monitor stole pointer stream");
Michael Wright3dd60e22019-03-27 22:06:44 +00005075 options.deviceId = deviceId;
5076 options.displayId = displayId;
5077 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005078 std::shared_ptr<InputChannel> channel =
5079 getInputChannelLocked(window.windowHandle->getToken());
Michael Wright3a240c42019-12-10 20:53:41 +00005080 if (channel != nullptr) {
5081 synthesizeCancelationEventsForInputChannelLocked(channel, options);
5082 }
Michael Wright3dd60e22019-03-27 22:06:44 +00005083 }
5084 // Then clear the current touch state so we stop dispatching to them as well.
5085 state.filterNonMonitors();
5086 }
5087 return OK;
5088}
5089
Prabir Pradhan99987712020-11-10 18:43:05 -08005090void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
5091 { // acquire lock
5092 std::scoped_lock _l(mLock);
5093 if (DEBUG_FOCUS) {
5094 const sp<InputWindowHandle> windowHandle = getWindowHandleLocked(windowToken);
5095 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
5096 windowHandle != nullptr ? windowHandle->getName().c_str()
5097 : "token without window");
5098 }
5099
5100 const sp<IBinder> focusedToken =
5101 getValueByKey(mFocusedWindowTokenByDisplay, mFocusedDisplayId);
5102 if (focusedToken != windowToken) {
5103 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
5104 enabled ? "enable" : "disable");
5105 return;
5106 }
5107
5108 if (enabled == mFocusedWindowRequestedPointerCapture) {
5109 ALOGW("Ignoring request to %s Pointer Capture: "
5110 "window has %s requested pointer capture.",
5111 enabled ? "enable" : "disable", enabled ? "already" : "not");
5112 return;
5113 }
5114
5115 mFocusedWindowRequestedPointerCapture = enabled;
5116 setPointerCaptureLocked(enabled);
5117 } // release lock
5118
5119 // Wake the thread to process command entries.
5120 mLooper->wake();
5121}
5122
Michael Wright3dd60e22019-03-27 22:06:44 +00005123std::optional<int32_t> InputDispatcher::findGestureMonitorDisplayByTokenLocked(
5124 const sp<IBinder>& token) {
5125 for (const auto& it : mGestureMonitorsByDisplay) {
5126 const std::vector<Monitor>& monitors = it.second;
5127 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005128 if (monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005129 return it.first;
5130 }
5131 }
5132 }
5133 return std::nullopt;
5134}
5135
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005136sp<Connection> InputDispatcher::getConnectionLocked(const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005137 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005138 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08005139 }
5140
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005141 for (const auto& pair : mConnectionsByFd) {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005142 const sp<Connection>& connection = pair.second;
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005143 if (connection->inputChannel->getConnectionToken() == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005144 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005145 }
5146 }
Robert Carr4e670e52018-08-15 13:26:12 -07005147
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005148 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005149}
5150
Siarhei Vishniakouad991402020-10-28 11:40:09 -05005151std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
5152 sp<Connection> connection = getConnectionLocked(connectionToken);
5153 if (connection == nullptr) {
5154 return "<nullptr>";
5155 }
5156 return connection->getInputChannelName();
5157}
5158
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005159void InputDispatcher::removeConnectionLocked(const sp<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005160 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005161 removeByValue(mConnectionsByFd, connection);
5162}
5163
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005164void InputDispatcher::onDispatchCycleFinishedLocked(nsecs_t currentTime,
5165 const sp<Connection>& connection, uint32_t seq,
5166 bool handled) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005167 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5168 &InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005169 commandEntry->connection = connection;
5170 commandEntry->eventTime = currentTime;
5171 commandEntry->seq = seq;
5172 commandEntry->handled = handled;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005173 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005174}
5175
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005176void InputDispatcher::onDispatchCycleBrokenLocked(nsecs_t currentTime,
5177 const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005178 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005179 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005180
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005181 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5182 &InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005183 commandEntry->connection = connection;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005184 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005185}
5186
Vishnu Nairad321cd2020-08-20 16:40:21 -07005187void InputDispatcher::notifyFocusChangedLocked(const sp<IBinder>& oldToken,
5188 const sp<IBinder>& newToken) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005189 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5190 &InputDispatcher::doNotifyFocusChangedLockedInterruptible);
chaviw0c06c6e2019-01-09 13:27:07 -08005191 commandEntry->oldToken = oldToken;
5192 commandEntry->newToken = newToken;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005193 postCommandLocked(std::move(commandEntry));
Robert Carrf759f162018-11-13 12:57:11 -08005194}
5195
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -05005196void InputDispatcher::onAnrLocked(const Connection& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005197 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
5198 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -05005199 if (connection.waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005200 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -05005201 connection.inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005202 return;
5203 }
5204 /**
5205 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
5206 * may not be the one that caused the timeout to occur. One possibility is that window timeout
5207 * has changed. This could cause newer entries to time out before the already dispatched
5208 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
5209 * processes the events linearly. So providing information about the oldest entry seems to be
5210 * most useful.
5211 */
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -05005212 DispatchEntry* oldestEntry = *connection.waitQueue.begin();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005213 const nsecs_t currentWait = now() - oldestEntry->deliveryTime;
5214 std::string reason =
5215 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -05005216 connection.inputChannel->getName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005217 ns2ms(currentWait),
5218 oldestEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06005219 sp<IBinder> connectionToken = connection.inputChannel->getConnectionToken();
5220 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005221
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005222 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5223 &InputDispatcher::doNotifyConnectionUnresponsiveLockedInterruptible);
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06005224 commandEntry->connectionToken = connectionToken;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005225 commandEntry->reason = std::move(reason);
5226 postCommandLocked(std::move(commandEntry));
5227}
5228
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005229void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
5230 std::string reason =
5231 StringPrintf("%s does not have a focused window", application->getName().c_str());
5232 updateLastAnrStateLocked(*application, reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005233
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005234 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5235 &InputDispatcher::doNotifyNoFocusedWindowAnrLockedInterruptible);
5236 commandEntry->inputApplicationHandle = std::move(application);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005237 postCommandLocked(std::move(commandEntry));
5238}
5239
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00005240void InputDispatcher::onUntrustedTouchLocked(const std::string& obscuringPackage) {
5241 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5242 &InputDispatcher::doNotifyUntrustedTouchLockedInterruptible);
5243 commandEntry->obscuringPackage = obscuringPackage;
5244 postCommandLocked(std::move(commandEntry));
5245}
5246
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005247void InputDispatcher::updateLastAnrStateLocked(const sp<InputWindowHandle>& window,
5248 const std::string& reason) {
5249 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
5250 updateLastAnrStateLocked(windowLabel, reason);
5251}
5252
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005253void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
5254 const std::string& reason) {
5255 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005256 updateLastAnrStateLocked(windowLabel, reason);
5257}
5258
5259void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
5260 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005261 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07005262 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005263 struct tm tm;
5264 localtime_r(&t, &tm);
5265 char timestr[64];
5266 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005267 mLastAnrState.clear();
5268 mLastAnrState += INDENT "ANR:\n";
5269 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005270 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
5271 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005272 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005273}
5274
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005275void InputDispatcher::doNotifyConfigurationChangedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005276 mLock.unlock();
5277
5278 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
5279
5280 mLock.lock();
5281}
5282
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005283void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005284 sp<Connection> connection = commandEntry->connection;
5285
5286 if (connection->status != Connection::STATUS_ZOMBIE) {
5287 mLock.unlock();
5288
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005289 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005290
5291 mLock.lock();
5292 }
5293}
5294
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005295void InputDispatcher::doNotifyFocusChangedLockedInterruptible(CommandEntry* commandEntry) {
chaviw0c06c6e2019-01-09 13:27:07 -08005296 sp<IBinder> oldToken = commandEntry->oldToken;
5297 sp<IBinder> newToken = commandEntry->newToken;
Robert Carrf759f162018-11-13 12:57:11 -08005298 mLock.unlock();
chaviw0c06c6e2019-01-09 13:27:07 -08005299 mPolicy->notifyFocusChanged(oldToken, newToken);
Robert Carrf759f162018-11-13 12:57:11 -08005300 mLock.lock();
5301}
5302
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005303void InputDispatcher::doNotifyNoFocusedWindowAnrLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005304 mLock.unlock();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005305
5306 mPolicy->notifyNoFocusedWindowAnr(commandEntry->inputApplicationHandle);
5307
5308 mLock.lock();
5309}
5310
5311void InputDispatcher::doNotifyConnectionUnresponsiveLockedInterruptible(
5312 CommandEntry* commandEntry) {
5313 mLock.unlock();
5314
5315 mPolicy->notifyConnectionUnresponsive(commandEntry->connectionToken, commandEntry->reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005316
5317 mLock.lock();
5318
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005319 // stop waking up for events in this connection, it is already not responding
5320 sp<Connection> connection = getConnectionLocked(commandEntry->connectionToken);
5321 if (connection == nullptr) {
5322 return;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005323 }
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005324 cancelEventsForAnrLocked(connection);
5325}
5326
5327void InputDispatcher::doNotifyConnectionResponsiveLockedInterruptible(CommandEntry* commandEntry) {
5328 mLock.unlock();
5329
5330 mPolicy->notifyConnectionResponsive(commandEntry->connectionToken);
5331
5332 mLock.lock();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005333}
5334
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00005335void InputDispatcher::doNotifyUntrustedTouchLockedInterruptible(CommandEntry* commandEntry) {
5336 mLock.unlock();
5337
5338 mPolicy->notifyUntrustedTouch(commandEntry->obscuringPackage);
5339
5340 mLock.lock();
5341}
5342
Michael Wrightd02c5b62014-02-10 15:10:22 -08005343void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
5344 CommandEntry* commandEntry) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005345 KeyEntry& entry = *(commandEntry->keyEntry);
5346 KeyEvent event = createKeyEvent(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005347
5348 mLock.unlock();
5349
Michael Wright2b3c3302018-03-02 17:19:13 +00005350 android::base::Timer t;
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06005351 const sp<IBinder>& token = commandEntry->connectionToken;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005352 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(token, &event, entry.policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00005353 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
5354 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005355 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00005356 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005357
5358 mLock.lock();
5359
5360 if (delay < 0) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005361 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005362 } else if (!delay) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005363 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005364 } else {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005365 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
5366 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005367 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005368}
5369
chaviwfd6d3512019-03-25 13:23:49 -07005370void InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible(CommandEntry* commandEntry) {
5371 mLock.unlock();
5372 mPolicy->onPointerDownOutsideFocus(commandEntry->newToken);
5373 mLock.lock();
5374}
5375
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005376/**
5377 * Connection is responsive if it has no events in the waitQueue that are older than the
5378 * current time.
5379 */
5380static bool isConnectionResponsive(const Connection& connection) {
5381 const nsecs_t currentTime = now();
5382 for (const DispatchEntry* entry : connection.waitQueue) {
5383 if (entry->timeoutTime < currentTime) {
5384 return false;
5385 }
5386 }
5387 return true;
5388}
5389
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005390void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005391 sp<Connection> connection = commandEntry->connection;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005392 const nsecs_t finishTime = commandEntry->eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005393 uint32_t seq = commandEntry->seq;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005394 const bool handled = commandEntry->handled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005395
5396 // Handle post-event policy actions.
Garfield Tane84e6f92019-08-29 17:28:41 -07005397 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005398 if (dispatchEntryIt == connection->waitQueue.end()) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005399 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005400 }
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005401 DispatchEntry* dispatchEntry = *dispatchEntryIt;
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07005402 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005403 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005404 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
5405 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005406 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07005407 reportDispatchStatistics(std::chrono::nanoseconds(eventDuration), *connection, handled);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005408
5409 bool restartEvent;
Siarhei Vishniakou49483272019-10-22 13:13:47 -07005410 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005411 KeyEntry& keyEntry = static_cast<KeyEntry&>(*(dispatchEntry->eventEntry));
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005412 restartEvent =
5413 afterKeyEventLockedInterruptible(connection, dispatchEntry, keyEntry, handled);
Siarhei Vishniakou49483272019-10-22 13:13:47 -07005414 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005415 MotionEntry& motionEntry = static_cast<MotionEntry&>(*(dispatchEntry->eventEntry));
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005416 restartEvent = afterMotionEventLockedInterruptible(connection, dispatchEntry, motionEntry,
5417 handled);
5418 } else {
5419 restartEvent = false;
5420 }
5421
5422 // Dequeue the event and start the next cycle.
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07005423 // Because the lock might have been released, it is possible that the
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005424 // contents of the wait queue to have been drained, so we need to double-check
5425 // a few things.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005426 dispatchEntryIt = connection->findWaitQueueEntry(seq);
5427 if (dispatchEntryIt != connection->waitQueue.end()) {
5428 dispatchEntry = *dispatchEntryIt;
5429 connection->waitQueue.erase(dispatchEntryIt);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005430 const sp<IBinder>& connectionToken = connection->inputChannel->getConnectionToken();
5431 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005432 if (!connection->responsive) {
5433 connection->responsive = isConnectionResponsive(*connection);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005434 if (connection->responsive) {
5435 // The connection was unresponsive, and now it's responsive. Tell the policy
5436 // about it so that it can stop ANR.
5437 std::unique_ptr<CommandEntry> connectionResponsiveCommand =
5438 std::make_unique<CommandEntry>(
5439 &InputDispatcher::doNotifyConnectionResponsiveLockedInterruptible);
5440 connectionResponsiveCommand->connectionToken = connectionToken;
5441 postCommandLocked(std::move(connectionResponsiveCommand));
5442 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005443 }
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005444 traceWaitQueueLength(connection);
5445 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005446 connection->outboundQueue.push_front(dispatchEntry);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005447 traceOutboundQueueLength(connection);
5448 } else {
5449 releaseDispatchEntry(dispatchEntry);
5450 }
5451 }
5452
5453 // Start the next dispatch cycle for this connection.
5454 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005455}
5456
5457bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005458 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005459 KeyEntry& keyEntry, bool handled) {
5460 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005461 if (!handled) {
5462 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005463 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005464 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005465 return false;
5466 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005467
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005468 // Get the fallback key state.
5469 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005470 int32_t originalKeyCode = keyEntry.keyCode;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005471 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005472 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005473 connection->inputState.removeFallbackKey(originalKeyCode);
5474 }
5475
5476 if (handled || !dispatchEntry->hasForegroundTarget()) {
5477 // If the application handles the original key for which we previously
5478 // generated a fallback or if the window is not a foreground window,
5479 // then cancel the associated fallback key, if any.
5480 if (fallbackKeyCode != -1) {
5481 // Dispatch the unhandled key to the policy with the cancel flag.
Michael Wrightd02c5b62014-02-10 15:10:22 -08005482#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005483 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005484 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005485 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005486#endif
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005487 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005488 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005489
5490 mLock.unlock();
5491
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005492 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005493 keyEntry.policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005494
5495 mLock.lock();
5496
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005497 // Cancel the fallback key.
5498 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005499 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005500 "application handled the original non-fallback key "
5501 "or is no longer a foreground target, "
5502 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005503 options.keyCode = fallbackKeyCode;
5504 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005505 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005506 connection->inputState.removeFallbackKey(originalKeyCode);
5507 }
5508 } else {
5509 // If the application did not handle a non-fallback key, first check
5510 // that we are in a good state to perform unhandled key event processing
5511 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005512 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005513 if (fallbackKeyCode == -1 && !initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005514#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005515 ALOGD("Unhandled key event: Skipping unhandled key event processing "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005516 "since this is not an initial down. "
5517 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005518 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005519#endif
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005520 return false;
5521 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005522
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005523 // Dispatch the unhandled key to the policy.
5524#if DEBUG_OUTBOUND_EVENT_DETAILS
5525 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005526 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005527 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005528#endif
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005529 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005530
5531 mLock.unlock();
5532
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005533 bool fallback =
5534 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005535 &event, keyEntry.policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005536
5537 mLock.lock();
5538
5539 if (connection->status != Connection::STATUS_NORMAL) {
5540 connection->inputState.removeFallbackKey(originalKeyCode);
5541 return false;
5542 }
5543
5544 // Latch the fallback keycode for this key on an initial down.
5545 // The fallback keycode cannot change at any other point in the lifecycle.
5546 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005547 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005548 fallbackKeyCode = event.getKeyCode();
5549 } else {
5550 fallbackKeyCode = AKEYCODE_UNKNOWN;
5551 }
5552 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
5553 }
5554
5555 ALOG_ASSERT(fallbackKeyCode != -1);
5556
5557 // Cancel the fallback key if the policy decides not to send it anymore.
5558 // We will continue to dispatch the key to the policy but we will no
5559 // longer dispatch a fallback key to the application.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005560 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
5561 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005562#if DEBUG_OUTBOUND_EVENT_DETAILS
5563 if (fallback) {
5564 ALOGD("Unhandled key event: Policy requested to send key %d"
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005565 "as a fallback for %d, but on the DOWN it had requested "
5566 "to send %d instead. Fallback canceled.",
5567 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005568 } else {
5569 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005570 "but on the DOWN it had requested to send %d. "
5571 "Fallback canceled.",
5572 originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005573 }
5574#endif
5575
5576 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
5577 "canceling fallback, policy no longer desires it");
5578 options.keyCode = fallbackKeyCode;
5579 synthesizeCancelationEventsForConnectionLocked(connection, options);
5580
5581 fallback = false;
5582 fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005583 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005584 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005585 }
5586 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005587
5588#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005589 {
5590 std::string msg;
5591 const KeyedVector<int32_t, int32_t>& fallbackKeys =
5592 connection->inputState.getFallbackKeys();
5593 for (size_t i = 0; i < fallbackKeys.size(); i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005594 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005595 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005596 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005597 fallbackKeys.size(), msg.c_str());
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005598 }
5599#endif
5600
5601 if (fallback) {
5602 // Restart the dispatch cycle using the fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005603 keyEntry.eventTime = event.getEventTime();
5604 keyEntry.deviceId = event.getDeviceId();
5605 keyEntry.source = event.getSource();
5606 keyEntry.displayId = event.getDisplayId();
5607 keyEntry.flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
5608 keyEntry.keyCode = fallbackKeyCode;
5609 keyEntry.scanCode = event.getScanCode();
5610 keyEntry.metaState = event.getMetaState();
5611 keyEntry.repeatCount = event.getRepeatCount();
5612 keyEntry.downTime = event.getDownTime();
5613 keyEntry.syntheticRepeat = false;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005614
5615#if DEBUG_OUTBOUND_EVENT_DETAILS
5616 ALOGD("Unhandled key event: Dispatching fallback key. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005617 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005618 originalKeyCode, fallbackKeyCode, keyEntry.metaState);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005619#endif
5620 return true; // restart the event
5621 } else {
5622#if DEBUG_OUTBOUND_EVENT_DETAILS
5623 ALOGD("Unhandled key event: No fallback key.");
5624#endif
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005625
5626 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005627 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005628 }
5629 }
5630 return false;
5631}
5632
5633bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005634 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005635 MotionEntry& motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005636 return false;
5637}
5638
5639void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
5640 mLock.unlock();
5641
5642 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType);
5643
5644 mLock.lock();
5645}
5646
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07005647KeyEvent InputDispatcher::createKeyEvent(const KeyEntry& entry) {
5648 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08005649 event.initialize(entry.id, entry.deviceId, entry.source, entry.displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08005650 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
5651 entry.repeatCount, entry.downTime, entry.eventTime);
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07005652 return event;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005653}
5654
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07005655void InputDispatcher::reportDispatchStatistics(std::chrono::nanoseconds eventDuration,
5656 const Connection& connection, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005657 // TODO Write some statistics about how long we spend waiting.
5658}
5659
Siarhei Vishniakoude4bf152019-08-16 11:12:52 -05005660/**
5661 * Report the touch event latency to the statsd server.
5662 * Input events are reported for statistics if:
5663 * - This is a touchscreen event
5664 * - InputFilter is not enabled
5665 * - Event is not injected or synthesized
5666 *
5667 * Statistics should be reported before calling addValue, to prevent a fresh new sample
5668 * from getting aggregated with the "old" data.
5669 */
5670void InputDispatcher::reportTouchEventForStatistics(const MotionEntry& motionEntry)
5671 REQUIRES(mLock) {
5672 const bool reportForStatistics = (motionEntry.source == AINPUT_SOURCE_TOUCHSCREEN) &&
5673 !(motionEntry.isSynthesized()) && !mInputFilterEnabled;
5674 if (!reportForStatistics) {
5675 return;
5676 }
5677
5678 if (mTouchStatistics.shouldReport()) {
5679 android::util::stats_write(android::util::TOUCH_EVENT_REPORTED, mTouchStatistics.getMin(),
5680 mTouchStatistics.getMax(), mTouchStatistics.getMean(),
5681 mTouchStatistics.getStDev(), mTouchStatistics.getCount());
5682 mTouchStatistics.reset();
5683 }
5684 const float latencyMicros = nanoseconds_to_microseconds(now() - motionEntry.eventTime);
5685 mTouchStatistics.addValue(latencyMicros);
5686}
5687
Michael Wrightd02c5b62014-02-10 15:10:22 -08005688void InputDispatcher::traceInboundQueueLengthLocked() {
5689 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005690 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005691 }
5692}
5693
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08005694void InputDispatcher::traceOutboundQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005695 if (ATRACE_ENABLED()) {
5696 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08005697 snprintf(counterName, sizeof(counterName), "oq:%s", connection->getWindowName().c_str());
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005698 ATRACE_INT(counterName, connection->outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005699 }
5700}
5701
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08005702void InputDispatcher::traceWaitQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005703 if (ATRACE_ENABLED()) {
5704 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08005705 snprintf(counterName, sizeof(counterName), "wq:%s", connection->getWindowName().c_str());
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005706 ATRACE_INT(counterName, connection->waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005707 }
5708}
5709
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005710void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005711 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005712
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005713 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005714 dumpDispatchStateLocked(dump);
5715
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005716 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005717 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005718 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005719 }
5720}
5721
5722void InputDispatcher::monitor() {
5723 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005724 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005725 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005726 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005727}
5728
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08005729/**
5730 * Wake up the dispatcher and wait until it processes all events and commands.
5731 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
5732 * this method can be safely called from any thread, as long as you've ensured that
5733 * the work you are interested in completing has already been queued.
5734 */
5735bool InputDispatcher::waitForIdle() {
5736 /**
5737 * Timeout should represent the longest possible time that a device might spend processing
5738 * events and commands.
5739 */
5740 constexpr std::chrono::duration TIMEOUT = 100ms;
5741 std::unique_lock lock(mLock);
5742 mLooper->wake();
5743 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
5744 return result == std::cv_status::no_timeout;
5745}
5746
Vishnu Naire798b472020-07-23 13:52:21 -07005747/**
5748 * Sets focus to the window identified by the token. This must be called
5749 * after updating any input window handles.
5750 *
5751 * Params:
5752 * request.token - input channel token used to identify the window that should gain focus.
5753 * request.focusedToken - the token that the caller expects currently to be focused. If the
5754 * specified token does not match the currently focused window, this request will be dropped.
5755 * If the specified focused token matches the currently focused window, the call will succeed.
5756 * Set this to "null" if this call should succeed no matter what the currently focused token is.
5757 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
5758 * when requesting the focus change. This determines which request gets
5759 * precedence if there is a focus change request from another source such as pointer down.
5760 */
Vishnu Nair958da932020-08-21 17:12:37 -07005761void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
5762 { // acquire lock
5763 std::scoped_lock _l(mLock);
5764
5765 const int32_t displayId = request.displayId;
5766 const sp<IBinder> oldFocusedToken = getValueByKey(mFocusedWindowTokenByDisplay, displayId);
5767 if (request.focusedToken && oldFocusedToken != request.focusedToken) {
5768 ALOGD_IF(DEBUG_FOCUS,
5769 "setFocusedWindow on display %" PRId32
5770 " ignored, reason: focusedToken is not focused",
5771 displayId);
5772 return;
5773 }
5774
5775 mPendingFocusRequests.erase(displayId);
5776 FocusResult result = handleFocusRequestLocked(request);
5777 if (result == FocusResult::NOT_VISIBLE) {
5778 // The requested window is not currently visible. Wait for the window to become visible
5779 // and then provide it focus. This is to handle situations where a user action triggers
5780 // a new window to appear. We want to be able to queue any key events after the user
5781 // action and deliver it to the newly focused window. In order for this to happen, we
5782 // take focus from the currently focused window so key events can be queued.
5783 ALOGD_IF(DEBUG_FOCUS,
5784 "setFocusedWindow on display %" PRId32
5785 " pending, reason: window is not visible",
5786 displayId);
5787 mPendingFocusRequests[displayId] = request;
5788 onFocusChangedLocked(oldFocusedToken, nullptr, displayId,
5789 "setFocusedWindow_AwaitingWindowVisibility");
5790 } else if (result != FocusResult::OK) {
5791 ALOGW("setFocusedWindow on display %" PRId32 " ignored, reason:%s", displayId,
5792 typeToString(result));
5793 }
5794 } // release lock
5795 // Wake up poll loop since it may need to make new input dispatching choices.
5796 mLooper->wake();
5797}
5798
5799InputDispatcher::FocusResult InputDispatcher::handleFocusRequestLocked(
5800 const FocusRequest& request) {
5801 const int32_t displayId = request.displayId;
5802 const sp<IBinder> newFocusedToken = request.token;
5803 const sp<IBinder> oldFocusedToken = getValueByKey(mFocusedWindowTokenByDisplay, displayId);
5804
5805 if (oldFocusedToken == request.token) {
5806 ALOGD_IF(DEBUG_FOCUS,
5807 "setFocusedWindow on display %" PRId32 " ignored, reason: already focused",
5808 displayId);
5809 return FocusResult::OK;
5810 }
5811
5812 FocusResult result = checkTokenFocusableLocked(newFocusedToken, displayId);
5813 if (result != FocusResult::OK) {
5814 return result;
5815 }
5816
5817 std::string_view reason =
5818 (request.focusedToken) ? "setFocusedWindow_FocusCheck" : "setFocusedWindow";
5819 onFocusChangedLocked(oldFocusedToken, newFocusedToken, displayId, reason);
5820 return FocusResult::OK;
5821}
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005822
Vishnu Nairad321cd2020-08-20 16:40:21 -07005823void InputDispatcher::onFocusChangedLocked(const sp<IBinder>& oldFocusedToken,
5824 const sp<IBinder>& newFocusedToken, int32_t displayId,
5825 std::string_view reason) {
5826 if (oldFocusedToken) {
5827 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(oldFocusedToken);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005828 if (focusedInputChannel) {
5829 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
5830 "focus left window");
5831 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Vishnu Nairad321cd2020-08-20 16:40:21 -07005832 enqueueFocusEventLocked(oldFocusedToken, false /*hasFocus*/, reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005833 }
Vishnu Nairad321cd2020-08-20 16:40:21 -07005834 mFocusedWindowTokenByDisplay.erase(displayId);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005835 }
Vishnu Nairad321cd2020-08-20 16:40:21 -07005836 if (newFocusedToken) {
5837 mFocusedWindowTokenByDisplay[displayId] = newFocusedToken;
5838 enqueueFocusEventLocked(newFocusedToken, true /*hasFocus*/, reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005839 }
5840
Prabir Pradhan99987712020-11-10 18:43:05 -08005841 // If a window has pointer capture, then it must have focus. We need to ensure that this
5842 // contract is upheld when pointer capture is being disabled due to a loss of window focus.
5843 // If the window loses focus before it loses pointer capture, then the window can be in a state
5844 // where it has pointer capture but not focus, violating the contract. Therefore we must
5845 // dispatch the pointer capture event before the focus event. Since focus events are added to
5846 // the front of the queue (above), we add the pointer capture event to the front of the queue
5847 // after the focus events are added. This ensures the pointer capture event ends up at the
5848 // front.
5849 disablePointerCaptureForcedLocked();
5850
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005851 if (mFocusedDisplayId == displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005852 notifyFocusChangedLocked(oldFocusedToken, newFocusedToken);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005853 }
5854}
Vishnu Nair958da932020-08-21 17:12:37 -07005855
Prabir Pradhan99987712020-11-10 18:43:05 -08005856void InputDispatcher::disablePointerCaptureForcedLocked() {
5857 if (!mFocusedWindowRequestedPointerCapture && !mWindowTokenWithPointerCapture) {
5858 return;
5859 }
5860
5861 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
5862
5863 if (mFocusedWindowRequestedPointerCapture) {
5864 mFocusedWindowRequestedPointerCapture = false;
5865 setPointerCaptureLocked(false);
5866 }
5867
5868 if (!mWindowTokenWithPointerCapture) {
5869 // No need to send capture changes because no window has capture.
5870 return;
5871 }
5872
5873 if (mPendingEvent != nullptr) {
5874 // Move the pending event to the front of the queue. This will give the chance
5875 // for the pending event to be dropped if it is a captured event.
5876 mInboundQueue.push_front(mPendingEvent);
5877 mPendingEvent = nullptr;
5878 }
5879
5880 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
5881 false /* hasCapture */);
5882 mInboundQueue.push_front(std::move(entry));
5883}
5884
Vishnu Nair958da932020-08-21 17:12:37 -07005885/**
5886 * Checks if the window token can be focused on a display. The token can be focused if there is
5887 * at least one window handle that is visible with the same token and all window handles with the
5888 * same token are focusable.
5889 *
5890 * In the case of mirroring, two windows may share the same window token and their visibility
5891 * might be different. Example, the mirrored window can cover the window its mirroring. However,
5892 * we expect the focusability of the windows to match since its hard to reason why one window can
5893 * receive focus events and the other cannot when both are backed by the same input channel.
5894 */
5895InputDispatcher::FocusResult InputDispatcher::checkTokenFocusableLocked(const sp<IBinder>& token,
5896 int32_t displayId) const {
5897 bool allWindowsAreFocusable = true;
5898 bool visibleWindowFound = false;
5899 bool windowFound = false;
5900 for (const sp<InputWindowHandle>& window : getWindowHandlesLocked(displayId)) {
5901 if (window->getToken() != token) {
5902 continue;
5903 }
5904 windowFound = true;
5905 if (window->getInfo()->visible) {
5906 // Check if at least a single window is visible.
5907 visibleWindowFound = true;
5908 }
5909 if (!window->getInfo()->focusable) {
5910 // Check if all windows with the window token are focusable.
5911 allWindowsAreFocusable = false;
5912 break;
5913 }
5914 }
5915
5916 if (!windowFound) {
5917 return FocusResult::NO_WINDOW;
5918 }
5919 if (!allWindowsAreFocusable) {
5920 return FocusResult::NOT_FOCUSABLE;
5921 }
5922 if (!visibleWindowFound) {
5923 return FocusResult::NOT_VISIBLE;
5924 }
5925
5926 return FocusResult::OK;
5927}
Prabir Pradhan99987712020-11-10 18:43:05 -08005928
5929void InputDispatcher::setPointerCaptureLocked(bool enabled) {
5930 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5931 &InputDispatcher::doSetPointerCaptureLockedInterruptible);
5932 commandEntry->enabled = enabled;
5933 postCommandLocked(std::move(commandEntry));
5934}
5935
5936void InputDispatcher::doSetPointerCaptureLockedInterruptible(
5937 android::inputdispatcher::CommandEntry* commandEntry) {
5938 mLock.unlock();
5939
5940 mPolicy->setPointerCapture(commandEntry->enabled);
5941
5942 mLock.lock();
5943}
5944
Garfield Tane84e6f92019-08-29 17:28:41 -07005945} // namespace android::inputdispatcher