blob: 3af33726fded55ff49107239a3377490179448d8 [file] [log] [blame]
Michael Wrightd02c5b62014-02-10 15:10:22 -08001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "InputDispatcher"
18#define ATRACE_TAG ATRACE_TAG_INPUT
19
John Recke0710582019-09-26 13:46:12 -070020#define LOG_NDEBUG 1
Michael Wrightd02c5b62014-02-10 15:10:22 -080021
22// Log detailed debug messages about each inbound event notification to the dispatcher.
23#define DEBUG_INBOUND_EVENT_DETAILS 0
24
25// Log detailed debug messages about each outbound event processed by the dispatcher.
26#define DEBUG_OUTBOUND_EVENT_DETAILS 0
27
28// Log debug messages about the dispatch cycle.
29#define DEBUG_DISPATCH_CYCLE 0
30
Garfield Tan15601662020-09-22 15:32:38 -070031// Log debug messages about channel creation
32#define DEBUG_CHANNEL_CREATION 0
Michael Wrightd02c5b62014-02-10 15:10:22 -080033
34// Log debug messages about input event injection.
35#define DEBUG_INJECTION 0
36
37// Log debug messages about input focus tracking.
Siarhei Vishniakou86587282019-09-09 18:20:15 +010038static constexpr bool DEBUG_FOCUS = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -080039
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +000040// Log debug messages about touch occlusion
41// STOPSHIP(b/169067926): Set to false
42static constexpr bool DEBUG_TOUCH_OCCLUSION = true;
43
Michael Wrightd02c5b62014-02-10 15:10:22 -080044// Log debug messages about the app switch latency optimization.
45#define DEBUG_APP_SWITCH 0
46
47// Log debug messages about hover events.
48#define DEBUG_HOVER 0
49
Michael Wright2b3c3302018-03-02 17:19:13 +000050#include <android-base/chrono_utils.h>
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080051#include <android-base/stringprintf.h>
Siarhei Vishniakou70622952020-07-30 11:17:23 -050052#include <android/os/IInputConstants.h>
Robert Carr4e670e52018-08-15 13:26:12 -070053#include <binder/Binder.h>
Siarhei Vishniakou2508b872020-12-03 16:33:53 -100054#include <binder/IServiceManager.h>
55#include <com/android/internal/compat/IPlatformCompatNative.h>
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -080056#include <input/InputDevice.h>
Michael Wright44753b12020-07-08 13:48:11 +010057#include <input/InputWindow.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070058#include <log/log.h>
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +000059#include <log/log_event_list.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070060#include <powermanager/PowerManager.h>
Michael Wright44753b12020-07-08 13:48:11 +010061#include <statslog.h>
62#include <unistd.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070063#include <utils/Trace.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080064
Michael Wright44753b12020-07-08 13:48:11 +010065#include <cerrno>
66#include <cinttypes>
67#include <climits>
68#include <cstddef>
69#include <ctime>
70#include <queue>
71#include <sstream>
72
73#include "Connection.h"
Chris Yef59a2f42020-10-16 12:55:26 -070074#include "InputDispatcher.h"
Michael Wright44753b12020-07-08 13:48:11 +010075
Michael Wrightd02c5b62014-02-10 15:10:22 -080076#define INDENT " "
77#define INDENT2 " "
78#define INDENT3 " "
79#define INDENT4 " "
80
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080081using android::base::StringPrintf;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -080082using android::os::BlockUntrustedTouchesMode;
Siarhei Vishniakou2508b872020-12-03 16:33:53 -100083using android::os::IInputConstants;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -080084using android::os::InputEventInjectionResult;
85using android::os::InputEventInjectionSync;
Siarhei Vishniakou2508b872020-12-03 16:33:53 -100086using com::android::internal::compat::IPlatformCompatNative;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080087
Garfield Tane84e6f92019-08-29 17:28:41 -070088namespace android::inputdispatcher {
Michael Wrightd02c5b62014-02-10 15:10:22 -080089
90// Default input dispatching timeout if there is no focused application or paused window
91// from which to determine an appropriate dispatching timeout.
Siarhei Vishniakou70622952020-07-30 11:17:23 -050092constexpr std::chrono::duration DEFAULT_INPUT_DISPATCHING_TIMEOUT =
93 std::chrono::milliseconds(android::os::IInputConstants::DEFAULT_DISPATCHING_TIMEOUT_MILLIS);
Michael Wrightd02c5b62014-02-10 15:10:22 -080094
95// Amount of time to allow for all pending events to be processed when an app switch
96// key is on the way. This is used to preempt input dispatch and drop input events
97// when an application takes too long to respond and the user has pressed an app switch key.
Michael Wright2b3c3302018-03-02 17:19:13 +000098constexpr nsecs_t APP_SWITCH_TIMEOUT = 500 * 1000000LL; // 0.5sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080099
100// Amount of time to allow for an event to be dispatched (measured since its eventTime)
101// before considering it stale and dropping it.
Michael Wright2b3c3302018-03-02 17:19:13 +0000102constexpr nsecs_t STALE_EVENT_TIMEOUT = 10000 * 1000000LL; // 10sec
Michael Wrightd02c5b62014-02-10 15:10:22 -0800103
Michael Wrightd02c5b62014-02-10 15:10:22 -0800104// Log a warning when an event takes longer than this to process, even if an ANR does not occur.
Michael Wright2b3c3302018-03-02 17:19:13 +0000105constexpr nsecs_t SLOW_EVENT_PROCESSING_WARNING_TIMEOUT = 2000 * 1000000LL; // 2sec
106
107// Log a warning when an interception call takes longer than this to process.
108constexpr std::chrono::milliseconds SLOW_INTERCEPTION_THRESHOLD = 50ms;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800109
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700110// Additional key latency in case a connection is still processing some motion events.
111// This will help with the case when a user touched a button that opens a new window,
112// and gives us the chance to dispatch the key to this new window.
113constexpr std::chrono::nanoseconds KEY_WAITING_FOR_EVENTS_TIMEOUT = 500ms;
114
Michael Wrightd02c5b62014-02-10 15:10:22 -0800115// Number of recent events to keep for debugging purposes.
Michael Wright2b3c3302018-03-02 17:19:13 +0000116constexpr size_t RECENT_QUEUE_MAX_SIZE = 10;
117
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +0000118// Event log tags. See EventLogTags.logtags for reference
119constexpr int LOGTAG_INPUT_INTERACTION = 62000;
120constexpr int LOGTAG_INPUT_FOCUS = 62001;
121
Michael Wrightd02c5b62014-02-10 15:10:22 -0800122static inline nsecs_t now() {
123 return systemTime(SYSTEM_TIME_MONOTONIC);
124}
125
126static inline const char* toString(bool value) {
127 return value ? "true" : "false";
128}
129
130static inline int32_t getMotionEventActionPointerIndex(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700131 return (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) >>
132 AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800133}
134
135static bool isValidKeyAction(int32_t action) {
136 switch (action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700137 case AKEY_EVENT_ACTION_DOWN:
138 case AKEY_EVENT_ACTION_UP:
139 return true;
140 default:
141 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800142 }
143}
144
145static bool validateKeyEvent(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700146 if (!isValidKeyAction(action)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800147 ALOGE("Key event has invalid action code 0x%x", action);
148 return false;
149 }
150 return true;
151}
152
Michael Wright7b159c92015-05-14 14:48:03 +0100153static bool isValidMotionAction(int32_t action, int32_t actionButton, int32_t pointerCount) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800154 switch (action & AMOTION_EVENT_ACTION_MASK) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700155 case AMOTION_EVENT_ACTION_DOWN:
156 case AMOTION_EVENT_ACTION_UP:
157 case AMOTION_EVENT_ACTION_CANCEL:
158 case AMOTION_EVENT_ACTION_MOVE:
159 case AMOTION_EVENT_ACTION_OUTSIDE:
160 case AMOTION_EVENT_ACTION_HOVER_ENTER:
161 case AMOTION_EVENT_ACTION_HOVER_MOVE:
162 case AMOTION_EVENT_ACTION_HOVER_EXIT:
163 case AMOTION_EVENT_ACTION_SCROLL:
164 return true;
165 case AMOTION_EVENT_ACTION_POINTER_DOWN:
166 case AMOTION_EVENT_ACTION_POINTER_UP: {
167 int32_t index = getMotionEventActionPointerIndex(action);
168 return index >= 0 && index < pointerCount;
169 }
170 case AMOTION_EVENT_ACTION_BUTTON_PRESS:
171 case AMOTION_EVENT_ACTION_BUTTON_RELEASE:
172 return actionButton != 0;
173 default:
174 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800175 }
176}
177
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -0500178static int64_t millis(std::chrono::nanoseconds t) {
179 return std::chrono::duration_cast<std::chrono::milliseconds>(t).count();
180}
181
Michael Wright7b159c92015-05-14 14:48:03 +0100182static bool validateMotionEvent(int32_t action, int32_t actionButton, size_t pointerCount,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700183 const PointerProperties* pointerProperties) {
184 if (!isValidMotionAction(action, actionButton, pointerCount)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800185 ALOGE("Motion event has invalid action code 0x%x", action);
186 return false;
187 }
188 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
Narayan Kamath37764c72014-03-27 14:21:09 +0000189 ALOGE("Motion event has invalid pointer count %zu; value must be between 1 and %d.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700190 pointerCount, MAX_POINTERS);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800191 return false;
192 }
193 BitSet32 pointerIdBits;
194 for (size_t i = 0; i < pointerCount; i++) {
195 int32_t id = pointerProperties[i].id;
196 if (id < 0 || id > MAX_POINTER_ID) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700197 ALOGE("Motion event has invalid pointer id %d; value must be between 0 and %d", id,
198 MAX_POINTER_ID);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800199 return false;
200 }
201 if (pointerIdBits.hasBit(id)) {
202 ALOGE("Motion event has duplicate pointer id %d", id);
203 return false;
204 }
205 pointerIdBits.markBit(id);
206 }
207 return true;
208}
209
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000210static std::string dumpRegion(const Region& region) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800211 if (region.isEmpty()) {
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000212 return "<empty>";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800213 }
214
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000215 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800216 bool first = true;
217 Region::const_iterator cur = region.begin();
218 Region::const_iterator const tail = region.end();
219 while (cur != tail) {
220 if (first) {
221 first = false;
222 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800223 dump += "|";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800224 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800225 dump += StringPrintf("[%d,%d][%d,%d]", cur->left, cur->top, cur->right, cur->bottom);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800226 cur++;
227 }
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000228 return dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800229}
230
Siarhei Vishniakou14411c92020-09-18 21:15:05 -0500231static std::string dumpQueue(const std::deque<DispatchEntry*>& queue, nsecs_t currentTime) {
232 constexpr size_t maxEntries = 50; // max events to print
233 constexpr size_t skipBegin = maxEntries / 2;
234 const size_t skipEnd = queue.size() - maxEntries / 2;
235 // skip from maxEntries / 2 ... size() - maxEntries/2
236 // only print from 0 .. skipBegin and then from skipEnd .. size()
237
238 std::string dump;
239 for (size_t i = 0; i < queue.size(); i++) {
240 const DispatchEntry& entry = *queue[i];
241 if (i >= skipBegin && i < skipEnd) {
242 dump += StringPrintf(INDENT4 "<skipped %zu entries>\n", skipEnd - skipBegin);
243 i = skipEnd - 1; // it will be incremented to "skipEnd" by 'continue'
244 continue;
245 }
246 dump.append(INDENT4);
247 dump += entry.eventEntry->getDescription();
248 dump += StringPrintf(", seq=%" PRIu32
249 ", targetFlags=0x%08x, resolvedAction=%d, age=%" PRId64 "ms",
250 entry.seq, entry.targetFlags, entry.resolvedAction,
251 ns2ms(currentTime - entry.eventEntry->eventTime));
252 if (entry.deliveryTime != 0) {
253 // This entry was delivered, so add information on how long we've been waiting
254 dump += StringPrintf(", wait=%" PRId64 "ms", ns2ms(currentTime - entry.deliveryTime));
255 }
256 dump.append("\n");
257 }
258 return dump;
259}
260
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700261/**
262 * Find the entry in std::unordered_map by key, and return it.
263 * If the entry is not found, return a default constructed entry.
264 *
265 * Useful when the entries are vectors, since an empty vector will be returned
266 * if the entry is not found.
267 * Also useful when the entries are sp<>. If an entry is not found, nullptr is returned.
268 */
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700269template <typename K, typename V>
270static V getValueByKey(const std::unordered_map<K, V>& map, K key) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700271 auto it = map.find(key);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700272 return it != map.end() ? it->second : V{};
Tiger Huang721e26f2018-07-24 22:26:19 +0800273}
274
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700275/**
276 * Find the entry in std::unordered_map by value, and remove it.
277 * If more than one entry has the same value, then all matching
278 * key-value pairs will be removed.
279 *
280 * Return true if at least one value has been removed.
281 */
282template <typename K, typename V>
283static bool removeByValue(std::unordered_map<K, V>& map, const V& value) {
284 bool removed = false;
285 for (auto it = map.begin(); it != map.end();) {
286 if (it->second == value) {
287 it = map.erase(it);
288 removed = true;
289 } else {
290 it++;
291 }
292 }
293 return removed;
294}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800295
Vishnu Nair958da932020-08-21 17:12:37 -0700296/**
297 * Find the entry in std::unordered_map by key and return the value as an optional.
298 */
299template <typename K, typename V>
300static std::optional<V> getOptionalValueByKey(const std::unordered_map<K, V>& map, K key) {
301 auto it = map.find(key);
302 return it != map.end() ? std::optional<V>{it->second} : std::nullopt;
303}
304
chaviwaf87b3e2019-10-01 16:59:28 -0700305static bool haveSameToken(const sp<InputWindowHandle>& first, const sp<InputWindowHandle>& second) {
306 if (first == second) {
307 return true;
308 }
309
310 if (first == nullptr || second == nullptr) {
311 return false;
312 }
313
314 return first->getToken() == second->getToken();
315}
316
Siarhei Vishniakouadfd4fa2019-12-20 11:02:58 -0800317static bool isStaleEvent(nsecs_t currentTime, const EventEntry& entry) {
318 return currentTime - entry.eventTime >= STALE_EVENT_TIMEOUT;
319}
320
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000321static std::unique_ptr<DispatchEntry> createDispatchEntry(const InputTarget& inputTarget,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700322 std::shared_ptr<EventEntry> eventEntry,
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000323 int32_t inputTargetFlags) {
chaviw1ff3d1e2020-07-01 15:53:47 -0700324 if (inputTarget.useDefaultPointerTransform()) {
325 const ui::Transform& transform = inputTarget.getDefaultPointerTransform();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700326 return std::make_unique<DispatchEntry>(eventEntry, inputTargetFlags, transform,
chaviw1ff3d1e2020-07-01 15:53:47 -0700327 inputTarget.globalScaleFactor);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000328 }
329
330 ALOG_ASSERT(eventEntry->type == EventEntry::Type::MOTION);
331 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
332
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700333 std::vector<PointerCoords> pointerCoords;
334 pointerCoords.resize(motionEntry.pointerCount);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000335
336 // Use the first pointer information to normalize all other pointers. This could be any pointer
337 // as long as all other pointers are normalized to the same value and the final DispatchEntry
chaviw1ff3d1e2020-07-01 15:53:47 -0700338 // uses the transform for the normalized pointer.
339 const ui::Transform& firstPointerTransform =
340 inputTarget.pointerTransforms[inputTarget.pointerIds.firstMarkedBit()];
341 ui::Transform inverseFirstTransform = firstPointerTransform.inverse();
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000342
343 // Iterate through all pointers in the event to normalize against the first.
344 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.pointerCount; pointerIndex++) {
345 const PointerProperties& pointerProperties = motionEntry.pointerProperties[pointerIndex];
346 uint32_t pointerId = uint32_t(pointerProperties.id);
chaviw1ff3d1e2020-07-01 15:53:47 -0700347 const ui::Transform& currTransform = inputTarget.pointerTransforms[pointerId];
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000348
349 pointerCoords[pointerIndex].copyFrom(motionEntry.pointerCoords[pointerIndex]);
chaviw1ff3d1e2020-07-01 15:53:47 -0700350 // First, apply the current pointer's transform to update the coordinates into
351 // window space.
352 pointerCoords[pointerIndex].transform(currTransform);
353 // Next, apply the inverse transform of the normalized coordinates so the
354 // current coordinates are transformed into the normalized coordinate space.
355 pointerCoords[pointerIndex].transform(inverseFirstTransform);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000356 }
357
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700358 std::unique_ptr<MotionEntry> combinedMotionEntry =
359 std::make_unique<MotionEntry>(motionEntry.id, motionEntry.eventTime,
360 motionEntry.deviceId, motionEntry.source,
361 motionEntry.displayId, motionEntry.policyFlags,
362 motionEntry.action, motionEntry.actionButton,
363 motionEntry.flags, motionEntry.metaState,
364 motionEntry.buttonState, motionEntry.classification,
365 motionEntry.edgeFlags, motionEntry.xPrecision,
366 motionEntry.yPrecision, motionEntry.xCursorPosition,
367 motionEntry.yCursorPosition, motionEntry.downTime,
368 motionEntry.pointerCount, motionEntry.pointerProperties,
369 pointerCoords.data(), 0 /* xOffset */, 0 /* yOffset */);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000370
371 if (motionEntry.injectionState) {
372 combinedMotionEntry->injectionState = motionEntry.injectionState;
373 combinedMotionEntry->injectionState->refCount += 1;
374 }
375
376 std::unique_ptr<DispatchEntry> dispatchEntry =
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700377 std::make_unique<DispatchEntry>(std::move(combinedMotionEntry), inputTargetFlags,
378 firstPointerTransform, inputTarget.globalScaleFactor);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000379 return dispatchEntry;
380}
381
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -0700382static void addGestureMonitors(const std::vector<Monitor>& monitors,
383 std::vector<TouchedMonitor>& outTouchedMonitors, float xOffset = 0,
384 float yOffset = 0) {
385 if (monitors.empty()) {
386 return;
387 }
388 outTouchedMonitors.reserve(monitors.size() + outTouchedMonitors.size());
389 for (const Monitor& monitor : monitors) {
390 outTouchedMonitors.emplace_back(monitor, xOffset, yOffset);
391 }
392}
393
Garfield Tan15601662020-09-22 15:32:38 -0700394static status_t openInputChannelPair(const std::string& name,
395 std::shared_ptr<InputChannel>& serverChannel,
396 std::unique_ptr<InputChannel>& clientChannel) {
397 std::unique_ptr<InputChannel> uniqueServerChannel;
398 status_t result = InputChannel::openInputChannelPair(name, uniqueServerChannel, clientChannel);
399
400 serverChannel = std::move(uniqueServerChannel);
401 return result;
402}
403
Vishnu Nair958da932020-08-21 17:12:37 -0700404const char* InputDispatcher::typeToString(InputDispatcher::FocusResult result) {
405 switch (result) {
406 case InputDispatcher::FocusResult::OK:
407 return "Ok";
408 case InputDispatcher::FocusResult::NO_WINDOW:
409 return "Window not found";
410 case InputDispatcher::FocusResult::NOT_FOCUSABLE:
411 return "Window not focusable";
412 case InputDispatcher::FocusResult::NOT_VISIBLE:
413 return "Window not visible";
414 }
415}
416
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500417template <typename T>
418static bool sharedPointersEqual(const std::shared_ptr<T>& lhs, const std::shared_ptr<T>& rhs) {
419 if (lhs == nullptr && rhs == nullptr) {
420 return true;
421 }
422 if (lhs == nullptr || rhs == nullptr) {
423 return false;
424 }
425 return *lhs == *rhs;
426}
427
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000428static sp<IPlatformCompatNative> getCompatService() {
429 sp<IBinder> service(defaultServiceManager()->getService(String16("platform_compat_native")));
430 if (service == nullptr) {
431 ALOGE("Failed to link to compat service");
432 return nullptr;
433 }
434 return interface_cast<IPlatformCompatNative>(service);
435}
436
Michael Wrightd02c5b62014-02-10 15:10:22 -0800437// --- InputDispatcher ---
438
Garfield Tan00f511d2019-06-12 16:55:40 -0700439InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy)
440 : mPolicy(policy),
441 mPendingEvent(nullptr),
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700442 mLastDropReason(DropReason::NOT_DROPPED),
Garfield Tanff1f1bb2020-01-28 13:24:04 -0800443 mIdGenerator(IdGenerator::Source::INPUT_DISPATCHER),
Garfield Tan00f511d2019-06-12 16:55:40 -0700444 mAppSwitchSawKeyDown(false),
445 mAppSwitchDueTime(LONG_LONG_MAX),
446 mNextUnblockedEvent(nullptr),
447 mDispatchEnabled(false),
448 mDispatchFrozen(false),
449 mInputFilterEnabled(false),
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -0800450 // mInTouchMode will be initialized by the WindowManager to the default device config.
451 // To avoid leaking stack in case that call never comes, and for tests,
452 // initialize it here anyways.
453 mInTouchMode(true),
Bernardo Rufinoea97d182020-08-19 14:43:14 +0100454 mMaximumObscuringOpacityForTouch(1.0f),
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000455 mFocusedDisplayId(ADISPLAY_ID_DEFAULT),
Prabir Pradhan99987712020-11-10 18:43:05 -0800456 mFocusedWindowRequestedPointerCapture(false),
457 mWindowTokenWithPointerCapture(nullptr),
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000458 mCompatService(getCompatService()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800459 mLooper = new Looper(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800460 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800461
Yi Kong9b14ac62018-07-17 13:48:38 -0700462 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800463
464 policy->getDispatcherConfiguration(&mConfig);
465}
466
467InputDispatcher::~InputDispatcher() {
468 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800469 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800470
471 resetKeyRepeatLocked();
472 releasePendingEventLocked();
473 drainInboundQueueLocked();
474 }
475
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700476 while (!mConnectionsByFd.empty()) {
477 sp<Connection> connection = mConnectionsByFd.begin()->second;
Garfield Tan15601662020-09-22 15:32:38 -0700478 removeInputChannel(connection->inputChannel->getConnectionToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800479 }
480}
481
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700482status_t InputDispatcher::start() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700483 if (mThread) {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700484 return ALREADY_EXISTS;
485 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700486 mThread = std::make_unique<InputThread>(
487 "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
488 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700489}
490
491status_t InputDispatcher::stop() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700492 if (mThread && mThread->isCallingThread()) {
493 ALOGE("InputDispatcher cannot be stopped from its own thread!");
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700494 return INVALID_OPERATION;
495 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700496 mThread.reset();
497 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700498}
499
Michael Wrightd02c5b62014-02-10 15:10:22 -0800500void InputDispatcher::dispatchOnce() {
501 nsecs_t nextWakeupTime = LONG_LONG_MAX;
502 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800503 std::scoped_lock _l(mLock);
504 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800505
506 // Run a dispatch loop if there are no pending commands.
507 // The dispatch loop might enqueue commands to run afterwards.
508 if (!haveCommandsLocked()) {
509 dispatchOnceInnerLocked(&nextWakeupTime);
510 }
511
512 // Run all pending commands if there are any.
513 // If any commands were run then force the next poll to wake up immediately.
514 if (runCommandsLockedInterruptible()) {
515 nextWakeupTime = LONG_LONG_MIN;
516 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800517
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700518 // If we are still waiting for ack on some events,
519 // we might have to wake up earlier to check if an app is anr'ing.
520 const nsecs_t nextAnrCheck = processAnrsLocked();
521 nextWakeupTime = std::min(nextWakeupTime, nextAnrCheck);
522
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800523 // We are about to enter an infinitely long sleep, because we have no commands or
524 // pending or queued events
525 if (nextWakeupTime == LONG_LONG_MAX) {
526 mDispatcherEnteredIdle.notify_all();
527 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800528 } // release lock
529
530 // Wait for callback or timeout or wake. (make sure we round up, not down)
531 nsecs_t currentTime = now();
532 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
533 mLooper->pollOnce(timeoutMillis);
534}
535
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700536/**
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500537 * Raise ANR if there is no focused window.
538 * Before the ANR is raised, do a final state check:
539 * 1. The currently focused application must be the same one we are waiting for.
540 * 2. Ensure we still don't have a focused window.
541 */
542void InputDispatcher::processNoFocusedWindowAnrLocked() {
543 // Check if the application that we are waiting for is still focused.
544 std::shared_ptr<InputApplicationHandle> focusedApplication =
545 getValueByKey(mFocusedApplicationHandlesByDisplay, mAwaitedApplicationDisplayId);
546 if (focusedApplication == nullptr ||
547 focusedApplication->getApplicationToken() !=
548 mAwaitedFocusedApplication->getApplicationToken()) {
549 // Unexpected because we should have reset the ANR timer when focused application changed
550 ALOGE("Waited for a focused window, but focused application has already changed to %s",
551 focusedApplication->getName().c_str());
552 return; // The focused application has changed.
553 }
554
555 const sp<InputWindowHandle>& focusedWindowHandle =
556 getFocusedWindowHandleLocked(mAwaitedApplicationDisplayId);
557 if (focusedWindowHandle != nullptr) {
558 return; // We now have a focused window. No need for ANR.
559 }
560 onAnrLocked(mAwaitedFocusedApplication);
561}
562
563/**
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700564 * Check if any of the connections' wait queues have events that are too old.
565 * If we waited for events to be ack'ed for more than the window timeout, raise an ANR.
566 * Return the time at which we should wake up next.
567 */
568nsecs_t InputDispatcher::processAnrsLocked() {
569 const nsecs_t currentTime = now();
570 nsecs_t nextAnrCheck = LONG_LONG_MAX;
571 // Check if we are waiting for a focused window to appear. Raise ANR if waited too long
572 if (mNoFocusedWindowTimeoutTime.has_value() && mAwaitedFocusedApplication != nullptr) {
573 if (currentTime >= *mNoFocusedWindowTimeoutTime) {
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500574 processNoFocusedWindowAnrLocked();
Chris Yea209fde2020-07-22 13:54:51 -0700575 mAwaitedFocusedApplication.reset();
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500576 mNoFocusedWindowTimeoutTime = std::nullopt;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700577 return LONG_LONG_MIN;
578 } else {
Siarhei Vishniakou38a6d272020-10-20 20:29:33 -0500579 // Keep waiting. We will drop the event when mNoFocusedWindowTimeoutTime comes.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700580 nextAnrCheck = *mNoFocusedWindowTimeoutTime;
581 }
582 }
583
584 // Check if any connection ANRs are due
585 nextAnrCheck = std::min(nextAnrCheck, mAnrTracker.firstTimeout());
586 if (currentTime < nextAnrCheck) { // most likely scenario
587 return nextAnrCheck; // everything is normal. Let's check again at nextAnrCheck
588 }
589
590 // If we reached here, we have an unresponsive connection.
591 sp<Connection> connection = getConnectionLocked(mAnrTracker.firstToken());
592 if (connection == nullptr) {
593 ALOGE("Could not find connection for entry %" PRId64, mAnrTracker.firstTimeout());
594 return nextAnrCheck;
595 }
596 connection->responsive = false;
597 // Stop waking up for this unresponsive connection
598 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -0500599 onAnrLocked(*connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700600 return LONG_LONG_MIN;
601}
602
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500603std::chrono::nanoseconds InputDispatcher::getDispatchingTimeoutLocked(const sp<IBinder>& token) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700604 sp<InputWindowHandle> window = getWindowHandleLocked(token);
605 if (window != nullptr) {
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500606 return window->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700607 }
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500608 return DEFAULT_INPUT_DISPATCHING_TIMEOUT;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700609}
610
Michael Wrightd02c5b62014-02-10 15:10:22 -0800611void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
612 nsecs_t currentTime = now();
613
Jeff Browndc5992e2014-04-11 01:27:26 -0700614 // Reset the key repeat timer whenever normal dispatch is suspended while the
615 // device is in a non-interactive state. This is to ensure that we abort a key
616 // repeat if the device is just coming out of sleep.
617 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800618 resetKeyRepeatLocked();
619 }
620
621 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
622 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +0100623 if (DEBUG_FOCUS) {
624 ALOGD("Dispatch frozen. Waiting some more.");
625 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800626 return;
627 }
628
629 // Optimize latency of app switches.
630 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
631 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
632 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
633 if (mAppSwitchDueTime < *nextWakeupTime) {
634 *nextWakeupTime = mAppSwitchDueTime;
635 }
636
637 // Ready to start a new event.
638 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700639 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700640 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800641 if (isAppSwitchDue) {
642 // The inbound queue is empty so the app switch key we were waiting
643 // for will never arrive. Stop waiting for it.
644 resetPendingAppSwitchLocked(false);
645 isAppSwitchDue = false;
646 }
647
648 // Synthesize a key repeat if appropriate.
649 if (mKeyRepeatState.lastKeyEntry) {
650 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
651 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
652 } else {
653 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
654 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
655 }
656 }
657 }
658
659 // Nothing to do if there is no pending event.
660 if (!mPendingEvent) {
661 return;
662 }
663 } else {
664 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700665 mPendingEvent = mInboundQueue.front();
666 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800667 traceInboundQueueLengthLocked();
668 }
669
670 // Poke user activity for this event.
671 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700672 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800673 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800674 }
675
676 // Now we have an event to dispatch.
677 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700678 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800679 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700680 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800681 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700682 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800683 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700684 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800685 }
686
687 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700688 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800689 }
690
691 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700692 case EventEntry::Type::CONFIGURATION_CHANGED: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700693 const ConfigurationChangedEntry& typedEntry =
694 static_cast<const ConfigurationChangedEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700695 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700696 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700697 break;
698 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800699
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700700 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700701 const DeviceResetEntry& typedEntry =
702 static_cast<const DeviceResetEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700703 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700704 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700705 break;
706 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800707
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100708 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700709 std::shared_ptr<FocusEntry> typedEntry =
710 std::static_pointer_cast<FocusEntry>(mPendingEvent);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100711 dispatchFocusLocked(currentTime, typedEntry);
712 done = true;
713 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
714 break;
715 }
716
Prabir Pradhan99987712020-11-10 18:43:05 -0800717 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
718 const auto typedEntry =
719 std::static_pointer_cast<PointerCaptureChangedEntry>(mPendingEvent);
720 dispatchPointerCaptureChangedLocked(currentTime, typedEntry, dropReason);
721 done = true;
722 break;
723 }
724
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700725 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700726 std::shared_ptr<KeyEntry> keyEntry = std::static_pointer_cast<KeyEntry>(mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700727 if (isAppSwitchDue) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700728 if (isAppSwitchKeyEvent(*keyEntry)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700729 resetPendingAppSwitchLocked(true);
730 isAppSwitchDue = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700731 } else if (dropReason == DropReason::NOT_DROPPED) {
732 dropReason = DropReason::APP_SWITCH;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700733 }
734 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700735 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *keyEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700736 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700737 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700738 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
739 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700740 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700741 done = dispatchKeyLocked(currentTime, keyEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700742 break;
743 }
744
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700745 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700746 std::shared_ptr<MotionEntry> motionEntry =
747 std::static_pointer_cast<MotionEntry>(mPendingEvent);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700748 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
749 dropReason = DropReason::APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800750 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700751 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *motionEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700752 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700753 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700754 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
755 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700756 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700757 done = dispatchMotionLocked(currentTime, motionEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700758 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800759 }
Chris Yef59a2f42020-10-16 12:55:26 -0700760
761 case EventEntry::Type::SENSOR: {
762 std::shared_ptr<SensorEntry> sensorEntry =
763 std::static_pointer_cast<SensorEntry>(mPendingEvent);
764 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
765 dropReason = DropReason::APP_SWITCH;
766 }
767 // Sensor timestamps use SYSTEM_TIME_BOOTTIME time base, so we can't use
768 // 'currentTime' here, get SYSTEM_TIME_BOOTTIME instead.
769 nsecs_t bootTime = systemTime(SYSTEM_TIME_BOOTTIME);
770 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(bootTime, *sensorEntry)) {
771 dropReason = DropReason::STALE;
772 }
773 dispatchSensorLocked(currentTime, sensorEntry, &dropReason, nextWakeupTime);
774 done = true;
775 break;
776 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800777 }
778
779 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700780 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700781 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800782 }
Michael Wright3a981722015-06-10 15:26:13 +0100783 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800784
785 releasePendingEventLocked();
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700786 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -0800787 }
788}
789
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700790/**
791 * Return true if the events preceding this incoming motion event should be dropped
792 * Return false otherwise (the default behaviour)
793 */
794bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700795 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700796 (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700797
798 // Optimize case where the current application is unresponsive and the user
799 // decides to touch a window in a different application.
800 // If the application takes too long to catch up then we drop all events preceding
801 // the touch into the other window.
802 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700803 int32_t displayId = motionEntry.displayId;
804 int32_t x = static_cast<int32_t>(
805 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
806 int32_t y = static_cast<int32_t>(
807 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
808 sp<InputWindowHandle> touchedWindowHandle =
809 findTouchedWindowAtLocked(displayId, x, y, nullptr);
810 if (touchedWindowHandle != nullptr &&
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700811 touchedWindowHandle->getApplicationToken() !=
812 mAwaitedFocusedApplication->getApplicationToken()) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700813 // User touched a different application than the one we are waiting on.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700814 ALOGI("Pruning input queue because user touched a different application while waiting "
815 "for %s",
816 mAwaitedFocusedApplication->getName().c_str());
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700817 return true;
818 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700819
820 // Alternatively, maybe there's a gesture monitor that could handle this event
821 std::vector<TouchedMonitor> gestureMonitors =
822 findTouchedGestureMonitorsLocked(displayId, {});
823 for (TouchedMonitor& gestureMonitor : gestureMonitors) {
824 sp<Connection> connection =
825 getConnectionLocked(gestureMonitor.monitor.inputChannel->getConnectionToken());
Siarhei Vishniakou34ed4d42020-06-18 00:43:02 +0000826 if (connection != nullptr && connection->responsive) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700827 // This monitor could take more input. Drop all events preceding this
828 // event, so that gesture monitor could get a chance to receive the stream
829 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
830 "responsive gesture monitor that may handle the event",
831 mAwaitedFocusedApplication->getName().c_str());
832 return true;
833 }
834 }
835 }
836
837 // Prevent getting stuck: if we have a pending key event, and some motion events that have not
838 // yet been processed by some connections, the dispatcher will wait for these motion
839 // events to be processed before dispatching the key event. This is because these motion events
840 // may cause a new window to be launched, which the user might expect to receive focus.
841 // To prevent waiting forever for such events, just send the key to the currently focused window
842 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
843 ALOGD("Received a new pointer down event, stop waiting for events to process and "
844 "just send the pending key event to the focused window.");
845 mKeyIsWaitingForEventsTimeout = now();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700846 }
847 return false;
848}
849
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700850bool InputDispatcher::enqueueInboundEventLocked(std::unique_ptr<EventEntry> newEntry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700851 bool needWake = mInboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700852 mInboundQueue.push_back(std::move(newEntry));
853 EventEntry& entry = *(mInboundQueue.back());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800854 traceInboundQueueLengthLocked();
855
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700856 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700857 case EventEntry::Type::KEY: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700858 // Optimize app switch latency.
859 // If the application takes too long to catch up then we drop all events preceding
860 // the app switch key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700861 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700862 if (isAppSwitchKeyEvent(keyEntry)) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700863 if (keyEntry.action == AKEY_EVENT_ACTION_DOWN) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700864 mAppSwitchSawKeyDown = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700865 } else if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700866 if (mAppSwitchSawKeyDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800867#if DEBUG_APP_SWITCH
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700868 ALOGD("App switch is pending!");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800869#endif
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700870 mAppSwitchDueTime = keyEntry.eventTime + APP_SWITCH_TIMEOUT;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700871 mAppSwitchSawKeyDown = false;
872 needWake = true;
873 }
874 }
875 }
876 break;
877 }
878
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700879 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700880 if (shouldPruneInboundQueueLocked(static_cast<MotionEntry&>(entry))) {
881 mNextUnblockedEvent = mInboundQueue.back();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700882 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800883 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700884 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800885 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100886 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700887 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
888 break;
889 }
890 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -0800891 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -0700892 case EventEntry::Type::SENSOR:
Prabir Pradhan99987712020-11-10 18:43:05 -0800893 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700894 // nothing to do
895 break;
896 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800897 }
898
899 return needWake;
900}
901
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700902void InputDispatcher::addRecentEventLocked(std::shared_ptr<EventEntry> entry) {
Chris Yef59a2f42020-10-16 12:55:26 -0700903 // Do not store sensor event in recent queue to avoid flooding the queue.
904 if (entry->type != EventEntry::Type::SENSOR) {
905 mRecentQueue.push_back(entry);
906 }
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700907 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700908 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800909 }
910}
911
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700912sp<InputWindowHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, int32_t x,
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700913 int32_t y, TouchState* touchState,
914 bool addOutsideTargets,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700915 bool addPortalWindows) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700916 if ((addPortalWindows || addOutsideTargets) && touchState == nullptr) {
917 LOG_ALWAYS_FATAL(
918 "Must provide a valid touch state if adding portal windows or outside targets");
919 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800920 // Traverse windows from front to back to find touched window.
Vishnu Nairad321cd2020-08-20 16:40:21 -0700921 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800922 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800923 const InputWindowInfo* windowInfo = windowHandle->getInfo();
924 if (windowInfo->displayId == displayId) {
Michael Wright44753b12020-07-08 13:48:11 +0100925 auto flags = windowInfo->flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800926
927 if (windowInfo->visible) {
Michael Wright44753b12020-07-08 13:48:11 +0100928 if (!flags.test(InputWindowInfo::Flag::NOT_TOUCHABLE)) {
929 bool isTouchModal = !flags.test(InputWindowInfo::Flag::NOT_FOCUSABLE) &&
930 !flags.test(InputWindowInfo::Flag::NOT_TOUCH_MODAL);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800931 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800932 int32_t portalToDisplayId = windowInfo->portalToDisplayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700933 if (portalToDisplayId != ADISPLAY_ID_NONE &&
934 portalToDisplayId != displayId) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800935 if (addPortalWindows) {
936 // For the monitoring channels of the display.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700937 touchState->addPortalWindow(windowHandle);
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800938 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700939 return findTouchedWindowAtLocked(portalToDisplayId, x, y, touchState,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700940 addOutsideTargets, addPortalWindows);
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800941 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800942 // Found window.
943 return windowHandle;
944 }
945 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800946
Michael Wright44753b12020-07-08 13:48:11 +0100947 if (addOutsideTargets && flags.test(InputWindowInfo::Flag::WATCH_OUTSIDE_TOUCH)) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700948 touchState->addOrUpdateWindow(windowHandle,
949 InputTarget::FLAG_DISPATCH_AS_OUTSIDE,
950 BitSet32(0));
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800951 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800952 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800953 }
954 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700955 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800956}
957
Garfield Tane84e6f92019-08-29 17:28:41 -0700958std::vector<TouchedMonitor> InputDispatcher::findTouchedGestureMonitorsLocked(
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -0700959 int32_t displayId, const std::vector<sp<InputWindowHandle>>& portalWindows) const {
Michael Wright3dd60e22019-03-27 22:06:44 +0000960 std::vector<TouchedMonitor> touchedMonitors;
961
962 std::vector<Monitor> monitors = getValueByKey(mGestureMonitorsByDisplay, displayId);
963 addGestureMonitors(monitors, touchedMonitors);
964 for (const sp<InputWindowHandle>& portalWindow : portalWindows) {
965 const InputWindowInfo* windowInfo = portalWindow->getInfo();
966 monitors = getValueByKey(mGestureMonitorsByDisplay, windowInfo->portalToDisplayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700967 addGestureMonitors(monitors, touchedMonitors, -windowInfo->frameLeft,
968 -windowInfo->frameTop);
Michael Wright3dd60e22019-03-27 22:06:44 +0000969 }
970 return touchedMonitors;
971}
972
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700973void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800974 const char* reason;
975 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700976 case DropReason::POLICY:
Michael Wrightd02c5b62014-02-10 15:10:22 -0800977#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700978 ALOGD("Dropped event because policy consumed it.");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800979#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700980 reason = "inbound event was dropped because the policy consumed it";
981 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700982 case DropReason::DISABLED:
983 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700984 ALOGI("Dropped event because input dispatch is disabled.");
985 }
986 reason = "inbound event was dropped because input dispatch is disabled";
987 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700988 case DropReason::APP_SWITCH:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700989 ALOGI("Dropped event because of pending overdue app switch.");
990 reason = "inbound event was dropped because of pending overdue app switch";
991 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700992 case DropReason::BLOCKED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700993 ALOGI("Dropped event because the current application is not responding and the user "
994 "has started interacting with a different application.");
995 reason = "inbound event was dropped because the current application is not responding "
996 "and the user has started interacting with a different application";
997 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700998 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700999 ALOGI("Dropped event because it is stale.");
1000 reason = "inbound event was dropped because it is stale";
1001 break;
Prabir Pradhan99987712020-11-10 18:43:05 -08001002 case DropReason::NO_POINTER_CAPTURE:
1003 ALOGI("Dropped event because there is no window with Pointer Capture.");
1004 reason = "inbound event was dropped because there is no window with Pointer Capture";
1005 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001006 case DropReason::NOT_DROPPED: {
1007 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001008 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001009 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001010 }
1011
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001012 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001013 case EventEntry::Type::KEY: {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001014 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
1015 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001016 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001017 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001018 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001019 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1020 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001021 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
1022 synthesizeCancelationEventsForAllConnectionsLocked(options);
1023 } else {
1024 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
1025 synthesizeCancelationEventsForAllConnectionsLocked(options);
1026 }
1027 break;
1028 }
Chris Yef59a2f42020-10-16 12:55:26 -07001029 case EventEntry::Type::SENSOR: {
1030 break;
1031 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001032 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
1033 break;
1034 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001035 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001036 case EventEntry::Type::CONFIGURATION_CHANGED:
1037 case EventEntry::Type::DEVICE_RESET: {
Chris Yef59a2f42020-10-16 12:55:26 -07001038 LOG_ALWAYS_FATAL("Should not drop %s events", NamedEnum::string(entry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001039 break;
1040 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001041 }
1042}
1043
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001044static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001045 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
1046 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001047}
1048
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001049bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
1050 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
1051 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
1052 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001053}
1054
1055bool InputDispatcher::isAppSwitchPendingLocked() {
1056 return mAppSwitchDueTime != LONG_LONG_MAX;
1057}
1058
1059void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
1060 mAppSwitchDueTime = LONG_LONG_MAX;
1061
1062#if DEBUG_APP_SWITCH
1063 if (handled) {
1064 ALOGD("App switch has arrived.");
1065 } else {
1066 ALOGD("App switch was abandoned.");
1067 }
1068#endif
1069}
1070
Michael Wrightd02c5b62014-02-10 15:10:22 -08001071bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001072 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001073}
1074
1075bool InputDispatcher::runCommandsLockedInterruptible() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001076 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001077 return false;
1078 }
1079
1080 do {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001081 std::unique_ptr<CommandEntry> commandEntry = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001082 mCommandQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001083 Command command = commandEntry->command;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001084 command(*this, commandEntry.get()); // commands are implicitly 'LockedInterruptible'
Michael Wrightd02c5b62014-02-10 15:10:22 -08001085
1086 commandEntry->connection.clear();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001087 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001088 return true;
1089}
1090
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001091void InputDispatcher::postCommandLocked(std::unique_ptr<CommandEntry> commandEntry) {
1092 mCommandQueue.push_back(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001093}
1094
1095void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001096 while (!mInboundQueue.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001097 std::shared_ptr<EventEntry> entry = mInboundQueue.front();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001098 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001099 releaseInboundEventLocked(entry);
1100 }
1101 traceInboundQueueLengthLocked();
1102}
1103
1104void InputDispatcher::releasePendingEventLocked() {
1105 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001106 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -07001107 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001108 }
1109}
1110
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001111void InputDispatcher::releaseInboundEventLocked(std::shared_ptr<EventEntry> entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001112 InjectionState* injectionState = entry->injectionState;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001113 if (injectionState && injectionState->injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001114#if DEBUG_DISPATCH_CYCLE
1115 ALOGD("Injected inbound event was dropped.");
1116#endif
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001117 setInjectionResult(*entry, InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001118 }
1119 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001120 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001121 }
1122 addRecentEventLocked(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001123}
1124
1125void InputDispatcher::resetKeyRepeatLocked() {
1126 if (mKeyRepeatState.lastKeyEntry) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001127 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001128 }
1129}
1130
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001131std::shared_ptr<KeyEntry> InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
1132 std::shared_ptr<KeyEntry> entry = mKeyRepeatState.lastKeyEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001133
Michael Wright2e732952014-09-24 13:26:59 -07001134 uint32_t policyFlags = entry->policyFlags &
1135 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001136
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001137 std::shared_ptr<KeyEntry> newEntry =
1138 std::make_unique<KeyEntry>(mIdGenerator.nextId(), currentTime, entry->deviceId,
1139 entry->source, entry->displayId, policyFlags, entry->action,
1140 entry->flags, entry->keyCode, entry->scanCode,
1141 entry->metaState, entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001142
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001143 newEntry->syntheticRepeat = true;
1144 mKeyRepeatState.lastKeyEntry = newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001145 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001146 return newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001147}
1148
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001149bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001150 const ConfigurationChangedEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001151#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001152 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry.eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001153#endif
1154
1155 // Reset key repeating in case a keyboard device was added or removed or something.
1156 resetKeyRepeatLocked();
1157
1158 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001159 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
1160 &InputDispatcher::doNotifyConfigurationChangedLockedInterruptible);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001161 commandEntry->eventTime = entry.eventTime;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001162 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001163 return true;
1164}
1165
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001166bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime,
1167 const DeviceResetEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001168#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001169 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry.eventTime,
1170 entry.deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001171#endif
1172
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001173 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, "device was reset");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001174 options.deviceId = entry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001175 synthesizeCancelationEventsForAllConnectionsLocked(options);
1176 return true;
1177}
1178
Vishnu Nairad321cd2020-08-20 16:40:21 -07001179void InputDispatcher::enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus,
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001180 std::string_view reason) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001181 if (mPendingEvent != nullptr) {
1182 // Move the pending event to the front of the queue. This will give the chance
1183 // for the pending event to get dispatched to the newly focused window
1184 mInboundQueue.push_front(mPendingEvent);
1185 mPendingEvent = nullptr;
1186 }
1187
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001188 std::unique_ptr<FocusEntry> focusEntry =
1189 std::make_unique<FocusEntry>(mIdGenerator.nextId(), now(), windowToken, hasFocus,
1190 reason);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001191
1192 // This event should go to the front of the queue, but behind all other focus events
1193 // Find the last focus event, and insert right after it
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001194 std::deque<std::shared_ptr<EventEntry>>::reverse_iterator it =
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001195 std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001196 [](const std::shared_ptr<EventEntry>& event) {
1197 return event->type == EventEntry::Type::FOCUS;
1198 });
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001199
1200 // Maintain the order of focus events. Insert the entry after all other focus events.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001201 mInboundQueue.insert(it.base(), std::move(focusEntry));
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001202}
1203
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001204void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime, std::shared_ptr<FocusEntry> entry) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05001205 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001206 if (channel == nullptr) {
1207 return; // Window has gone away
1208 }
1209 InputTarget target;
1210 target.inputChannel = channel;
1211 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1212 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001213 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
1214 channel->getName();
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001215 std::string reason = std::string("reason=").append(entry->reason);
1216 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001217 dispatchEventLocked(currentTime, entry, {target});
1218}
1219
Prabir Pradhan99987712020-11-10 18:43:05 -08001220void InputDispatcher::dispatchPointerCaptureChangedLocked(
1221 nsecs_t currentTime, const std::shared_ptr<PointerCaptureChangedEntry>& entry,
1222 DropReason& dropReason) {
1223 const bool haveWindowWithPointerCapture = mWindowTokenWithPointerCapture != nullptr;
1224 if (entry->pointerCaptureEnabled == haveWindowWithPointerCapture) {
1225 LOG_ALWAYS_FATAL_IF(mFocusedWindowRequestedPointerCapture,
1226 "The Pointer Capture state has already been dispatched to the window.");
1227 // Pointer capture was already forcefully disabled because of focus change.
1228 dropReason = DropReason::NOT_DROPPED;
1229 return;
1230 }
1231
1232 // Set drop reason for early returns
1233 dropReason = DropReason::NO_POINTER_CAPTURE;
1234
1235 sp<IBinder> token;
1236 if (entry->pointerCaptureEnabled) {
1237 // Enable Pointer Capture
1238 if (!mFocusedWindowRequestedPointerCapture) {
1239 // This can happen if a window requests capture and immediately releases capture.
1240 ALOGW("No window requested Pointer Capture.");
1241 return;
1242 }
1243 token = getValueByKey(mFocusedWindowTokenByDisplay, mFocusedDisplayId);
1244 LOG_ALWAYS_FATAL_IF(!token, "Cannot find focused window for Pointer Capture.");
1245 mWindowTokenWithPointerCapture = token;
1246 } else {
1247 // Disable Pointer Capture
1248 token = mWindowTokenWithPointerCapture;
1249 mWindowTokenWithPointerCapture = nullptr;
1250 mFocusedWindowRequestedPointerCapture = false;
1251 }
1252
1253 auto channel = getInputChannelLocked(token);
1254 if (channel == nullptr) {
1255 // Window has gone away, clean up Pointer Capture state.
1256 mWindowTokenWithPointerCapture = nullptr;
1257 mFocusedWindowRequestedPointerCapture = false;
1258 return;
1259 }
1260 InputTarget target;
1261 target.inputChannel = channel;
1262 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1263 entry->dispatchInProgress = true;
1264 dispatchEventLocked(currentTime, entry, {target});
1265
1266 dropReason = DropReason::NOT_DROPPED;
1267}
1268
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001269bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, std::shared_ptr<KeyEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001270 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001271 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001272 if (!entry->dispatchInProgress) {
1273 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1274 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1275 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1276 if (mKeyRepeatState.lastKeyEntry &&
Chris Ye2ad95392020-09-01 13:44:44 -07001277 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode &&
Michael Wrightd02c5b62014-02-10 15:10:22 -08001278 // We have seen two identical key downs in a row which indicates that the device
1279 // driver is automatically generating key repeats itself. We take note of the
1280 // repeat here, but we disable our own next key repeat timer since it is clear that
1281 // we will not need to synthesize key repeats ourselves.
Chris Ye2ad95392020-09-01 13:44:44 -07001282 mKeyRepeatState.lastKeyEntry->deviceId == entry->deviceId) {
1283 // Make sure we don't get key down from a different device. If a different
1284 // device Id has same key pressed down, the new device Id will replace the
1285 // current one to hold the key repeat with repeat count reset.
1286 // In the future when got a KEY_UP on the device id, drop it and do not
1287 // stop the key repeat on current device.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001288 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1289 resetKeyRepeatLocked();
1290 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
1291 } else {
1292 // Not a repeat. Save key down state in case we do see a repeat later.
1293 resetKeyRepeatLocked();
1294 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1295 }
1296 mKeyRepeatState.lastKeyEntry = entry;
Chris Ye2ad95392020-09-01 13:44:44 -07001297 } else if (entry->action == AKEY_EVENT_ACTION_UP && mKeyRepeatState.lastKeyEntry &&
1298 mKeyRepeatState.lastKeyEntry->deviceId != entry->deviceId) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001299 // The key on device 'deviceId' is still down, do not stop key repeat
Chris Ye2ad95392020-09-01 13:44:44 -07001300#if DEBUG_INBOUND_EVENT_DETAILS
1301 ALOGD("deviceId=%d got KEY_UP as stale", entry->deviceId);
1302#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001303 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001304 resetKeyRepeatLocked();
1305 }
1306
1307 if (entry->repeatCount == 1) {
1308 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1309 } else {
1310 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1311 }
1312
1313 entry->dispatchInProgress = true;
1314
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001315 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001316 }
1317
1318 // Handle case where the policy asked us to try again later last time.
1319 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
1320 if (currentTime < entry->interceptKeyWakeupTime) {
1321 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1322 *nextWakeupTime = entry->interceptKeyWakeupTime;
1323 }
1324 return false; // wait until next wakeup
1325 }
1326 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
1327 entry->interceptKeyWakeupTime = 0;
1328 }
1329
1330 // Give the policy a chance to intercept the key.
1331 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
1332 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001333 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
Siarhei Vishniakou49a350a2019-07-26 18:44:23 -07001334 &InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible);
Vishnu Nairad321cd2020-08-20 16:40:21 -07001335 sp<IBinder> focusedWindowToken =
1336 getValueByKey(mFocusedWindowTokenByDisplay, getTargetDisplayId(*entry));
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06001337 commandEntry->connectionToken = focusedWindowToken;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001338 commandEntry->keyEntry = entry;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001339 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001340 return false; // wait for the command to run
1341 } else {
1342 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
1343 }
1344 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001345 if (*dropReason == DropReason::NOT_DROPPED) {
1346 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001347 }
1348 }
1349
1350 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001351 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001352 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001353 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1354 : InputEventInjectionResult::FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001355 mReporter->reportDroppedKey(entry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001356 return true;
1357 }
1358
1359 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001360 std::vector<InputTarget> inputTargets;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001361 InputEventInjectionResult injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001362 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001363 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001364 return false;
1365 }
1366
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001367 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001368 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001369 return true;
1370 }
1371
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001372 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001373 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001374
1375 // Dispatch the key.
1376 dispatchEventLocked(currentTime, entry, inputTargets);
1377 return true;
1378}
1379
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001380void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001381#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01001382 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001383 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1384 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001385 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1386 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
1387 entry.repeatCount, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001388#endif
1389}
1390
Chris Yef59a2f42020-10-16 12:55:26 -07001391void InputDispatcher::doNotifySensorLockedInterruptible(CommandEntry* commandEntry) {
1392 mLock.unlock();
1393
1394 const std::shared_ptr<SensorEntry>& entry = commandEntry->sensorEntry;
1395 if (entry->accuracyChanged) {
1396 mPolicy->notifySensorAccuracy(entry->deviceId, entry->sensorType, entry->accuracy);
1397 }
1398 mPolicy->notifySensorEvent(entry->deviceId, entry->sensorType, entry->accuracy,
1399 entry->hwTimestamp, entry->values);
1400 mLock.lock();
1401}
1402
1403void InputDispatcher::dispatchSensorLocked(nsecs_t currentTime, std::shared_ptr<SensorEntry> entry,
1404 DropReason* dropReason, nsecs_t* nextWakeupTime) {
1405#if DEBUG_OUTBOUND_EVENT_DETAILS
1406 ALOGD("notifySensorEvent eventTime=%" PRId64 ", hwTimestamp=%" PRId64 ", deviceId=%d, "
1407 "source=0x%x, sensorType=%s",
1408 entry->eventTime, entry->hwTimestamp, entry->deviceId, entry->source,
1409 NamedEnum::string(sensorType).c_str());
1410#endif
1411 std::unique_ptr<CommandEntry> commandEntry =
1412 std::make_unique<CommandEntry>(&InputDispatcher::doNotifySensorLockedInterruptible);
1413 commandEntry->sensorEntry = entry;
1414 postCommandLocked(std::move(commandEntry));
1415}
1416
1417bool InputDispatcher::flushSensor(int deviceId, InputDeviceSensorType sensorType) {
1418#if DEBUG_OUTBOUND_EVENT_DETAILS
1419 ALOGD("flushSensor deviceId=%d, sensorType=%s", deviceId,
1420 NamedEnum::string(sensorType).c_str());
1421#endif
1422 { // acquire lock
1423 std::scoped_lock _l(mLock);
1424
1425 for (auto it = mInboundQueue.begin(); it != mInboundQueue.end(); it++) {
1426 std::shared_ptr<EventEntry> entry = *it;
1427 if (entry->type == EventEntry::Type::SENSOR) {
1428 it = mInboundQueue.erase(it);
1429 releaseInboundEventLocked(entry);
1430 }
1431 }
1432 }
1433 return true;
1434}
1435
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001436bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, std::shared_ptr<MotionEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001437 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001438 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001439 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001440 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001441 entry->dispatchInProgress = true;
1442
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001443 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001444 }
1445
1446 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001447 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001448 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001449 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1450 : InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001451 return true;
1452 }
1453
1454 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
1455
1456 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001457 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001458
1459 bool conflictingPointerActions = false;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001460 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001461 if (isPointerEvent) {
1462 // Pointer event. (eg. touchscreen)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001463 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001464 findTouchedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001465 &conflictingPointerActions);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001466 } else {
1467 // Non touch event. (eg. trackball)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001468 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001469 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001470 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001471 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001472 return false;
1473 }
1474
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001475 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001476 if (injectionResult == InputEventInjectionResult::PERMISSION_DENIED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001477 ALOGW("Permission denied, dropping the motion (isPointer=%s)", toString(isPointerEvent));
1478 return true;
1479 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001480 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001481 CancelationOptions::Mode mode(isPointerEvent
1482 ? CancelationOptions::CANCEL_POINTER_EVENTS
1483 : CancelationOptions::CANCEL_NON_POINTER_EVENTS);
1484 CancelationOptions options(mode, "input event injection failed");
1485 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001486 return true;
1487 }
1488
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001489 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001490 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001491
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001492 if (isPointerEvent) {
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07001493 std::unordered_map<int32_t, TouchState>::iterator it =
1494 mTouchStatesByDisplay.find(entry->displayId);
1495 if (it != mTouchStatesByDisplay.end()) {
1496 const TouchState& state = it->second;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001497 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001498 // The event has gone through these portal windows, so we add monitoring targets of
1499 // the corresponding displays as well.
1500 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001501 const InputWindowInfo* windowInfo = state.portalWindows[i]->getInfo();
Michael Wright3dd60e22019-03-27 22:06:44 +00001502 addGlobalMonitoringTargetsLocked(inputTargets, windowInfo->portalToDisplayId,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001503 -windowInfo->frameLeft, -windowInfo->frameTop);
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001504 }
1505 }
1506 }
1507 }
1508
Michael Wrightd02c5b62014-02-10 15:10:22 -08001509 // Dispatch the motion.
1510 if (conflictingPointerActions) {
1511 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001512 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001513 synthesizeCancelationEventsForAllConnectionsLocked(options);
1514 }
1515 dispatchEventLocked(currentTime, entry, inputTargets);
1516 return true;
1517}
1518
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001519void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001520#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08001521 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001522 ", policyFlags=0x%x, "
1523 "action=0x%x, actionButton=0x%x, flags=0x%x, "
1524 "metaState=0x%x, buttonState=0x%x,"
1525 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001526 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1527 entry.action, entry.actionButton, entry.flags, entry.metaState, entry.buttonState,
1528 entry.edgeFlags, entry.xPrecision, entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001529
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001530 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001531 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001532 "x=%f, y=%f, pressure=%f, size=%f, "
1533 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1534 "orientation=%f",
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001535 i, entry.pointerProperties[i].id, entry.pointerProperties[i].toolType,
1536 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1537 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1538 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1539 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1540 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1541 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1542 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1543 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1544 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001545 }
1546#endif
1547}
1548
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001549void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
1550 std::shared_ptr<EventEntry> eventEntry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001551 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001552 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001553#if DEBUG_DISPATCH_CYCLE
1554 ALOGD("dispatchEventToCurrentInputTargets");
1555#endif
1556
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001557 updateInteractionTokensLocked(*eventEntry, inputTargets);
1558
Michael Wrightd02c5b62014-02-10 15:10:22 -08001559 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1560
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001561 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001562
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001563 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001564 sp<Connection> connection =
1565 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001566 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08001567 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001568 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001569 if (DEBUG_FOCUS) {
1570 ALOGD("Dropping event delivery to target with channel '%s' because it "
1571 "is no longer registered with the input dispatcher.",
1572 inputTarget.inputChannel->getName().c_str());
1573 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001574 }
1575 }
1576}
1577
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001578void InputDispatcher::cancelEventsForAnrLocked(const sp<Connection>& connection) {
1579 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
1580 // If the policy decides to close the app, we will get a channel removal event via
1581 // unregisterInputChannel, and will clean up the connection that way. We are already not
1582 // sending new pointers to the connection when it blocked, but focused events will continue to
1583 // pile up.
1584 ALOGW("Canceling events for %s because it is unresponsive",
1585 connection->inputChannel->getName().c_str());
1586 if (connection->status == Connection::STATUS_NORMAL) {
1587 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1588 "application not responding");
1589 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001590 }
1591}
1592
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001593void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001594 if (DEBUG_FOCUS) {
1595 ALOGD("Resetting ANR timeouts.");
1596 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001597
1598 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001599 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07001600 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001601}
1602
Tiger Huang721e26f2018-07-24 22:26:19 +08001603/**
1604 * Get the display id that the given event should go to. If this event specifies a valid display id,
1605 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1606 * Focused display is the display that the user most recently interacted with.
1607 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001608int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001609 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001610 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001611 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001612 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1613 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001614 break;
1615 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001616 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001617 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1618 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001619 break;
1620 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001621 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001622 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001623 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07001624 case EventEntry::Type::DEVICE_RESET:
1625 case EventEntry::Type::SENSOR: {
1626 ALOGE("%s events do not have a target display", NamedEnum::string(entry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001627 return ADISPLAY_ID_NONE;
1628 }
Tiger Huang721e26f2018-07-24 22:26:19 +08001629 }
1630 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1631}
1632
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001633bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
1634 const char* focusedWindowName) {
1635 if (mAnrTracker.empty()) {
1636 // already processed all events that we waited for
1637 mKeyIsWaitingForEventsTimeout = std::nullopt;
1638 return false;
1639 }
1640
1641 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
1642 // Start the timer
1643 ALOGD("Waiting to send key to %s because there are unprocessed events that may cause "
1644 "focus to change",
1645 focusedWindowName);
Siarhei Vishniakou70622952020-07-30 11:17:23 -05001646 mKeyIsWaitingForEventsTimeout = currentTime +
1647 std::chrono::duration_cast<std::chrono::nanoseconds>(KEY_WAITING_FOR_EVENTS_TIMEOUT)
1648 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001649 return true;
1650 }
1651
1652 // We still have pending events, and already started the timer
1653 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
1654 return true; // Still waiting
1655 }
1656
1657 // Waited too long, and some connection still hasn't processed all motions
1658 // Just send the key to the focused window
1659 ALOGW("Dispatching key to %s even though there are other unprocessed events",
1660 focusedWindowName);
1661 mKeyIsWaitingForEventsTimeout = std::nullopt;
1662 return false;
1663}
1664
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001665InputEventInjectionResult InputDispatcher::findFocusedWindowTargetsLocked(
1666 nsecs_t currentTime, const EventEntry& entry, std::vector<InputTarget>& inputTargets,
1667 nsecs_t* nextWakeupTime) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001668 std::string reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001669
Tiger Huang721e26f2018-07-24 22:26:19 +08001670 int32_t displayId = getTargetDisplayId(entry);
Vishnu Nairad321cd2020-08-20 16:40:21 -07001671 sp<InputWindowHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07001672 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08001673 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1674
Michael Wrightd02c5b62014-02-10 15:10:22 -08001675 // If there is no currently focused window and no focused application
1676 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001677 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
1678 ALOGI("Dropping %s event because there is no focused window or focused application in "
1679 "display %" PRId32 ".",
Chris Yef59a2f42020-10-16 12:55:26 -07001680 NamedEnum::string(entry.type).c_str(), displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001681 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001682 }
1683
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001684 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
1685 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
1686 // start interacting with another application via touch (app switch). This code can be removed
1687 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
1688 // an app is expected to have a focused window.
1689 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
1690 if (!mNoFocusedWindowTimeoutTime.has_value()) {
1691 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001692 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
1693 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
1694 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001695 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05001696 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001697 ALOGW("Waiting because no window has focus but %s may eventually add a "
1698 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001699 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001700 *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001701 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001702 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
1703 // Already raised ANR. Drop the event
1704 ALOGE("Dropping %s event because there is no focused window",
Chris Yef59a2f42020-10-16 12:55:26 -07001705 NamedEnum::string(entry.type).c_str());
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001706 return InputEventInjectionResult::FAILED;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001707 } else {
1708 // Still waiting for the focused window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001709 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001710 }
1711 }
1712
1713 // we have a valid, non-null focused window
1714 resetNoFocusedWindowTimeoutLocked();
1715
Michael Wrightd02c5b62014-02-10 15:10:22 -08001716 // Check permissions.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001717 if (!checkInjectionPermission(focusedWindowHandle, entry.injectionState)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001718 return InputEventInjectionResult::PERMISSION_DENIED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001719 }
1720
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001721 if (focusedWindowHandle->getInfo()->paused) {
1722 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001723 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001724 }
1725
1726 // If the event is a key event, then we must wait for all previous events to
1727 // complete before delivering it because previous events may have the
1728 // side-effect of transferring focus to a different window and we want to
1729 // ensure that the following keys are sent to the new window.
1730 //
1731 // Suppose the user touches a button in a window then immediately presses "A".
1732 // If the button causes a pop-up window to appear then we want to ensure that
1733 // the "A" key is delivered to the new pop-up window. This is because users
1734 // often anticipate pending UI changes when typing on a keyboard.
1735 // To obtain this behavior, we must serialize key events with respect to all
1736 // prior input events.
1737 if (entry.type == EventEntry::Type::KEY) {
1738 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
1739 *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001740 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001741 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001742 }
1743
1744 // Success! Output targets.
Tiger Huang721e26f2018-07-24 22:26:19 +08001745 addWindowTargetLocked(focusedWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001746 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS,
1747 BitSet32(0), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001748
1749 // Done.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001750 return InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001751}
1752
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001753/**
1754 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
1755 * that are currently unresponsive.
1756 */
1757std::vector<TouchedMonitor> InputDispatcher::selectResponsiveMonitorsLocked(
1758 const std::vector<TouchedMonitor>& monitors) const {
1759 std::vector<TouchedMonitor> responsiveMonitors;
1760 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
1761 [this](const TouchedMonitor& monitor) REQUIRES(mLock) {
1762 sp<Connection> connection = getConnectionLocked(
1763 monitor.monitor.inputChannel->getConnectionToken());
1764 if (connection == nullptr) {
1765 ALOGE("Could not find connection for monitor %s",
1766 monitor.monitor.inputChannel->getName().c_str());
1767 return false;
1768 }
1769 if (!connection->responsive) {
1770 ALOGW("Unresponsive monitor %s will not get the new gesture",
1771 connection->inputChannel->getName().c_str());
1772 return false;
1773 }
1774 return true;
1775 });
1776 return responsiveMonitors;
1777}
1778
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001779InputEventInjectionResult InputDispatcher::findTouchedWindowTargetsLocked(
1780 nsecs_t currentTime, const MotionEntry& entry, std::vector<InputTarget>& inputTargets,
1781 nsecs_t* nextWakeupTime, bool* outConflictingPointerActions) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001782 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001783 enum InjectionPermission {
1784 INJECTION_PERMISSION_UNKNOWN,
1785 INJECTION_PERMISSION_GRANTED,
1786 INJECTION_PERMISSION_DENIED
1787 };
1788
Michael Wrightd02c5b62014-02-10 15:10:22 -08001789 // For security reasons, we defer updating the touch state until we are sure that
1790 // event injection will be allowed.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001791 int32_t displayId = entry.displayId;
1792 int32_t action = entry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001793 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
1794
1795 // Update the touch state as needed based on the properties of the touch event.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001796 InputEventInjectionResult injectionResult = InputEventInjectionResult::PENDING;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001797 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
Garfield Tandf26e862020-07-01 20:18:19 -07001798 sp<InputWindowHandle> newHoverWindowHandle(mLastHoverWindowHandle);
1799 sp<InputWindowHandle> newTouchedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001800
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001801 // Copy current touch state into tempTouchState.
1802 // This state will be used to update mTouchStatesByDisplay at the end of this function.
1803 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07001804 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001805 TouchState tempTouchState;
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07001806 std::unordered_map<int32_t, TouchState>::iterator oldStateIt =
1807 mTouchStatesByDisplay.find(displayId);
1808 if (oldStateIt != mTouchStatesByDisplay.end()) {
1809 oldState = &(oldStateIt->second);
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001810 tempTouchState.copyFrom(*oldState);
Jeff Brownf086ddb2014-02-11 14:28:48 -08001811 }
1812
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001813 bool isSplit = tempTouchState.split;
1814 bool switchedDevice = tempTouchState.deviceId >= 0 && tempTouchState.displayId >= 0 &&
1815 (tempTouchState.deviceId != entry.deviceId || tempTouchState.source != entry.source ||
1816 tempTouchState.displayId != displayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001817 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
1818 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
1819 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
1820 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN ||
1821 maskedAction == AMOTION_EVENT_ACTION_SCROLL || isHoverAction);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001822 const bool isFromMouse = entry.source == AINPUT_SOURCE_MOUSE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001823 bool wrongDevice = false;
1824 if (newGesture) {
1825 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001826 if (switchedDevice && tempTouchState.down && !down && !isHoverAction) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001827 ALOGI("Dropping event because a pointer for a different device is already down "
1828 "in display %" PRId32,
1829 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001830 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001831 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001832 switchedDevice = false;
1833 wrongDevice = true;
1834 goto Failed;
1835 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001836 tempTouchState.reset();
1837 tempTouchState.down = down;
1838 tempTouchState.deviceId = entry.deviceId;
1839 tempTouchState.source = entry.source;
1840 tempTouchState.displayId = displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001841 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001842 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001843 ALOGI("Dropping move event because a pointer for a different device is already active "
1844 "in display %" PRId32,
1845 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001846 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001847 injectionResult = InputEventInjectionResult::PERMISSION_DENIED;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001848 switchedDevice = false;
1849 wrongDevice = true;
1850 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001851 }
1852
1853 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
1854 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
1855
Garfield Tan00f511d2019-06-12 16:55:40 -07001856 int32_t x;
1857 int32_t y;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001858 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Garfield Tan00f511d2019-06-12 16:55:40 -07001859 // Always dispatch mouse events to cursor position.
1860 if (isFromMouse) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001861 x = int32_t(entry.xCursorPosition);
1862 y = int32_t(entry.yCursorPosition);
Garfield Tan00f511d2019-06-12 16:55:40 -07001863 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001864 x = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X));
1865 y = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y));
Garfield Tan00f511d2019-06-12 16:55:40 -07001866 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001867 bool isDown = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Garfield Tandf26e862020-07-01 20:18:19 -07001868 newTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001869 findTouchedWindowAtLocked(displayId, x, y, &tempTouchState,
1870 isDown /*addOutsideTargets*/, true /*addPortalWindows*/);
Michael Wright3dd60e22019-03-27 22:06:44 +00001871
1872 std::vector<TouchedMonitor> newGestureMonitors = isDown
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001873 ? findTouchedGestureMonitorsLocked(displayId, tempTouchState.portalWindows)
Michael Wright3dd60e22019-03-27 22:06:44 +00001874 : std::vector<TouchedMonitor>{};
Michael Wrightd02c5b62014-02-10 15:10:22 -08001875
Michael Wrightd02c5b62014-02-10 15:10:22 -08001876 // Figure out whether splitting will be allowed for this window.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001877 if (newTouchedWindowHandle != nullptr &&
1878 newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Garfield Tanaddb02b2019-06-25 16:36:13 -07001879 // New window supports splitting, but we should never split mouse events.
1880 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001881 } else if (isSplit) {
1882 // New window does not support splitting but we have already split events.
1883 // Ignore the new window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001884 newTouchedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001885 }
1886
1887 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001888 if (newTouchedWindowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001889 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001890 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001891 }
1892
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001893 if (newTouchedWindowHandle != nullptr && newTouchedWindowHandle->getInfo()->paused) {
1894 ALOGI("Not sending touch event to %s because it is paused",
1895 newTouchedWindowHandle->getName().c_str());
1896 newTouchedWindowHandle = nullptr;
1897 }
1898
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001899 // Ensure the window has a connection and the connection is responsive
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001900 if (newTouchedWindowHandle != nullptr) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001901 const bool isResponsive = hasResponsiveConnectionLocked(*newTouchedWindowHandle);
1902 if (!isResponsive) {
1903 ALOGW("%s will not receive the new gesture at %" PRIu64,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001904 newTouchedWindowHandle->getName().c_str(), entry.eventTime);
1905 newTouchedWindowHandle = nullptr;
1906 }
1907 }
1908
Bernardo Rufinoea97d182020-08-19 14:43:14 +01001909 // Drop events that can't be trusted due to occlusion
1910 if (newTouchedWindowHandle != nullptr &&
1911 mBlockUntrustedTouchesMode != BlockUntrustedTouchesMode::DISABLED) {
1912 TouchOcclusionInfo occlusionInfo =
1913 computeTouchOcclusionInfoLocked(newTouchedWindowHandle, x, y);
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00001914 if (!isTouchTrustedLocked(occlusionInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00001915 if (DEBUG_TOUCH_OCCLUSION) {
1916 ALOGD("Stack of obscuring windows during untrusted touch (%d, %d):", x, y);
1917 for (const auto& log : occlusionInfo.debugInfo) {
1918 ALOGD("%s", log.c_str());
1919 }
1920 }
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00001921 onUntrustedTouchLocked(occlusionInfo.obscuringPackage);
1922 if (mBlockUntrustedTouchesMode == BlockUntrustedTouchesMode::BLOCK) {
1923 ALOGW("Dropping untrusted touch event due to %s/%d",
1924 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid);
1925 newTouchedWindowHandle = nullptr;
1926 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01001927 }
1928 }
1929
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001930 // Also don't send the new touch event to unresponsive gesture monitors
1931 newGestureMonitors = selectResponsiveMonitorsLocked(newGestureMonitors);
1932
Michael Wright3dd60e22019-03-27 22:06:44 +00001933 if (newTouchedWindowHandle == nullptr && newGestureMonitors.empty()) {
1934 ALOGI("Dropping event because there is no touchable window or gesture monitor at "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001935 "(%d, %d) in display %" PRId32 ".",
1936 x, y, displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001937 injectionResult = InputEventInjectionResult::FAILED;
Michael Wright3dd60e22019-03-27 22:06:44 +00001938 goto Failed;
1939 }
1940
1941 if (newTouchedWindowHandle != nullptr) {
1942 // Set target flags.
1943 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
1944 if (isSplit) {
1945 targetFlags |= InputTarget::FLAG_SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001946 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001947 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1948 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1949 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
1950 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1951 }
1952
1953 // Update hover state.
Garfield Tandf26e862020-07-01 20:18:19 -07001954 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
1955 newHoverWindowHandle = nullptr;
1956 } else if (isHoverAction) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001957 newHoverWindowHandle = newTouchedWindowHandle;
Michael Wright3dd60e22019-03-27 22:06:44 +00001958 }
1959
1960 // Update the temporary touch state.
1961 BitSet32 pointerIds;
1962 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001963 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wright3dd60e22019-03-27 22:06:44 +00001964 pointerIds.markBit(pointerId);
1965 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001966 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001967 }
1968
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001969 tempTouchState.addGestureMonitors(newGestureMonitors);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001970 } else {
1971 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
1972
1973 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001974 if (!tempTouchState.down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001975 if (DEBUG_FOCUS) {
1976 ALOGD("Dropping event because the pointer is not down or we previously "
1977 "dropped the pointer down event in display %" PRId32,
1978 displayId);
1979 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001980 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001981 goto Failed;
1982 }
1983
1984 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001985 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001986 tempTouchState.isSlippery()) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001987 int32_t x = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
1988 int32_t y = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001989
1990 sp<InputWindowHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001991 tempTouchState.getFirstForegroundWindowHandle();
Garfield Tandf26e862020-07-01 20:18:19 -07001992 newTouchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y, &tempTouchState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001993 if (oldTouchedWindowHandle != newTouchedWindowHandle &&
1994 oldTouchedWindowHandle != nullptr && newTouchedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001995 if (DEBUG_FOCUS) {
1996 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
1997 oldTouchedWindowHandle->getName().c_str(),
1998 newTouchedWindowHandle->getName().c_str(), displayId);
1999 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002000 // Make a slippery exit from the old window.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002001 tempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
2002 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT,
2003 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002004
2005 // Make a slippery entrance into the new window.
2006 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
2007 isSplit = true;
2008 }
2009
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002010 int32_t targetFlags =
2011 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002012 if (isSplit) {
2013 targetFlags |= InputTarget::FLAG_SPLIT;
2014 }
2015 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
2016 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
2017 }
2018
2019 BitSet32 pointerIds;
2020 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002021 pointerIds.markBit(entry.pointerProperties[0].id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002022 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002023 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002024 }
2025 }
2026 }
2027
2028 if (newHoverWindowHandle != mLastHoverWindowHandle) {
Garfield Tandf26e862020-07-01 20:18:19 -07002029 // Let the previous window know that the hover sequence is over, unless we already did it
2030 // when dispatching it as is to newTouchedWindowHandle.
2031 if (mLastHoverWindowHandle != nullptr &&
2032 (maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT ||
2033 mLastHoverWindowHandle != newTouchedWindowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002034#if DEBUG_HOVER
2035 ALOGD("Sending hover exit event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002036 mLastHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002037#endif
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002038 tempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
2039 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002040 }
2041
Garfield Tandf26e862020-07-01 20:18:19 -07002042 // Let the new window know that the hover sequence is starting, unless we already did it
2043 // when dispatching it as is to newTouchedWindowHandle.
2044 if (newHoverWindowHandle != nullptr &&
2045 (maskedAction != AMOTION_EVENT_ACTION_HOVER_ENTER ||
2046 newHoverWindowHandle != newTouchedWindowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002047#if DEBUG_HOVER
2048 ALOGD("Sending hover enter event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002049 newHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002050#endif
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002051 tempTouchState.addOrUpdateWindow(newHoverWindowHandle,
2052 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER,
2053 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002054 }
2055 }
2056
2057 // Check permission to inject into all touched foreground windows and ensure there
2058 // is at least one touched foreground window.
2059 {
2060 bool haveForegroundWindow = false;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002061 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002062 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
2063 haveForegroundWindow = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002064 if (!checkInjectionPermission(touchedWindow.windowHandle, entry.injectionState)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002065 injectionResult = InputEventInjectionResult::PERMISSION_DENIED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002066 injectionPermission = INJECTION_PERMISSION_DENIED;
2067 goto Failed;
2068 }
2069 }
2070 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002071 bool hasGestureMonitor = !tempTouchState.gestureMonitors.empty();
Michael Wright3dd60e22019-03-27 22:06:44 +00002072 if (!haveForegroundWindow && !hasGestureMonitor) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002073 ALOGI("Dropping event because there is no touched foreground window in display "
2074 "%" PRId32 " or gesture monitor to receive it.",
2075 displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002076 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002077 goto Failed;
2078 }
2079
2080 // Permission granted to injection into all touched foreground windows.
2081 injectionPermission = INJECTION_PERMISSION_GRANTED;
2082 }
2083
2084 // Check whether windows listening for outside touches are owned by the same UID. If it is
2085 // set the policy flag that we will not reveal coordinate information to this window.
2086 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2087 sp<InputWindowHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002088 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002089 if (foregroundWindowHandle) {
2090 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002091 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002092 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2093 sp<InputWindowHandle> inputWindowHandle = touchedWindow.windowHandle;
2094 if (inputWindowHandle->getInfo()->ownerUid != foregroundWindowUid) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002095 tempTouchState.addOrUpdateWindow(inputWindowHandle,
2096 InputTarget::FLAG_ZERO_COORDS,
2097 BitSet32(0));
Michael Wright3dd60e22019-03-27 22:06:44 +00002098 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002099 }
2100 }
2101 }
2102 }
2103
Michael Wrightd02c5b62014-02-10 15:10:22 -08002104 // If this is the first pointer going down and the touched window has a wallpaper
2105 // then also add the touched wallpaper windows so they are locked in for the duration
2106 // of the touch gesture.
2107 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
2108 // engine only supports touch events. We would need to add a mechanism similar
2109 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
2110 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2111 sp<InputWindowHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002112 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002113 if (foregroundWindowHandle && foregroundWindowHandle->getInfo()->hasWallpaper) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07002114 const std::vector<sp<InputWindowHandle>>& windowHandles =
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002115 getWindowHandlesLocked(displayId);
2116 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002117 const InputWindowInfo* info = windowHandle->getInfo();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002118 if (info->displayId == displayId &&
Michael Wright44753b12020-07-08 13:48:11 +01002119 windowHandle->getInfo()->type == InputWindowInfo::Type::WALLPAPER) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002120 tempTouchState
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002121 .addOrUpdateWindow(windowHandle,
2122 InputTarget::FLAG_WINDOW_IS_OBSCURED |
2123 InputTarget::
2124 FLAG_WINDOW_IS_PARTIALLY_OBSCURED |
2125 InputTarget::FLAG_DISPATCH_AS_IS,
2126 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002127 }
2128 }
2129 }
2130 }
2131
2132 // Success! Output targets.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002133 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002134
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002135 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002136 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002137 touchedWindow.pointerIds, inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002138 }
2139
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002140 for (const TouchedMonitor& touchedMonitor : tempTouchState.gestureMonitors) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002141 addMonitoringTargetLocked(touchedMonitor.monitor, touchedMonitor.xOffset,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002142 touchedMonitor.yOffset, inputTargets);
Michael Wright3dd60e22019-03-27 22:06:44 +00002143 }
2144
Michael Wrightd02c5b62014-02-10 15:10:22 -08002145 // Drop the outside or hover touch windows since we will not care about them
2146 // in the next iteration.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002147 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002148
2149Failed:
2150 // Check injection permission once and for all.
2151 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002152 if (checkInjectionPermission(nullptr, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002153 injectionPermission = INJECTION_PERMISSION_GRANTED;
2154 } else {
2155 injectionPermission = INJECTION_PERMISSION_DENIED;
2156 }
2157 }
2158
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002159 if (injectionPermission != INJECTION_PERMISSION_GRANTED) {
2160 return injectionResult;
2161 }
2162
Michael Wrightd02c5b62014-02-10 15:10:22 -08002163 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002164 if (!wrongDevice) {
2165 if (switchedDevice) {
2166 if (DEBUG_FOCUS) {
2167 ALOGD("Conflicting pointer actions: Switched to a different device.");
2168 }
2169 *outConflictingPointerActions = true;
2170 }
2171
2172 if (isHoverAction) {
2173 // Started hovering, therefore no longer down.
2174 if (oldState && oldState->down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002175 if (DEBUG_FOCUS) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002176 ALOGD("Conflicting pointer actions: Hover received while pointer was "
2177 "down.");
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002178 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002179 *outConflictingPointerActions = true;
2180 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002181 tempTouchState.reset();
2182 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2183 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
2184 tempTouchState.deviceId = entry.deviceId;
2185 tempTouchState.source = entry.source;
2186 tempTouchState.displayId = displayId;
2187 }
2188 } else if (maskedAction == AMOTION_EVENT_ACTION_UP ||
2189 maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
2190 // All pointers up or canceled.
2191 tempTouchState.reset();
2192 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2193 // First pointer went down.
2194 if (oldState && oldState->down) {
2195 if (DEBUG_FOCUS) {
2196 ALOGD("Conflicting pointer actions: Down received while already down.");
2197 }
2198 *outConflictingPointerActions = true;
2199 }
2200 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2201 // One pointer went up.
2202 if (isSplit) {
2203 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2204 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002205
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002206 for (size_t i = 0; i < tempTouchState.windows.size();) {
2207 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2208 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
2209 touchedWindow.pointerIds.clearBit(pointerId);
2210 if (touchedWindow.pointerIds.isEmpty()) {
2211 tempTouchState.windows.erase(tempTouchState.windows.begin() + i);
2212 continue;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002213 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002214 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002215 i += 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002216 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002217 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002218 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002219
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002220 // Save changes unless the action was scroll in which case the temporary touch
2221 // state was only valid for this one action.
2222 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
2223 if (tempTouchState.displayId >= 0) {
2224 mTouchStatesByDisplay[displayId] = tempTouchState;
2225 } else {
2226 mTouchStatesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002227 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002228 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002229
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002230 // Update hover state.
2231 mLastHoverWindowHandle = newHoverWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002232 }
2233
Michael Wrightd02c5b62014-02-10 15:10:22 -08002234 return injectionResult;
2235}
2236
2237void InputDispatcher::addWindowTargetLocked(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002238 int32_t targetFlags, BitSet32 pointerIds,
2239 std::vector<InputTarget>& inputTargets) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002240 std::vector<InputTarget>::iterator it =
2241 std::find_if(inputTargets.begin(), inputTargets.end(),
2242 [&windowHandle](const InputTarget& inputTarget) {
2243 return inputTarget.inputChannel->getConnectionToken() ==
2244 windowHandle->getToken();
2245 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002246
Chavi Weingarten114b77f2020-01-15 22:35:10 +00002247 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002248
2249 if (it == inputTargets.end()) {
2250 InputTarget inputTarget;
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05002251 std::shared_ptr<InputChannel> inputChannel =
2252 getInputChannelLocked(windowHandle->getToken());
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002253 if (inputChannel == nullptr) {
2254 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
2255 return;
2256 }
2257 inputTarget.inputChannel = inputChannel;
2258 inputTarget.flags = targetFlags;
2259 inputTarget.globalScaleFactor = windowInfo->globalScaleFactor;
2260 inputTargets.push_back(inputTarget);
2261 it = inputTargets.end() - 1;
2262 }
2263
2264 ALOG_ASSERT(it->flags == targetFlags);
2265 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
2266
chaviw1ff3d1e2020-07-01 15:53:47 -07002267 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002268}
2269
Michael Wright3dd60e22019-03-27 22:06:44 +00002270void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002271 int32_t displayId, float xOffset,
2272 float yOffset) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002273 std::unordered_map<int32_t, std::vector<Monitor>>::const_iterator it =
2274 mGlobalMonitorsByDisplay.find(displayId);
2275
2276 if (it != mGlobalMonitorsByDisplay.end()) {
2277 const std::vector<Monitor>& monitors = it->second;
2278 for (const Monitor& monitor : monitors) {
2279 addMonitoringTargetLocked(monitor, xOffset, yOffset, inputTargets);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002280 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002281 }
2282}
2283
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002284void InputDispatcher::addMonitoringTargetLocked(const Monitor& monitor, float xOffset,
2285 float yOffset,
2286 std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002287 InputTarget target;
2288 target.inputChannel = monitor.inputChannel;
2289 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
chaviw1ff3d1e2020-07-01 15:53:47 -07002290 ui::Transform t;
2291 t.set(xOffset, yOffset);
2292 target.setDefaultPointerTransform(t);
Michael Wright3dd60e22019-03-27 22:06:44 +00002293 inputTargets.push_back(target);
2294}
2295
Michael Wrightd02c5b62014-02-10 15:10:22 -08002296bool InputDispatcher::checkInjectionPermission(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002297 const InjectionState* injectionState) {
2298 if (injectionState &&
2299 (windowHandle == nullptr ||
2300 windowHandle->getInfo()->ownerUid != injectionState->injectorUid) &&
2301 !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002302 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002303 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002304 "owned by uid %d",
2305 injectionState->injectorPid, injectionState->injectorUid,
2306 windowHandle->getName().c_str(), windowHandle->getInfo()->ownerUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002307 } else {
2308 ALOGW("Permission denied: injecting event from pid %d uid %d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002309 injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002310 }
2311 return false;
2312 }
2313 return true;
2314}
2315
Robert Carrc9bf1d32020-04-13 17:21:08 -07002316/**
2317 * Indicate whether one window handle should be considered as obscuring
2318 * another window handle. We only check a few preconditions. Actually
2319 * checking the bounds is left to the caller.
2320 */
2321static bool canBeObscuredBy(const sp<InputWindowHandle>& windowHandle,
2322 const sp<InputWindowHandle>& otherHandle) {
2323 // Compare by token so cloned layers aren't counted
2324 if (haveSameToken(windowHandle, otherHandle)) {
2325 return false;
2326 }
2327 auto info = windowHandle->getInfo();
2328 auto otherInfo = otherHandle->getInfo();
2329 if (!otherInfo->visible) {
2330 return false;
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002331 } else if (otherInfo->alpha == 0 &&
2332 otherInfo->flags.test(InputWindowInfo::Flag::NOT_TOUCHABLE)) {
2333 // Those act as if they were invisible, so we don't need to flag them.
2334 // We do want to potentially flag touchable windows even if they have 0
2335 // opacity, since they can consume touches and alter the effects of the
2336 // user interaction (eg. apps that rely on
2337 // FLAG_WINDOW_IS_PARTIALLY_OBSCURED should still be told about those
2338 // windows), hence we also check for FLAG_NOT_TOUCHABLE.
2339 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00002340 } else if (info->ownerUid == otherInfo->ownerUid) {
2341 // If ownerUid is the same we don't generate occlusion events as there
2342 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002343 return false;
Chris Yefcdff3e2020-05-10 15:16:04 -07002344 } else if (otherInfo->trustedOverlay) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002345 return false;
2346 } else if (otherInfo->displayId != info->displayId) {
2347 return false;
2348 }
2349 return true;
2350}
2351
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002352/**
2353 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
2354 * untrusted, one should check:
2355 *
2356 * 1. If result.hasBlockingOcclusion is true.
2357 * If it's, it means the touch should be blocked due to a window with occlusion mode of
2358 * BLOCK_UNTRUSTED.
2359 *
2360 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
2361 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
2362 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
2363 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
2364 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
2365 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
2366 *
2367 * If neither of those is true, then it means the touch can be allowed.
2368 */
2369InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
2370 const sp<InputWindowHandle>& windowHandle, int32_t x, int32_t y) const {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002371 const InputWindowInfo* windowInfo = windowHandle->getInfo();
2372 int32_t displayId = windowInfo->displayId;
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002373 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2374 TouchOcclusionInfo info;
2375 info.hasBlockingOcclusion = false;
2376 info.obscuringOpacity = 0;
2377 info.obscuringUid = -1;
2378 std::map<int32_t, float> opacityByUid;
2379 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
2380 if (windowHandle == otherHandle) {
2381 break; // All future windows are below us. Exit early.
2382 }
2383 const InputWindowInfo* otherInfo = otherHandle->getInfo();
2384 if (canBeObscuredBy(windowHandle, otherHandle) &&
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002385 windowInfo->ownerUid != otherInfo->ownerUid && otherInfo->frameContainsPoint(x, y)) {
2386 if (DEBUG_TOUCH_OCCLUSION) {
2387 info.debugInfo.push_back(
2388 dumpWindowForTouchOcclusion(otherInfo, /* isTouchedWindow */ false));
2389 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002390 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
2391 // we perform the checks below to see if the touch can be propagated or not based on the
2392 // window's touch occlusion mode
2393 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
2394 info.hasBlockingOcclusion = true;
2395 info.obscuringUid = otherInfo->ownerUid;
2396 info.obscuringPackage = otherInfo->packageName;
2397 break;
2398 }
2399 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
2400 uint32_t uid = otherInfo->ownerUid;
2401 float opacity =
2402 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
2403 // Given windows A and B:
2404 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
2405 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
2406 opacityByUid[uid] = opacity;
2407 if (opacity > info.obscuringOpacity) {
2408 info.obscuringOpacity = opacity;
2409 info.obscuringUid = uid;
2410 info.obscuringPackage = otherInfo->packageName;
2411 }
2412 }
2413 }
2414 }
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002415 if (DEBUG_TOUCH_OCCLUSION) {
2416 info.debugInfo.push_back(
2417 dumpWindowForTouchOcclusion(windowInfo, /* isTouchedWindow */ true));
2418 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002419 return info;
2420}
2421
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002422std::string InputDispatcher::dumpWindowForTouchOcclusion(const InputWindowInfo* info,
2423 bool isTouchedWindow) const {
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00002424 return StringPrintf(INDENT2 "* %stype=%s, package=%s/%" PRId32 ", id=%" PRId32
2425 ", mode=%s, alpha=%.2f, "
Bernardo Rufinoc2f1fad2020-11-04 17:30:57 +00002426 "frame=[%" PRId32 ",%" PRId32 "][%" PRId32 ",%" PRId32
2427 "], touchableRegion=%s, window={%s}, applicationInfo=%s, "
2428 "flags={%s}, inputFeatures={%s}, hasToken=%s\n",
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002429 (isTouchedWindow) ? "[TOUCHED] " : "",
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00002430 NamedEnum::string(info->type, "%" PRId32).c_str(),
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00002431 info->packageName.c_str(), info->ownerUid, info->id,
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00002432 toString(info->touchOcclusionMode).c_str(), info->alpha, info->frameLeft,
2433 info->frameTop, info->frameRight, info->frameBottom,
2434 dumpRegion(info->touchableRegion).c_str(), info->name.c_str(),
Bernardo Rufinoc2f1fad2020-11-04 17:30:57 +00002435 info->applicationInfo.name.c_str(), info->flags.string().c_str(),
2436 info->inputFeatures.string().c_str(), toString(info->token != nullptr));
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002437}
2438
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002439bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
2440 if (occlusionInfo.hasBlockingOcclusion) {
2441 ALOGW("Untrusted touch due to occlusion by %s/%d", occlusionInfo.obscuringPackage.c_str(),
2442 occlusionInfo.obscuringUid);
2443 return false;
2444 }
2445 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
2446 ALOGW("Untrusted touch due to occlusion by %s/%d (obscuring opacity = "
2447 "%.2f, maximum allowed = %.2f)",
2448 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid,
2449 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
2450 return false;
2451 }
2452 return true;
2453}
2454
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002455bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<InputWindowHandle>& windowHandle,
2456 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002457 int32_t displayId = windowHandle->getInfo()->displayId;
Vishnu Nairad321cd2020-08-20 16:40:21 -07002458 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002459 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002460 if (windowHandle == otherHandle) {
2461 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002462 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002463 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002464 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002465 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002466 return true;
2467 }
2468 }
2469 return false;
2470}
2471
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002472bool InputDispatcher::isWindowObscuredLocked(const sp<InputWindowHandle>& windowHandle) const {
2473 int32_t displayId = windowHandle->getInfo()->displayId;
Vishnu Nairad321cd2020-08-20 16:40:21 -07002474 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002475 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002476 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002477 if (windowHandle == otherHandle) {
2478 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002479 }
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002480 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002481 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002482 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002483 return true;
2484 }
2485 }
2486 return false;
2487}
2488
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002489std::string InputDispatcher::getApplicationWindowLabel(
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05002490 const InputApplicationHandle* applicationHandle,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002491 const sp<InputWindowHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002492 if (applicationHandle != nullptr) {
2493 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002494 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002495 } else {
2496 return applicationHandle->getName();
2497 }
Yi Kong9b14ac62018-07-17 13:48:38 -07002498 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002499 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002500 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002501 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002502 }
2503}
2504
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002505void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Prabir Pradhan99987712020-11-10 18:43:05 -08002506 if (eventEntry.type == EventEntry::Type::FOCUS ||
2507 eventEntry.type == EventEntry::Type::POINTER_CAPTURE_CHANGED) {
2508 // Focus or pointer capture changed events are passed to apps, but do not represent user
2509 // activity.
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002510 return;
2511 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002512 int32_t displayId = getTargetDisplayId(eventEntry);
Vishnu Nairad321cd2020-08-20 16:40:21 -07002513 sp<InputWindowHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Tiger Huang721e26f2018-07-24 22:26:19 +08002514 if (focusedWindowHandle != nullptr) {
2515 const InputWindowInfo* info = focusedWindowHandle->getInfo();
Michael Wright44753b12020-07-08 13:48:11 +01002516 if (info->inputFeatures.test(InputWindowInfo::Feature::DISABLE_USER_ACTIVITY)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002517#if DEBUG_DISPATCH_CYCLE
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002518 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002519#endif
2520 return;
2521 }
2522 }
2523
2524 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002525 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002526 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002527 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
2528 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002529 return;
2530 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002531
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002532 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002533 eventType = USER_ACTIVITY_EVENT_TOUCH;
2534 }
2535 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002536 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002537 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002538 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
2539 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002540 return;
2541 }
2542 eventType = USER_ACTIVITY_EVENT_BUTTON;
2543 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002544 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002545 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002546 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08002547 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07002548 case EventEntry::Type::SENSOR:
Prabir Pradhan99987712020-11-10 18:43:05 -08002549 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002550 LOG_ALWAYS_FATAL("%s events are not user activity",
Chris Yef59a2f42020-10-16 12:55:26 -07002551 NamedEnum::string(eventEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002552 break;
2553 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002554 }
2555
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002556 std::unique_ptr<CommandEntry> commandEntry =
2557 std::make_unique<CommandEntry>(&InputDispatcher::doPokeUserActivityLockedInterruptible);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002558 commandEntry->eventTime = eventEntry.eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002559 commandEntry->userActivityEventType = eventType;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002560 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002561}
2562
2563void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002564 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002565 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002566 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002567 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002568 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002569 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002570 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002571 ATRACE_NAME(message.c_str());
2572 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002573#if DEBUG_DISPATCH_CYCLE
2574 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002575 "globalScaleFactor=%f, pointerIds=0x%x %s",
2576 connection->getInputChannelName().c_str(), inputTarget.flags,
2577 inputTarget.globalScaleFactor, inputTarget.pointerIds.value,
2578 inputTarget.getPointerInfoString().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002579#endif
2580
2581 // Skip this event if the connection status is not normal.
2582 // We don't want to enqueue additional outbound events if the connection is broken.
2583 if (connection->status != Connection::STATUS_NORMAL) {
2584#if DEBUG_DISPATCH_CYCLE
2585 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002586 connection->getInputChannelName().c_str(), connection->getStatusLabel());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002587#endif
2588 return;
2589 }
2590
2591 // Split a motion event if needed.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002592 if (inputTarget.flags & InputTarget::FLAG_SPLIT) {
2593 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
2594 "Entry type %s should not have FLAG_SPLIT",
Chris Yef59a2f42020-10-16 12:55:26 -07002595 NamedEnum::string(eventEntry->type).c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002596
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002597 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002598 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002599 std::unique_ptr<MotionEntry> splitMotionEntry =
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002600 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002601 if (!splitMotionEntry) {
2602 return; // split event was dropped
2603 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002604 if (DEBUG_FOCUS) {
2605 ALOGD("channel '%s' ~ Split motion event.",
2606 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002607 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002608 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002609 enqueueDispatchEntriesLocked(currentTime, connection, std::move(splitMotionEntry),
2610 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002611 return;
2612 }
2613 }
2614
2615 // Not splitting. Enqueue dispatch entries for the event as is.
2616 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
2617}
2618
2619void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002620 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002621 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002622 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002623 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002624 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002625 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002626 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002627 ATRACE_NAME(message.c_str());
2628 }
2629
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002630 bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002631
2632 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07002633 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002634 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002635 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002636 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07002637 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002638 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07002639 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002640 InputTarget::FLAG_DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07002641 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002642 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002643 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002644 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002645
2646 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002647 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002648 startDispatchCycleLocked(currentTime, connection);
2649 }
2650}
2651
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002652void InputDispatcher::enqueueDispatchEntryLocked(const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002653 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002654 const InputTarget& inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002655 int32_t dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002656 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002657 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
2658 connection->getInputChannelName().c_str(),
2659 dispatchModeToString(dispatchMode).c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002660 ATRACE_NAME(message.c_str());
2661 }
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002662 int32_t inputTargetFlags = inputTarget.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002663 if (!(inputTargetFlags & dispatchMode)) {
2664 return;
2665 }
2666 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
2667
2668 // This is a new event.
2669 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002670 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002671 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002672
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002673 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
2674 // different EventEntry than what was passed in.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002675 EventEntry& newEntry = *(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002676 // Apply target flags and update the connection's input state.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002677 switch (newEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002678 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002679 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002680 dispatchEntry->resolvedEventId = keyEntry.id;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002681 dispatchEntry->resolvedAction = keyEntry.action;
2682 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002683
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002684 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
2685 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002686#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002687 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key event",
2688 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002689#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002690 return; // skip the inconsistent event
2691 }
2692 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002693 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002694
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002695 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002696 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002697 // Assign a default value to dispatchEntry that will never be generated by InputReader,
2698 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
2699 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
2700 static_cast<int32_t>(IdGenerator::Source::OTHER);
2701 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002702 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2703 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
2704 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
2705 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
2706 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
2707 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2708 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
2709 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
2710 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
2711 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
2712 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002713 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002714 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002715 }
2716 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002717 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
2718 motionEntry.displayId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002719#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002720 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover enter "
2721 "event",
2722 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002723#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002724 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2725 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002726
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002727 dispatchEntry->resolvedFlags = motionEntry.flags;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002728 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
2729 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
2730 }
2731 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
2732 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2733 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002734
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002735 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
2736 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002737#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002738 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
2739 "event",
2740 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002741#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002742 return; // skip the inconsistent event
2743 }
2744
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002745 dispatchEntry->resolvedEventId =
2746 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
2747 ? mIdGenerator.nextId()
2748 : motionEntry.id;
2749 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
2750 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
2751 ") to MotionEvent(id=0x%" PRIx32 ").",
2752 motionEntry.id, dispatchEntry->resolvedEventId);
2753 ATRACE_NAME(message.c_str());
2754 }
2755
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002756 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002757 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002758
2759 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002760 }
Prabir Pradhan99987712020-11-10 18:43:05 -08002761 case EventEntry::Type::FOCUS:
2762 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002763 break;
2764 }
Chris Yef59a2f42020-10-16 12:55:26 -07002765 case EventEntry::Type::SENSOR: {
2766 LOG_ALWAYS_FATAL("SENSOR events should not go to apps via input channel");
2767 break;
2768 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002769 case EventEntry::Type::CONFIGURATION_CHANGED:
2770 case EventEntry::Type::DEVICE_RESET: {
2771 LOG_ALWAYS_FATAL("%s events should not go to apps",
Chris Yef59a2f42020-10-16 12:55:26 -07002772 NamedEnum::string(newEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002773 break;
2774 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002775 }
2776
2777 // Remember that we are waiting for this dispatch to complete.
2778 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002779 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002780 }
2781
2782 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002783 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002784 traceOutboundQueueLength(connection);
chaviw8c9cf542019-03-25 13:02:48 -07002785}
2786
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00002787/**
2788 * This function is purely for debugging. It helps us understand where the user interaction
2789 * was taking place. For example, if user is touching launcher, we will see a log that user
2790 * started interacting with launcher. In that example, the event would go to the wallpaper as well.
2791 * We will see both launcher and wallpaper in that list.
2792 * Once the interaction with a particular set of connections starts, no new logs will be printed
2793 * until the set of interacted connections changes.
2794 *
2795 * The following items are skipped, to reduce the logspam:
2796 * ACTION_OUTSIDE: any windows that are receiving ACTION_OUTSIDE are not logged
2797 * ACTION_UP: any windows that receive ACTION_UP are not logged (for both keys and motions).
2798 * This includes situations like the soft BACK button key. When the user releases (lifts up the
2799 * finger) the back button, then navigation bar will inject KEYCODE_BACK with ACTION_UP.
2800 * Both of those ACTION_UP events would not be logged
2801 * Monitors (both gesture and global): any gesture monitors or global monitors receiving events
2802 * will not be logged. This is omitted to reduce the amount of data printed.
2803 * If you see <none>, it's likely that one of the gesture monitors pilfered the event, and therefore
2804 * gesture monitor is the only connection receiving the remainder of the gesture.
2805 */
2806void InputDispatcher::updateInteractionTokensLocked(const EventEntry& entry,
2807 const std::vector<InputTarget>& targets) {
2808 // Skip ACTION_UP events, and all events other than keys and motions
2809 if (entry.type == EventEntry::Type::KEY) {
2810 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
2811 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
2812 return;
2813 }
2814 } else if (entry.type == EventEntry::Type::MOTION) {
2815 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
2816 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
2817 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
2818 return;
2819 }
2820 } else {
2821 return; // Not a key or a motion
2822 }
2823
2824 std::unordered_set<sp<IBinder>, IBinderHash> newConnectionTokens;
2825 std::vector<sp<Connection>> newConnections;
2826 for (const InputTarget& target : targets) {
2827 if ((target.flags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) ==
2828 InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2829 continue; // Skip windows that receive ACTION_OUTSIDE
2830 }
2831
2832 sp<IBinder> token = target.inputChannel->getConnectionToken();
2833 sp<Connection> connection = getConnectionLocked(token);
2834 if (connection == nullptr || connection->monitor) {
2835 continue; // We only need to keep track of the non-monitor connections.
2836 }
2837 newConnectionTokens.insert(std::move(token));
2838 newConnections.emplace_back(connection);
2839 }
2840 if (newConnectionTokens == mInteractionConnectionTokens) {
2841 return; // no change
2842 }
2843 mInteractionConnectionTokens = newConnectionTokens;
2844
2845 std::string windowList;
2846 for (const sp<Connection>& connection : newConnections) {
2847 windowList += connection->getWindowName() + ", ";
2848 }
2849 std::string message = "Interaction with windows: " + windowList;
2850 if (windowList.empty()) {
2851 message += "<none>";
2852 }
2853 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
2854}
2855
chaviwfd6d3512019-03-25 13:23:49 -07002856void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07002857 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07002858 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07002859 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
2860 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07002861 return;
2862 }
2863
Vishnu Nairad321cd2020-08-20 16:40:21 -07002864 sp<IBinder> focusedToken = getValueByKey(mFocusedWindowTokenByDisplay, mFocusedDisplayId);
2865 if (focusedToken == token) {
2866 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07002867 return;
2868 }
2869
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002870 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
2871 &InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible);
Vishnu Nairad321cd2020-08-20 16:40:21 -07002872 commandEntry->newToken = token;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002873 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002874}
2875
2876void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002877 const sp<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002878 if (ATRACE_ENABLED()) {
2879 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002880 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002881 ATRACE_NAME(message.c_str());
2882 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002883#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002884 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002885#endif
2886
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002887 while (connection->status == Connection::STATUS_NORMAL && !connection->outboundQueue.empty()) {
2888 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002889 dispatchEntry->deliveryTime = currentTime;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05002890 const std::chrono::nanoseconds timeout =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002891 getDispatchingTimeoutLocked(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou70622952020-07-30 11:17:23 -05002892 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002893
2894 // Publish the event.
2895 status_t status;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002896 const EventEntry& eventEntry = *(dispatchEntry->eventEntry);
2897 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002898 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002899 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
2900 std::array<uint8_t, 32> hmac = getSignature(keyEntry, *dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002901
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002902 // Publish the key event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002903 status = connection->inputPublisher
2904 .publishKeyEvent(dispatchEntry->seq,
2905 dispatchEntry->resolvedEventId, keyEntry.deviceId,
2906 keyEntry.source, keyEntry.displayId,
2907 std::move(hmac), dispatchEntry->resolvedAction,
2908 dispatchEntry->resolvedFlags, keyEntry.keyCode,
2909 keyEntry.scanCode, keyEntry.metaState,
2910 keyEntry.repeatCount, keyEntry.downTime,
2911 keyEntry.eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002912 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002913 }
2914
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002915 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002916 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002917
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002918 PointerCoords scaledCoords[MAX_POINTERS];
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002919 const PointerCoords* usingCoords = motionEntry.pointerCoords;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002920
chaviw82357092020-01-28 13:13:06 -08002921 // Set the X and Y offset and X and Y scale depending on the input source.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002922 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) &&
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002923 !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
2924 float globalScaleFactor = dispatchEntry->globalScaleFactor;
chaviw82357092020-01-28 13:13:06 -08002925 if (globalScaleFactor != 1.0f) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002926 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
2927 scaledCoords[i] = motionEntry.pointerCoords[i];
chaviw82357092020-01-28 13:13:06 -08002928 // Don't apply window scale here since we don't want scale to affect raw
2929 // coordinates. The scale will be sent back to the client and applied
2930 // later when requesting relative coordinates.
2931 scaledCoords[i].scale(globalScaleFactor, 1 /* windowXScale */,
2932 1 /* windowYScale */);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002933 }
2934 usingCoords = scaledCoords;
2935 }
2936 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002937 // We don't want the dispatch target to know.
2938 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002939 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002940 scaledCoords[i].clear();
2941 }
2942 usingCoords = scaledCoords;
2943 }
2944 }
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07002945
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002946 std::array<uint8_t, 32> hmac = getSignature(motionEntry, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002947
2948 // Publish the motion event.
2949 status = connection->inputPublisher
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002950 .publishMotionEvent(dispatchEntry->seq,
2951 dispatchEntry->resolvedEventId,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002952 motionEntry.deviceId, motionEntry.source,
2953 motionEntry.displayId, std::move(hmac),
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002954 dispatchEntry->resolvedAction,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002955 motionEntry.actionButton,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002956 dispatchEntry->resolvedFlags,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002957 motionEntry.edgeFlags, motionEntry.metaState,
2958 motionEntry.buttonState,
2959 motionEntry.classification,
chaviw9eaa22c2020-07-01 16:21:27 -07002960 dispatchEntry->transform,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002961 motionEntry.xPrecision, motionEntry.yPrecision,
2962 motionEntry.xCursorPosition,
2963 motionEntry.yCursorPosition,
2964 motionEntry.downTime, motionEntry.eventTime,
2965 motionEntry.pointerCount,
2966 motionEntry.pointerProperties, usingCoords);
2967 reportTouchEventForStatistics(motionEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002968 break;
2969 }
Prabir Pradhan99987712020-11-10 18:43:05 -08002970
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002971 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002972 const FocusEntry& focusEntry = static_cast<const FocusEntry&>(eventEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002973 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002974 focusEntry.id,
2975 focusEntry.hasFocus,
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002976 mInTouchMode);
2977 break;
2978 }
2979
Prabir Pradhan99987712020-11-10 18:43:05 -08002980 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
2981 const auto& captureEntry =
2982 static_cast<const PointerCaptureChangedEntry&>(eventEntry);
2983 status = connection->inputPublisher
2984 .publishCaptureEvent(dispatchEntry->seq, captureEntry.id,
2985 captureEntry.pointerCaptureEnabled);
2986 break;
2987 }
2988
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08002989 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07002990 case EventEntry::Type::DEVICE_RESET:
2991 case EventEntry::Type::SENSOR: {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08002992 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
Chris Yef59a2f42020-10-16 12:55:26 -07002993 NamedEnum::string(eventEntry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002994 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08002995 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002996 }
2997
2998 // Check the result.
2999 if (status) {
3000 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003001 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003002 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003003 "This is unexpected because the wait queue is empty, so the pipe "
3004 "should be empty and we shouldn't have any problems writing an "
3005 "event to it, status=%d",
3006 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003007 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3008 } else {
3009 // Pipe is full and we are waiting for the app to finish process some events
3010 // before sending more events to it.
3011#if DEBUG_DISPATCH_CYCLE
3012 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003013 "waiting for the application to catch up",
3014 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003015#endif
Michael Wrightd02c5b62014-02-10 15:10:22 -08003016 }
3017 } else {
3018 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003019 "status=%d",
3020 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003021 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3022 }
3023 return;
3024 }
3025
3026 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003027 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
3028 connection->outboundQueue.end(),
3029 dispatchEntry));
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003030 traceOutboundQueueLength(connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003031 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003032 if (connection->responsive) {
3033 mAnrTracker.insert(dispatchEntry->timeoutTime,
3034 connection->inputChannel->getConnectionToken());
3035 }
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003036 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003037 }
3038}
3039
chaviw09c8d2d2020-08-24 15:48:26 -07003040std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
3041 size_t size;
3042 switch (event.type) {
3043 case VerifiedInputEvent::Type::KEY: {
3044 size = sizeof(VerifiedKeyEvent);
3045 break;
3046 }
3047 case VerifiedInputEvent::Type::MOTION: {
3048 size = sizeof(VerifiedMotionEvent);
3049 break;
3050 }
3051 }
3052 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
3053 return mHmacKeyManager.sign(start, size);
3054}
3055
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003056const std::array<uint8_t, 32> InputDispatcher::getSignature(
3057 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
3058 int32_t actionMasked = dispatchEntry.resolvedAction & AMOTION_EVENT_ACTION_MASK;
3059 if ((actionMasked == AMOTION_EVENT_ACTION_UP) || (actionMasked == AMOTION_EVENT_ACTION_DOWN)) {
3060 // Only sign events up and down events as the purely move events
3061 // are tied to their up/down counterparts so signing would be redundant.
3062 VerifiedMotionEvent verifiedEvent = verifiedMotionEventFromMotionEntry(motionEntry);
3063 verifiedEvent.actionMasked = actionMasked;
3064 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
chaviw09c8d2d2020-08-24 15:48:26 -07003065 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003066 }
3067 return INVALID_HMAC;
3068}
3069
3070const std::array<uint8_t, 32> InputDispatcher::getSignature(
3071 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
3072 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
3073 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
3074 verifiedEvent.action = dispatchEntry.resolvedAction;
chaviw09c8d2d2020-08-24 15:48:26 -07003075 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003076}
3077
Michael Wrightd02c5b62014-02-10 15:10:22 -08003078void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003079 const sp<Connection>& connection, uint32_t seq,
3080 bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003081#if DEBUG_DISPATCH_CYCLE
3082 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003083 connection->getInputChannelName().c_str(), seq, toString(handled));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003084#endif
3085
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003086 if (connection->status == Connection::STATUS_BROKEN ||
3087 connection->status == Connection::STATUS_ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003088 return;
3089 }
3090
3091 // Notify other system components and prepare to start the next dispatch cycle.
3092 onDispatchCycleFinishedLocked(currentTime, connection, seq, handled);
3093}
3094
3095void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003096 const sp<Connection>& connection,
3097 bool notify) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003098#if DEBUG_DISPATCH_CYCLE
3099 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003100 connection->getInputChannelName().c_str(), toString(notify));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003101#endif
3102
3103 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003104 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003105 traceOutboundQueueLength(connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003106 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003107 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003108
3109 // The connection appears to be unrecoverably broken.
3110 // Ignore already broken or zombie connections.
3111 if (connection->status == Connection::STATUS_NORMAL) {
3112 connection->status = Connection::STATUS_BROKEN;
3113
3114 if (notify) {
3115 // Notify other system components.
3116 onDispatchCycleBrokenLocked(currentTime, connection);
3117 }
3118 }
3119}
3120
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003121void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
3122 while (!queue.empty()) {
3123 DispatchEntry* dispatchEntry = queue.front();
3124 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003125 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003126 }
3127}
3128
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003129void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003130 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003131 decrementPendingForegroundDispatches(*(dispatchEntry->eventEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003132 }
3133 delete dispatchEntry;
3134}
3135
3136int InputDispatcher::handleReceiveCallback(int fd, int events, void* data) {
3137 InputDispatcher* d = static_cast<InputDispatcher*>(data);
3138
3139 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003140 std::scoped_lock _l(d->mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003141
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003142 if (d->mConnectionsByFd.find(fd) == d->mConnectionsByFd.end()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003143 ALOGE("Received spurious receive callback for unknown input channel. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003144 "fd=%d, events=0x%x",
3145 fd, events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003146 return 0; // remove the callback
3147 }
3148
3149 bool notify;
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003150 sp<Connection> connection = d->mConnectionsByFd[fd];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003151 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
3152 if (!(events & ALOOPER_EVENT_INPUT)) {
3153 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003154 "events=0x%x",
3155 connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003156 return 1;
3157 }
3158
3159 nsecs_t currentTime = now();
3160 bool gotOne = false;
3161 status_t status;
3162 for (;;) {
3163 uint32_t seq;
3164 bool handled;
3165 status = connection->inputPublisher.receiveFinishedSignal(&seq, &handled);
3166 if (status) {
3167 break;
3168 }
3169 d->finishDispatchCycleLocked(currentTime, connection, seq, handled);
3170 gotOne = true;
3171 }
3172 if (gotOne) {
3173 d->runCommandsLockedInterruptible();
3174 if (status == WOULD_BLOCK) {
3175 return 1;
3176 }
3177 }
3178
3179 notify = status != DEAD_OBJECT || !connection->monitor;
3180 if (notify) {
3181 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003182 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003183 }
3184 } else {
3185 // Monitor channels are never explicitly unregistered.
3186 // We do it automatically when the remote endpoint is closed so don't warn
3187 // about them.
arthurhungd352cb32020-04-28 17:09:28 +08003188 const bool stillHaveWindowHandle =
3189 d->getWindowHandleLocked(connection->inputChannel->getConnectionToken()) !=
3190 nullptr;
3191 notify = !connection->monitor && stillHaveWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003192 if (notify) {
3193 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003194 "events=0x%x",
3195 connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003196 }
3197 }
3198
Garfield Tan15601662020-09-22 15:32:38 -07003199 // Remove the channel.
3200 d->removeInputChannelLocked(connection->inputChannel->getConnectionToken(), notify);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003201 return 0; // remove the callback
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003202 } // release lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08003203}
3204
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003205void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08003206 const CancelationOptions& options) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003207 for (const auto& pair : mConnectionsByFd) {
3208 synthesizeCancelationEventsForConnectionLocked(pair.second, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003209 }
3210}
3211
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003212void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003213 const CancelationOptions& options) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003214 synthesizeCancelationEventsForMonitorsLocked(options, mGlobalMonitorsByDisplay);
3215 synthesizeCancelationEventsForMonitorsLocked(options, mGestureMonitorsByDisplay);
3216}
3217
3218void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
3219 const CancelationOptions& options,
3220 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
3221 for (const auto& it : monitorsByDisplay) {
3222 const std::vector<Monitor>& monitors = it.second;
3223 for (const Monitor& monitor : monitors) {
3224 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003225 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003226 }
3227}
3228
Michael Wrightd02c5b62014-02-10 15:10:22 -08003229void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003230 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07003231 sp<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003232 if (connection == nullptr) {
3233 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003234 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003235
3236 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003237}
3238
3239void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
3240 const sp<Connection>& connection, const CancelationOptions& options) {
3241 if (connection->status == Connection::STATUS_BROKEN) {
3242 return;
3243 }
3244
3245 nsecs_t currentTime = now();
3246
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003247 std::vector<std::unique_ptr<EventEntry>> cancelationEvents =
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07003248 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003249
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003250 if (cancelationEvents.empty()) {
3251 return;
3252 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003253#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003254 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
3255 "with reality: %s, mode=%d.",
3256 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
3257 options.mode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003258#endif
Svet Ganov5d3bc372020-01-26 23:11:07 -08003259
3260 InputTarget target;
3261 sp<InputWindowHandle> windowHandle =
3262 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3263 if (windowHandle != nullptr) {
3264 const InputWindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003265 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003266 target.globalScaleFactor = windowInfo->globalScaleFactor;
3267 }
3268 target.inputChannel = connection->inputChannel;
3269 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3270
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003271 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003272 std::unique_ptr<EventEntry> cancelationEventEntry = std::move(cancelationEvents[i]);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003273 switch (cancelationEventEntry->type) {
3274 case EventEntry::Type::KEY: {
3275 logOutboundKeyDetails("cancel - ",
3276 static_cast<const KeyEntry&>(*cancelationEventEntry));
3277 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003278 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003279 case EventEntry::Type::MOTION: {
3280 logOutboundMotionDetails("cancel - ",
3281 static_cast<const MotionEntry&>(*cancelationEventEntry));
3282 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003283 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003284 case EventEntry::Type::FOCUS:
3285 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3286 LOG_ALWAYS_FATAL("Canceling %s events is not supported",
Chris Yef59a2f42020-10-16 12:55:26 -07003287 NamedEnum::string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003288 break;
3289 }
3290 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003291 case EventEntry::Type::DEVICE_RESET:
3292 case EventEntry::Type::SENSOR: {
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003293 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Chris Yef59a2f42020-10-16 12:55:26 -07003294 NamedEnum::string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003295 break;
3296 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003297 }
3298
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003299 enqueueDispatchEntryLocked(connection, std::move(cancelationEventEntry), target,
3300 InputTarget::FLAG_DISPATCH_AS_IS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003301 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003302
3303 startDispatchCycleLocked(currentTime, connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003304}
3305
Svet Ganov5d3bc372020-01-26 23:11:07 -08003306void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
3307 const sp<Connection>& connection) {
3308 if (connection->status == Connection::STATUS_BROKEN) {
3309 return;
3310 }
3311
3312 nsecs_t currentTime = now();
3313
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003314 std::vector<std::unique_ptr<EventEntry>> downEvents =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003315 connection->inputState.synthesizePointerDownEvents(currentTime);
3316
3317 if (downEvents.empty()) {
3318 return;
3319 }
3320
3321#if DEBUG_OUTBOUND_EVENT_DETAILS
3322 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
3323 connection->getInputChannelName().c_str(), downEvents.size());
3324#endif
3325
3326 InputTarget target;
3327 sp<InputWindowHandle> windowHandle =
3328 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3329 if (windowHandle != nullptr) {
3330 const InputWindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003331 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003332 target.globalScaleFactor = windowInfo->globalScaleFactor;
3333 }
3334 target.inputChannel = connection->inputChannel;
3335 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3336
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003337 for (std::unique_ptr<EventEntry>& downEventEntry : downEvents) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003338 switch (downEventEntry->type) {
3339 case EventEntry::Type::MOTION: {
3340 logOutboundMotionDetails("down - ",
3341 static_cast<const MotionEntry&>(*downEventEntry));
3342 break;
3343 }
3344
3345 case EventEntry::Type::KEY:
3346 case EventEntry::Type::FOCUS:
3347 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08003348 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07003349 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3350 case EventEntry::Type::SENSOR: {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003351 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Chris Yef59a2f42020-10-16 12:55:26 -07003352 NamedEnum::string(downEventEntry->type).c_str());
Svet Ganov5d3bc372020-01-26 23:11:07 -08003353 break;
3354 }
3355 }
3356
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003357 enqueueDispatchEntryLocked(connection, std::move(downEventEntry), target,
3358 InputTarget::FLAG_DISPATCH_AS_IS);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003359 }
3360
3361 startDispatchCycleLocked(currentTime, connection);
3362}
3363
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003364std::unique_ptr<MotionEntry> InputDispatcher::splitMotionEvent(
3365 const MotionEntry& originalMotionEntry, BitSet32 pointerIds) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003366 ALOG_ASSERT(pointerIds.value != 0);
3367
3368 uint32_t splitPointerIndexMap[MAX_POINTERS];
3369 PointerProperties splitPointerProperties[MAX_POINTERS];
3370 PointerCoords splitPointerCoords[MAX_POINTERS];
3371
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003372 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003373 uint32_t splitPointerCount = 0;
3374
3375 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003376 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003377 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003378 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003379 uint32_t pointerId = uint32_t(pointerProperties.id);
3380 if (pointerIds.hasBit(pointerId)) {
3381 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
3382 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
3383 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003384 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003385 splitPointerCount += 1;
3386 }
3387 }
3388
3389 if (splitPointerCount != pointerIds.count()) {
3390 // This is bad. We are missing some of the pointers that we expected to deliver.
3391 // Most likely this indicates that we received an ACTION_MOVE events that has
3392 // different pointer ids than we expected based on the previous ACTION_DOWN
3393 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
3394 // in this way.
3395 ALOGW("Dropping split motion event because the pointer count is %d but "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003396 "we expected there to be %d pointers. This probably means we received "
3397 "a broken sequence of pointer ids from the input device.",
3398 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07003399 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003400 }
3401
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003402 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003403 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003404 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
3405 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003406 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
3407 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003408 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003409 uint32_t pointerId = uint32_t(pointerProperties.id);
3410 if (pointerIds.hasBit(pointerId)) {
3411 if (pointerIds.count() == 1) {
3412 // The first/last pointer went down/up.
3413 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003414 ? AMOTION_EVENT_ACTION_DOWN
3415 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003416 } else {
3417 // A secondary pointer went down/up.
3418 uint32_t splitPointerIndex = 0;
3419 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
3420 splitPointerIndex += 1;
3421 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003422 action = maskedAction |
3423 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003424 }
3425 } else {
3426 // An unrelated pointer changed.
3427 action = AMOTION_EVENT_ACTION_MOVE;
3428 }
3429 }
3430
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003431 int32_t newId = mIdGenerator.nextId();
3432 if (ATRACE_ENABLED()) {
3433 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
3434 ") to MotionEvent(id=0x%" PRIx32 ").",
3435 originalMotionEntry.id, newId);
3436 ATRACE_NAME(message.c_str());
3437 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003438 std::unique_ptr<MotionEntry> splitMotionEntry =
3439 std::make_unique<MotionEntry>(newId, originalMotionEntry.eventTime,
3440 originalMotionEntry.deviceId, originalMotionEntry.source,
3441 originalMotionEntry.displayId,
3442 originalMotionEntry.policyFlags, action,
3443 originalMotionEntry.actionButton,
3444 originalMotionEntry.flags, originalMotionEntry.metaState,
3445 originalMotionEntry.buttonState,
3446 originalMotionEntry.classification,
3447 originalMotionEntry.edgeFlags,
3448 originalMotionEntry.xPrecision,
3449 originalMotionEntry.yPrecision,
3450 originalMotionEntry.xCursorPosition,
3451 originalMotionEntry.yCursorPosition,
3452 originalMotionEntry.downTime, splitPointerCount,
3453 splitPointerProperties, splitPointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003454
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003455 if (originalMotionEntry.injectionState) {
3456 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003457 splitMotionEntry->injectionState->refCount += 1;
3458 }
3459
3460 return splitMotionEntry;
3461}
3462
3463void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
3464#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003465 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003466#endif
3467
3468 bool needWake;
3469 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003470 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003471
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003472 std::unique_ptr<ConfigurationChangedEntry> newEntry =
3473 std::make_unique<ConfigurationChangedEntry>(args->id, args->eventTime);
3474 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003475 } // release lock
3476
3477 if (needWake) {
3478 mLooper->wake();
3479 }
3480}
3481
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003482/**
3483 * If one of the meta shortcuts is detected, process them here:
3484 * Meta + Backspace -> generate BACK
3485 * Meta + Enter -> generate HOME
3486 * This will potentially overwrite keyCode and metaState.
3487 */
3488void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003489 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003490 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
3491 int32_t newKeyCode = AKEYCODE_UNKNOWN;
3492 if (keyCode == AKEYCODE_DEL) {
3493 newKeyCode = AKEYCODE_BACK;
3494 } else if (keyCode == AKEYCODE_ENTER) {
3495 newKeyCode = AKEYCODE_HOME;
3496 }
3497 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003498 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003499 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003500 mReplacedKeys[replacement] = newKeyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003501 keyCode = newKeyCode;
3502 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3503 }
3504 } else if (action == AKEY_EVENT_ACTION_UP) {
3505 // In order to maintain a consistent stream of up and down events, check to see if the key
3506 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
3507 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003508 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003509 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003510 auto replacementIt = mReplacedKeys.find(replacement);
3511 if (replacementIt != mReplacedKeys.end()) {
3512 keyCode = replacementIt->second;
3513 mReplacedKeys.erase(replacementIt);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003514 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3515 }
3516 }
3517}
3518
Michael Wrightd02c5b62014-02-10 15:10:22 -08003519void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
3520#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003521 ALOGD("notifyKey - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
3522 "policyFlags=0x%x, action=0x%x, "
3523 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
3524 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
3525 args->action, args->flags, args->keyCode, args->scanCode, args->metaState,
3526 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003527#endif
3528 if (!validateKeyEvent(args->action)) {
3529 return;
3530 }
3531
3532 uint32_t policyFlags = args->policyFlags;
3533 int32_t flags = args->flags;
3534 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07003535 // InputDispatcher tracks and generates key repeats on behalf of
3536 // whatever notifies it, so repeatCount should always be set to 0
3537 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003538 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
3539 policyFlags |= POLICY_FLAG_VIRTUAL;
3540 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
3541 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003542 if (policyFlags & POLICY_FLAG_FUNCTION) {
3543 metaState |= AMETA_FUNCTION_ON;
3544 }
3545
3546 policyFlags |= POLICY_FLAG_TRUSTED;
3547
Michael Wright78f24442014-08-06 15:55:28 -07003548 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003549 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07003550
Michael Wrightd02c5b62014-02-10 15:10:22 -08003551 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003552 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08003553 args->action, flags, keyCode, args->scanCode, metaState, repeatCount,
3554 args->downTime, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003555
Michael Wright2b3c3302018-03-02 17:19:13 +00003556 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003557 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003558 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3559 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003560 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003561 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003562
Michael Wrightd02c5b62014-02-10 15:10:22 -08003563 bool needWake;
3564 { // acquire lock
3565 mLock.lock();
3566
3567 if (shouldSendKeyToInputFilterLocked(args)) {
3568 mLock.unlock();
3569
3570 policyFlags |= POLICY_FLAG_FILTERED;
3571 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3572 return; // event was consumed by the filter
3573 }
3574
3575 mLock.lock();
3576 }
3577
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003578 std::unique_ptr<KeyEntry> newEntry =
3579 std::make_unique<KeyEntry>(args->id, args->eventTime, args->deviceId, args->source,
3580 args->displayId, policyFlags, args->action, flags,
3581 keyCode, args->scanCode, metaState, repeatCount,
3582 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003583
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003584 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003585 mLock.unlock();
3586 } // release lock
3587
3588 if (needWake) {
3589 mLooper->wake();
3590 }
3591}
3592
3593bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
3594 return mInputFilterEnabled;
3595}
3596
3597void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
3598#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003599 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
3600 "displayId=%" PRId32 ", policyFlags=0x%x, "
Garfield Tan00f511d2019-06-12 16:55:40 -07003601 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
3602 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
Garfield Tanab0ab9c2019-07-10 18:58:28 -07003603 "yCursorPosition=%f, downTime=%" PRId64,
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003604 args->id, args->eventTime, args->deviceId, args->source, args->displayId,
3605 args->policyFlags, args->action, args->actionButton, args->flags, args->metaState,
3606 args->buttonState, args->edgeFlags, args->xPrecision, args->yPrecision,
3607 args->xCursorPosition, args->yCursorPosition, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003608 for (uint32_t i = 0; i < args->pointerCount; i++) {
3609 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003610 "x=%f, y=%f, pressure=%f, size=%f, "
3611 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
3612 "orientation=%f",
3613 i, args->pointerProperties[i].id, args->pointerProperties[i].toolType,
3614 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
3615 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
3616 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
3617 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
3618 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
3619 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
3620 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
3621 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
3622 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003623 }
3624#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003625 if (!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
3626 args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003627 return;
3628 }
3629
3630 uint32_t policyFlags = args->policyFlags;
3631 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003632
3633 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08003634 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003635 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3636 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003637 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003638 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003639
3640 bool needWake;
3641 { // acquire lock
3642 mLock.lock();
3643
3644 if (shouldSendMotionToInputFilterLocked(args)) {
3645 mLock.unlock();
3646
3647 MotionEvent event;
chaviw9eaa22c2020-07-01 16:21:27 -07003648 ui::Transform transform;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003649 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
3650 args->action, args->actionButton, args->flags, args->edgeFlags,
chaviw9eaa22c2020-07-01 16:21:27 -07003651 args->metaState, args->buttonState, args->classification, transform,
3652 args->xPrecision, args->yPrecision, args->xCursorPosition,
3653 args->yCursorPosition, args->downTime, args->eventTime,
3654 args->pointerCount, args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003655
3656 policyFlags |= POLICY_FLAG_FILTERED;
3657 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3658 return; // event was consumed by the filter
3659 }
3660
3661 mLock.lock();
3662 }
3663
3664 // Just enqueue a new motion event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003665 std::unique_ptr<MotionEntry> newEntry =
3666 std::make_unique<MotionEntry>(args->id, args->eventTime, args->deviceId,
3667 args->source, args->displayId, policyFlags,
3668 args->action, args->actionButton, args->flags,
3669 args->metaState, args->buttonState,
3670 args->classification, args->edgeFlags,
3671 args->xPrecision, args->yPrecision,
3672 args->xCursorPosition, args->yCursorPosition,
3673 args->downTime, args->pointerCount,
3674 args->pointerProperties, args->pointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003675
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003676 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003677 mLock.unlock();
3678 } // release lock
3679
3680 if (needWake) {
3681 mLooper->wake();
3682 }
3683}
3684
Chris Yef59a2f42020-10-16 12:55:26 -07003685void InputDispatcher::notifySensor(const NotifySensorArgs* args) {
3686#if DEBUG_INBOUND_EVENT_DETAILS
3687 ALOGD("notifySensor - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
3688 " sensorType=%s",
3689 args->id, args->eventTime, args->deviceId, args->source,
3690 NamedEnum::string(args->sensorType).c_str());
3691#endif
3692
3693 bool needWake;
3694 { // acquire lock
3695 mLock.lock();
3696
3697 // Just enqueue a new sensor event.
3698 std::unique_ptr<SensorEntry> newEntry =
3699 std::make_unique<SensorEntry>(args->id, args->eventTime, args->deviceId,
3700 args->source, 0 /* policyFlags*/, args->hwTimestamp,
3701 args->sensorType, args->accuracy,
3702 args->accuracyChanged, args->values);
3703
3704 needWake = enqueueInboundEventLocked(std::move(newEntry));
3705 mLock.unlock();
3706 } // release lock
3707
3708 if (needWake) {
3709 mLooper->wake();
3710 }
3711}
3712
Michael Wrightd02c5b62014-02-10 15:10:22 -08003713bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08003714 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003715}
3716
3717void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
3718#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003719 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003720 "switchMask=0x%08x",
3721 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003722#endif
3723
3724 uint32_t policyFlags = args->policyFlags;
3725 policyFlags |= POLICY_FLAG_TRUSTED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003726 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003727}
3728
3729void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
3730#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003731 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
3732 args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003733#endif
3734
3735 bool needWake;
3736 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003737 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003738
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003739 std::unique_ptr<DeviceResetEntry> newEntry =
3740 std::make_unique<DeviceResetEntry>(args->id, args->eventTime, args->deviceId);
3741 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003742 } // release lock
3743
3744 if (needWake) {
3745 mLooper->wake();
3746 }
3747}
3748
Prabir Pradhan7e186182020-11-10 13:56:45 -08003749void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs* args) {
3750#if DEBUG_INBOUND_EVENT_DETAILS
3751 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args->eventTime,
3752 args->enabled ? "true" : "false");
3753#endif
3754
Prabir Pradhan99987712020-11-10 18:43:05 -08003755 bool needWake;
3756 { // acquire lock
3757 std::scoped_lock _l(mLock);
3758 auto entry = std::make_unique<PointerCaptureChangedEntry>(args->id, args->eventTime,
3759 args->enabled);
3760 needWake = enqueueInboundEventLocked(std::move(entry));
3761 } // release lock
3762
3763 if (needWake) {
3764 mLooper->wake();
3765 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08003766}
3767
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003768InputEventInjectionResult InputDispatcher::injectInputEvent(
3769 const InputEvent* event, int32_t injectorPid, int32_t injectorUid,
3770 InputEventInjectionSync syncMode, std::chrono::milliseconds timeout, uint32_t policyFlags) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003771#if DEBUG_INBOUND_EVENT_DETAILS
3772 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003773 "syncMode=%d, timeout=%lld, policyFlags=0x%08x",
3774 event->getType(), injectorPid, injectorUid, syncMode, timeout.count(), policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003775#endif
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003776 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003777
3778 policyFlags |= POLICY_FLAG_INJECTED;
3779 if (hasInjectionPermission(injectorPid, injectorUid)) {
3780 policyFlags |= POLICY_FLAG_TRUSTED;
3781 }
3782
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003783 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003784 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003785 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003786 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
3787 int32_t action = incomingKey.getAction();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003788 if (!validateKeyEvent(action)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003789 return InputEventInjectionResult::FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003790 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003791
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003792 int32_t flags = incomingKey.getFlags();
3793 int32_t keyCode = incomingKey.getKeyCode();
3794 int32_t metaState = incomingKey.getMetaState();
3795 accelerateMetaShortcuts(VIRTUAL_KEYBOARD_ID, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003796 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003797 KeyEvent keyEvent;
Garfield Tan4cc839f2020-01-24 11:26:14 -08003798 keyEvent.initialize(incomingKey.getId(), VIRTUAL_KEYBOARD_ID, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003799 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
3800 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
3801 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003802
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003803 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
3804 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00003805 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003806
3807 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
3808 android::base::Timer t;
3809 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
3810 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3811 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
3812 std::to_string(t.duration().count()).c_str());
3813 }
3814 }
3815
3816 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003817 std::unique_ptr<KeyEntry> injectedEntry =
3818 std::make_unique<KeyEntry>(incomingKey.getId(), incomingKey.getEventTime(),
3819 VIRTUAL_KEYBOARD_ID, incomingKey.getSource(),
3820 incomingKey.getDisplayId(), policyFlags, action,
3821 flags, keyCode, incomingKey.getScanCode(), metaState,
3822 incomingKey.getRepeatCount(),
3823 incomingKey.getDownTime());
3824 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003825 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003826 }
3827
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003828 case AINPUT_EVENT_TYPE_MOTION: {
3829 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
3830 int32_t action = motionEvent->getAction();
3831 size_t pointerCount = motionEvent->getPointerCount();
3832 const PointerProperties* pointerProperties = motionEvent->getPointerProperties();
3833 int32_t actionButton = motionEvent->getActionButton();
3834 int32_t displayId = motionEvent->getDisplayId();
3835 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003836 return InputEventInjectionResult::FAILED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003837 }
3838
3839 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
3840 nsecs_t eventTime = motionEvent->getEventTime();
3841 android::base::Timer t;
3842 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
3843 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3844 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
3845 std::to_string(t.duration().count()).c_str());
3846 }
3847 }
3848
3849 mLock.lock();
3850 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
3851 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003852 std::unique_ptr<MotionEntry> injectedEntry =
3853 std::make_unique<MotionEntry>(motionEvent->getId(), *sampleEventTimes,
3854 VIRTUAL_KEYBOARD_ID, motionEvent->getSource(),
3855 motionEvent->getDisplayId(), policyFlags, action,
3856 actionButton, motionEvent->getFlags(),
3857 motionEvent->getMetaState(),
3858 motionEvent->getButtonState(),
3859 motionEvent->getClassification(),
3860 motionEvent->getEdgeFlags(),
3861 motionEvent->getXPrecision(),
3862 motionEvent->getYPrecision(),
3863 motionEvent->getRawXCursorPosition(),
3864 motionEvent->getRawYCursorPosition(),
3865 motionEvent->getDownTime(),
3866 uint32_t(pointerCount), pointerProperties,
3867 samplePointerCoords, motionEvent->getXOffset(),
3868 motionEvent->getYOffset());
3869 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003870 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
3871 sampleEventTimes += 1;
3872 samplePointerCoords += pointerCount;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003873 std::unique_ptr<MotionEntry> nextInjectedEntry =
3874 std::make_unique<MotionEntry>(motionEvent->getId(), *sampleEventTimes,
3875 VIRTUAL_KEYBOARD_ID, motionEvent->getSource(),
3876 motionEvent->getDisplayId(), policyFlags,
3877 action, actionButton, motionEvent->getFlags(),
3878 motionEvent->getMetaState(),
3879 motionEvent->getButtonState(),
3880 motionEvent->getClassification(),
3881 motionEvent->getEdgeFlags(),
3882 motionEvent->getXPrecision(),
3883 motionEvent->getYPrecision(),
3884 motionEvent->getRawXCursorPosition(),
3885 motionEvent->getRawYCursorPosition(),
3886 motionEvent->getDownTime(),
3887 uint32_t(pointerCount), pointerProperties,
3888 samplePointerCoords,
3889 motionEvent->getXOffset(),
3890 motionEvent->getYOffset());
3891 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003892 }
3893 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003894 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003895
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003896 default:
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08003897 ALOGW("Cannot inject %s events", inputEventTypeToString(event->getType()));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003898 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003899 }
3900
3901 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003902 if (syncMode == InputEventInjectionSync::NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003903 injectionState->injectionIsAsync = true;
3904 }
3905
3906 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003907 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003908
3909 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003910 while (!injectedEntries.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003911 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003912 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003913 }
3914
3915 mLock.unlock();
3916
3917 if (needWake) {
3918 mLooper->wake();
3919 }
3920
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003921 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003922 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003923 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003924
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003925 if (syncMode == InputEventInjectionSync::NONE) {
3926 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003927 } else {
3928 for (;;) {
3929 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003930 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003931 break;
3932 }
3933
3934 nsecs_t remainingTimeout = endTime - now();
3935 if (remainingTimeout <= 0) {
3936#if DEBUG_INJECTION
3937 ALOGD("injectInputEvent - Timed out waiting for injection result "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003938 "to become available.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003939#endif
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003940 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003941 break;
3942 }
3943
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003944 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003945 }
3946
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003947 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
3948 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003949 while (injectionState->pendingForegroundDispatches != 0) {
3950#if DEBUG_INJECTION
3951 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003952 injectionState->pendingForegroundDispatches);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003953#endif
3954 nsecs_t remainingTimeout = endTime - now();
3955 if (remainingTimeout <= 0) {
3956#if DEBUG_INJECTION
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003957 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
3958 "dispatches to finish.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003959#endif
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003960 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003961 break;
3962 }
3963
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003964 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003965 }
3966 }
3967 }
3968
3969 injectionState->release();
3970 } // release lock
3971
3972#if DEBUG_INJECTION
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003973 ALOGD("injectInputEvent - Finished with result %d. injectorPid=%d, injectorUid=%d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003974 injectionResult, injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003975#endif
3976
3977 return injectionResult;
3978}
3979
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08003980std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05003981 std::array<uint8_t, 32> calculatedHmac;
3982 std::unique_ptr<VerifiedInputEvent> result;
3983 switch (event.getType()) {
3984 case AINPUT_EVENT_TYPE_KEY: {
3985 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
3986 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
3987 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07003988 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05003989 break;
3990 }
3991 case AINPUT_EVENT_TYPE_MOTION: {
3992 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
3993 VerifiedMotionEvent verifiedMotionEvent =
3994 verifiedMotionEventFromMotionEvent(motionEvent);
3995 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07003996 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05003997 break;
3998 }
3999 default: {
4000 ALOGE("Cannot verify events of type %" PRId32, event.getType());
4001 return nullptr;
4002 }
4003 }
4004 if (calculatedHmac == INVALID_HMAC) {
4005 return nullptr;
4006 }
4007 if (calculatedHmac != event.getHmac()) {
4008 return nullptr;
4009 }
4010 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004011}
4012
Michael Wrightd02c5b62014-02-10 15:10:22 -08004013bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004014 return injectorUid == 0 ||
4015 mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004016}
4017
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004018void InputDispatcher::setInjectionResult(EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004019 InputEventInjectionResult injectionResult) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004020 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004021 if (injectionState) {
4022#if DEBUG_INJECTION
4023 ALOGD("Setting input event injection result to %d. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004024 "injectorPid=%d, injectorUid=%d",
4025 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004026#endif
4027
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004028 if (injectionState->injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004029 // Log the outcome since the injector did not wait for the injection result.
4030 switch (injectionResult) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004031 case InputEventInjectionResult::SUCCEEDED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004032 ALOGV("Asynchronous input event injection succeeded.");
4033 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004034 case InputEventInjectionResult::FAILED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004035 ALOGW("Asynchronous input event injection failed.");
4036 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004037 case InputEventInjectionResult::PERMISSION_DENIED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004038 ALOGW("Asynchronous input event injection permission denied.");
4039 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004040 case InputEventInjectionResult::TIMED_OUT:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004041 ALOGW("Asynchronous input event injection timed out.");
4042 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004043 case InputEventInjectionResult::PENDING:
4044 ALOGE("Setting result to 'PENDING' for asynchronous injection");
4045 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004046 }
4047 }
4048
4049 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004050 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004051 }
4052}
4053
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004054void InputDispatcher::incrementPendingForegroundDispatches(EventEntry& entry) {
4055 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004056 if (injectionState) {
4057 injectionState->pendingForegroundDispatches += 1;
4058 }
4059}
4060
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004061void InputDispatcher::decrementPendingForegroundDispatches(EventEntry& entry) {
4062 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004063 if (injectionState) {
4064 injectionState->pendingForegroundDispatches -= 1;
4065
4066 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004067 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004068 }
4069 }
4070}
4071
Vishnu Nairad321cd2020-08-20 16:40:21 -07004072const std::vector<sp<InputWindowHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004073 int32_t displayId) const {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004074 static const std::vector<sp<InputWindowHandle>> EMPTY_WINDOW_HANDLES;
4075 auto it = mWindowHandlesByDisplay.find(displayId);
4076 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08004077}
4078
Michael Wrightd02c5b62014-02-10 15:10:22 -08004079sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08004080 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08004081 if (windowHandleToken == nullptr) {
4082 return nullptr;
4083 }
4084
Arthur Hungb92218b2018-08-14 12:00:21 +08004085 for (auto& it : mWindowHandlesByDisplay) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004086 const std::vector<sp<InputWindowHandle>>& windowHandles = it.second;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004087 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004088 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004089 return windowHandle;
4090 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004091 }
4092 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004093 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004094}
4095
Vishnu Nairad321cd2020-08-20 16:40:21 -07004096sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(const sp<IBinder>& windowHandleToken,
4097 int displayId) const {
4098 if (windowHandleToken == nullptr) {
4099 return nullptr;
4100 }
4101
4102 for (const sp<InputWindowHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
4103 if (windowHandle->getToken() == windowHandleToken) {
4104 return windowHandle;
4105 }
4106 }
4107 return nullptr;
4108}
4109
4110sp<InputWindowHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
4111 sp<IBinder> focusedToken = getValueByKey(mFocusedWindowTokenByDisplay, displayId);
4112 return getWindowHandleLocked(focusedToken, displayId);
4113}
4114
Mady Mellor017bcd12020-06-23 19:12:00 +00004115bool InputDispatcher::hasWindowHandleLocked(const sp<InputWindowHandle>& windowHandle) const {
4116 for (auto& it : mWindowHandlesByDisplay) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004117 const std::vector<sp<InputWindowHandle>>& windowHandles = it.second;
Mady Mellor017bcd12020-06-23 19:12:00 +00004118 for (const sp<InputWindowHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08004119 if (handle->getId() == windowHandle->getId() &&
4120 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004121 if (windowHandle->getInfo()->displayId != it.first) {
4122 ALOGE("Found window %s in display %" PRId32
4123 ", but it should belong to display %" PRId32,
4124 windowHandle->getName().c_str(), it.first,
4125 windowHandle->getInfo()->displayId);
4126 }
4127 return true;
Arthur Hungb92218b2018-08-14 12:00:21 +08004128 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004129 }
4130 }
4131 return false;
4132}
4133
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004134bool InputDispatcher::hasResponsiveConnectionLocked(InputWindowHandle& windowHandle) const {
4135 sp<Connection> connection = getConnectionLocked(windowHandle.getToken());
4136 const bool noInputChannel =
4137 windowHandle.getInfo()->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
4138 if (connection != nullptr && noInputChannel) {
4139 ALOGW("%s has feature NO_INPUT_CHANNEL, but it matched to connection %s",
4140 windowHandle.getName().c_str(), connection->inputChannel->getName().c_str());
4141 return false;
4142 }
4143
4144 if (connection == nullptr) {
4145 if (!noInputChannel) {
4146 ALOGI("Could not find connection for %s", windowHandle.getName().c_str());
4147 }
4148 return false;
4149 }
4150 if (!connection->responsive) {
4151 ALOGW("Window %s is not responsive", windowHandle.getName().c_str());
4152 return false;
4153 }
4154 return true;
4155}
4156
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004157std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
4158 const sp<IBinder>& token) const {
Robert Carr5c8a0262018-10-03 16:30:44 -07004159 size_t count = mInputChannelsByToken.count(token);
4160 if (count == 0) {
4161 return nullptr;
4162 }
4163 return mInputChannelsByToken.at(token);
4164}
4165
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004166void InputDispatcher::updateWindowHandlesForDisplayLocked(
4167 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
4168 if (inputWindowHandles.empty()) {
4169 // Remove all handles on a display if there are no windows left.
4170 mWindowHandlesByDisplay.erase(displayId);
4171 return;
4172 }
4173
4174 // Since we compare the pointer of input window handles across window updates, we need
4175 // to make sure the handle object for the same window stays unchanged across updates.
4176 const std::vector<sp<InputWindowHandle>>& oldHandles = getWindowHandlesLocked(displayId);
chaviwaf87b3e2019-10-01 16:59:28 -07004177 std::unordered_map<int32_t /*id*/, sp<InputWindowHandle>> oldHandlesById;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004178 for (const sp<InputWindowHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07004179 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004180 }
4181
4182 std::vector<sp<InputWindowHandle>> newHandles;
4183 for (const sp<InputWindowHandle>& handle : inputWindowHandles) {
4184 if (!handle->updateInfo()) {
4185 // handle no longer valid
4186 continue;
4187 }
4188
4189 const InputWindowInfo* info = handle->getInfo();
4190 if ((getInputChannelLocked(handle->getToken()) == nullptr &&
4191 info->portalToDisplayId == ADISPLAY_ID_NONE)) {
4192 const bool noInputChannel =
Michael Wright44753b12020-07-08 13:48:11 +01004193 info->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
4194 const bool canReceiveInput = !info->flags.test(InputWindowInfo::Flag::NOT_TOUCHABLE) ||
4195 !info->flags.test(InputWindowInfo::Flag::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004196 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07004197 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004198 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07004199 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004200 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004201 }
4202
4203 if (info->displayId != displayId) {
4204 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
4205 handle->getName().c_str(), displayId, info->displayId);
4206 continue;
4207 }
4208
Robert Carredd13602020-04-13 17:24:34 -07004209 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
4210 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviwaf87b3e2019-10-01 16:59:28 -07004211 const sp<InputWindowHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004212 oldHandle->updateFrom(handle);
4213 newHandles.push_back(oldHandle);
4214 } else {
4215 newHandles.push_back(handle);
4216 }
4217 }
4218
4219 // Insert or replace
4220 mWindowHandlesByDisplay[displayId] = newHandles;
4221}
4222
Arthur Hung72d8dc32020-03-28 00:48:39 +00004223void InputDispatcher::setInputWindows(
4224 const std::unordered_map<int32_t, std::vector<sp<InputWindowHandle>>>& handlesPerDisplay) {
4225 { // acquire lock
4226 std::scoped_lock _l(mLock);
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004227 for (const auto& [displayId, handles] : handlesPerDisplay) {
4228 setInputWindowsLocked(handles, displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004229 }
4230 }
4231 // Wake up poll loop since it may need to make new input dispatching choices.
4232 mLooper->wake();
4233}
4234
Arthur Hungb92218b2018-08-14 12:00:21 +08004235/**
4236 * Called from InputManagerService, update window handle list by displayId that can receive input.
4237 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
4238 * If set an empty list, remove all handles from the specific display.
4239 * For focused handle, check if need to change and send a cancel event to previous one.
4240 * For removed handle, check if need to send a cancel event if already in touch.
4241 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00004242void InputDispatcher::setInputWindowsLocked(
4243 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004244 if (DEBUG_FOCUS) {
4245 std::string windowList;
4246 for (const sp<InputWindowHandle>& iwh : inputWindowHandles) {
4247 windowList += iwh->getName() + " ";
4248 }
4249 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
4250 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004251
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004252 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
4253 for (const sp<InputWindowHandle>& window : inputWindowHandles) {
4254 const bool noInputWindow =
4255 window->getInfo()->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
4256 if (noInputWindow && window->getToken() != nullptr) {
4257 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
4258 window->getName().c_str());
4259 window->releaseChannel();
4260 }
4261 }
4262
Arthur Hung72d8dc32020-03-28 00:48:39 +00004263 // Copy old handles for release if they are no longer present.
4264 const std::vector<sp<InputWindowHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004265
Arthur Hung72d8dc32020-03-28 00:48:39 +00004266 updateWindowHandlesForDisplayLocked(inputWindowHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004267
Vishnu Nair958da932020-08-21 17:12:37 -07004268 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
4269 if (mLastHoverWindowHandle &&
4270 std::find(windowHandles.begin(), windowHandles.end(), mLastHoverWindowHandle) ==
4271 windowHandles.end()) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004272 mLastHoverWindowHandle = nullptr;
4273 }
4274
Vishnu Nair958da932020-08-21 17:12:37 -07004275 sp<IBinder> focusedToken = getValueByKey(mFocusedWindowTokenByDisplay, displayId);
4276 if (focusedToken) {
4277 FocusResult result = checkTokenFocusableLocked(focusedToken, displayId);
4278 if (result != FocusResult::OK) {
4279 onFocusChangedLocked(focusedToken, nullptr, displayId, typeToString(result));
4280 }
4281 }
4282
4283 std::optional<FocusRequest> focusRequest =
4284 getOptionalValueByKey(mPendingFocusRequests, displayId);
4285 if (focusRequest) {
4286 // If the window from the pending request is now visible, provide it focus.
4287 FocusResult result = handleFocusRequestLocked(*focusRequest);
4288 if (result != FocusResult::NOT_VISIBLE) {
4289 // Drop the request if we were able to change the focus or we cannot change
4290 // it for another reason.
4291 mPendingFocusRequests.erase(displayId);
4292 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004293 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004294
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004295 std::unordered_map<int32_t, TouchState>::iterator stateIt =
4296 mTouchStatesByDisplay.find(displayId);
4297 if (stateIt != mTouchStatesByDisplay.end()) {
4298 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00004299 for (size_t i = 0; i < state.windows.size();) {
4300 TouchedWindow& touchedWindow = state.windows[i];
Mady Mellor017bcd12020-06-23 19:12:00 +00004301 if (!hasWindowHandleLocked(touchedWindow.windowHandle)) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004302 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004303 ALOGD("Touched window was removed: %s in display %" PRId32,
4304 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004305 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004306 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00004307 getInputChannelLocked(touchedWindow.windowHandle->getToken());
4308 if (touchedInputChannel != nullptr) {
4309 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4310 "touched window was removed");
4311 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004312 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004313 state.windows.erase(state.windows.begin() + i);
4314 } else {
4315 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004316 }
4317 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004318 }
Arthur Hung25e2af12020-03-26 12:58:37 +00004319
Arthur Hung72d8dc32020-03-28 00:48:39 +00004320 // Release information for windows that are no longer present.
4321 // This ensures that unused input channels are released promptly.
4322 // Otherwise, they might stick around until the window handle is destroyed
4323 // which might not happen until the next GC.
4324 for (const sp<InputWindowHandle>& oldWindowHandle : oldWindowHandles) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004325 if (!hasWindowHandleLocked(oldWindowHandle)) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004326 if (DEBUG_FOCUS) {
4327 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00004328 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004329 oldWindowHandle->releaseChannel();
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004330 // To avoid making too many calls into the compat framework, only
4331 // check for window flags when windows are going away.
4332 // TODO(b/157929241) : delete this. This is only needed temporarily
4333 // in order to gather some data about the flag usage
4334 if (oldWindowHandle->getInfo()->flags.test(InputWindowInfo::Flag::SLIPPERY)) {
4335 ALOGW("%s has FLAG_SLIPPERY. Please report this in b/157929241",
4336 oldWindowHandle->getName().c_str());
4337 if (mCompatService != nullptr) {
4338 mCompatService->reportChangeByUid(IInputConstants::BLOCK_FLAG_SLIPPERY,
4339 oldWindowHandle->getInfo()->ownerUid);
4340 }
4341 }
Arthur Hung25e2af12020-03-26 12:58:37 +00004342 }
chaviw291d88a2019-02-14 10:33:58 -08004343 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004344}
4345
4346void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07004347 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004348 if (DEBUG_FOCUS) {
4349 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
4350 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
4351 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004352 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004353 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004354
Chris Yea209fde2020-07-22 13:54:51 -07004355 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08004356 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004357
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004358 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
4359 return; // This application is already focused. No need to wake up or change anything.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004360 }
4361
Chris Yea209fde2020-07-22 13:54:51 -07004362 // Set the new application handle.
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004363 if (inputApplicationHandle != nullptr) {
4364 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
4365 } else {
4366 mFocusedApplicationHandlesByDisplay.erase(displayId);
4367 }
4368
4369 // No matter what the old focused application was, stop waiting on it because it is
4370 // no longer focused.
4371 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004372 } // release lock
4373
4374 // Wake up poll loop since it may need to make new input dispatching choices.
4375 mLooper->wake();
4376}
4377
Tiger Huang721e26f2018-07-24 22:26:19 +08004378/**
4379 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
4380 * the display not specified.
4381 *
4382 * We track any unreleased events for each window. If a window loses the ability to receive the
4383 * released event, we will send a cancel event to it. So when the focused display is changed, we
4384 * cancel all the unreleased display-unspecified events for the focused window on the old focused
4385 * display. The display-specified events won't be affected.
4386 */
4387void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004388 if (DEBUG_FOCUS) {
4389 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
4390 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004391 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004392 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08004393
4394 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004395 sp<IBinder> oldFocusedWindowToken =
4396 getValueByKey(mFocusedWindowTokenByDisplay, mFocusedDisplayId);
4397 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004398 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07004399 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08004400 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004401 CancelationOptions
4402 options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
4403 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004404 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08004405 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
4406 }
4407 }
4408 mFocusedDisplayId = displayId;
4409
Chris Ye3c2d6f52020-08-09 10:39:48 -07004410 // Find new focused window and validate
Vishnu Nairad321cd2020-08-20 16:40:21 -07004411 sp<IBinder> newFocusedWindowToken =
4412 getValueByKey(mFocusedWindowTokenByDisplay, displayId);
4413 notifyFocusChangedLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08004414
Vishnu Nairad321cd2020-08-20 16:40:21 -07004415 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08004416 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07004417 if (!mFocusedWindowTokenByDisplay.empty()) {
4418 ALOGE("But another display has a focused window\n%s",
4419 dumpFocusedWindowsLocked().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08004420 }
4421 }
4422 }
4423
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004424 if (DEBUG_FOCUS) {
4425 logDispatchStateLocked();
4426 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004427 } // release lock
4428
4429 // Wake up poll loop since it may need to make new input dispatching choices.
4430 mLooper->wake();
4431}
4432
Michael Wrightd02c5b62014-02-10 15:10:22 -08004433void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004434 if (DEBUG_FOCUS) {
4435 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
4436 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004437
4438 bool changed;
4439 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004440 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004441
4442 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
4443 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004444 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004445 }
4446
4447 if (mDispatchEnabled && !enabled) {
4448 resetAndDropEverythingLocked("dispatcher is being disabled");
4449 }
4450
4451 mDispatchEnabled = enabled;
4452 mDispatchFrozen = frozen;
4453 changed = true;
4454 } else {
4455 changed = false;
4456 }
4457
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004458 if (DEBUG_FOCUS) {
4459 logDispatchStateLocked();
4460 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004461 } // release lock
4462
4463 if (changed) {
4464 // Wake up poll loop since it may need to make new input dispatching choices.
4465 mLooper->wake();
4466 }
4467}
4468
4469void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004470 if (DEBUG_FOCUS) {
4471 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
4472 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004473
4474 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004475 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004476
4477 if (mInputFilterEnabled == enabled) {
4478 return;
4479 }
4480
4481 mInputFilterEnabled = enabled;
4482 resetAndDropEverythingLocked("input filter is being enabled or disabled");
4483 } // release lock
4484
4485 // Wake up poll loop since there might be work to do to drop everything.
4486 mLooper->wake();
4487}
4488
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08004489void InputDispatcher::setInTouchMode(bool inTouchMode) {
4490 std::scoped_lock lock(mLock);
4491 mInTouchMode = inTouchMode;
4492}
4493
Bernardo Rufinoea97d182020-08-19 14:43:14 +01004494void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
4495 if (opacity < 0 || opacity > 1) {
4496 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
4497 return;
4498 }
4499
4500 std::scoped_lock lock(mLock);
4501 mMaximumObscuringOpacityForTouch = opacity;
4502}
4503
4504void InputDispatcher::setBlockUntrustedTouchesMode(BlockUntrustedTouchesMode mode) {
4505 std::scoped_lock lock(mLock);
4506 mBlockUntrustedTouchesMode = mode;
4507}
4508
chaviwfbe5d9c2018-12-26 12:23:37 -08004509bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken) {
4510 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004511 if (DEBUG_FOCUS) {
4512 ALOGD("Trivial transfer to same window.");
4513 }
chaviwfbe5d9c2018-12-26 12:23:37 -08004514 return true;
4515 }
4516
Michael Wrightd02c5b62014-02-10 15:10:22 -08004517 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004518 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004519
chaviwfbe5d9c2018-12-26 12:23:37 -08004520 sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromToken);
4521 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toToken);
Yi Kong9b14ac62018-07-17 13:48:38 -07004522 if (fromWindowHandle == nullptr || toWindowHandle == nullptr) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004523 ALOGW("Cannot transfer focus because from or to window not found.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004524 return false;
4525 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004526 if (DEBUG_FOCUS) {
4527 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
4528 fromWindowHandle->getName().c_str(), toWindowHandle->getName().c_str());
4529 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004530 if (fromWindowHandle->getInfo()->displayId != toWindowHandle->getInfo()->displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004531 if (DEBUG_FOCUS) {
4532 ALOGD("Cannot transfer focus because windows are on different displays.");
4533 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004534 return false;
4535 }
4536
4537 bool found = false;
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004538 for (std::pair<const int32_t, TouchState>& pair : mTouchStatesByDisplay) {
4539 TouchState& state = pair.second;
Jeff Brownf086ddb2014-02-11 14:28:48 -08004540 for (size_t i = 0; i < state.windows.size(); i++) {
4541 const TouchedWindow& touchedWindow = state.windows[i];
4542 if (touchedWindow.windowHandle == fromWindowHandle) {
4543 int32_t oldTargetFlags = touchedWindow.targetFlags;
4544 BitSet32 pointerIds = touchedWindow.pointerIds;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004545
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004546 state.windows.erase(state.windows.begin() + i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004547
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004548 int32_t newTargetFlags = oldTargetFlags &
4549 (InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_SPLIT |
4550 InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004551 state.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004552
Jeff Brownf086ddb2014-02-11 14:28:48 -08004553 found = true;
4554 goto Found;
4555 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004556 }
4557 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004558 Found:
Michael Wrightd02c5b62014-02-10 15:10:22 -08004559
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004560 if (!found) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004561 if (DEBUG_FOCUS) {
4562 ALOGD("Focus transfer failed because from window did not have focus.");
4563 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004564 return false;
4565 }
4566
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004567 sp<Connection> fromConnection = getConnectionLocked(fromToken);
4568 sp<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004569 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004570 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004571 CancelationOptions
4572 options(CancelationOptions::CANCEL_POINTER_EVENTS,
4573 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004574 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004575 synthesizePointerDownEventsForConnectionLocked(toConnection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004576 }
4577
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004578 if (DEBUG_FOCUS) {
4579 logDispatchStateLocked();
4580 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004581 } // release lock
4582
4583 // Wake up poll loop since it may need to make new input dispatching choices.
4584 mLooper->wake();
4585 return true;
4586}
4587
4588void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004589 if (DEBUG_FOCUS) {
4590 ALOGD("Resetting and dropping all events (%s).", reason);
4591 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004592
4593 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
4594 synthesizeCancelationEventsForAllConnectionsLocked(options);
4595
4596 resetKeyRepeatLocked();
4597 releasePendingEventLocked();
4598 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004599 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004600
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004601 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08004602 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004603 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07004604 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004605}
4606
4607void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004608 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004609 dumpDispatchStateLocked(dump);
4610
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004611 std::istringstream stream(dump);
4612 std::string line;
4613
4614 while (std::getline(stream, line, '\n')) {
4615 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004616 }
4617}
4618
Vishnu Nairad321cd2020-08-20 16:40:21 -07004619std::string InputDispatcher::dumpFocusedWindowsLocked() {
4620 if (mFocusedWindowTokenByDisplay.empty()) {
4621 return INDENT "FocusedWindows: <none>\n";
4622 }
4623
4624 std::string dump;
4625 dump += INDENT "FocusedWindows:\n";
4626 for (auto& it : mFocusedWindowTokenByDisplay) {
4627 const int32_t displayId = it.first;
4628 const sp<InputWindowHandle> windowHandle = getFocusedWindowHandleLocked(displayId);
4629 if (windowHandle) {
4630 dump += StringPrintf(INDENT2 "displayId=%" PRId32 ", name='%s'\n", displayId,
4631 windowHandle->getName().c_str());
4632 } else {
4633 dump += StringPrintf(INDENT2 "displayId=%" PRId32
4634 " has focused token without a window'\n",
4635 displayId);
4636 }
4637 }
4638 return dump;
4639}
4640
Siarhei Vishniakouad991402020-10-28 11:40:09 -05004641std::string InputDispatcher::dumpPendingFocusRequestsLocked() {
4642 if (mPendingFocusRequests.empty()) {
4643 return INDENT "mPendingFocusRequests: <none>\n";
4644 }
4645
4646 std::string dump;
4647 dump += INDENT "mPendingFocusRequests:\n";
4648 for (const auto& [displayId, focusRequest] : mPendingFocusRequests) {
4649 // Rather than printing raw values for focusRequest.token and focusRequest.focusedToken,
4650 // try to resolve them to actual windows.
4651 std::string windowName = getConnectionNameLocked(focusRequest.token);
4652 std::string focusedWindowName = getConnectionNameLocked(focusRequest.focusedToken);
4653 dump += StringPrintf(INDENT2 "displayId=%" PRId32 ", token->%s, focusedToken->%s\n",
4654 displayId, windowName.c_str(), focusedWindowName.c_str());
4655 }
4656 return dump;
4657}
4658
Prabir Pradhan99987712020-11-10 18:43:05 -08004659std::string InputDispatcher::dumpPointerCaptureStateLocked() {
4660 std::string dump;
4661
4662 dump += StringPrintf(INDENT "FocusedWindowRequestedPointerCapture: %s\n",
4663 toString(mFocusedWindowRequestedPointerCapture));
4664
4665 std::string windowName = "None";
4666 if (mWindowTokenWithPointerCapture) {
4667 const sp<InputWindowHandle> captureWindowHandle =
4668 getWindowHandleLocked(mWindowTokenWithPointerCapture);
4669 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
4670 : "token has capture without window";
4671 }
4672 dump += StringPrintf(INDENT "CurrentWindowWithPointerCapture: %s\n", windowName.c_str());
4673
4674 return dump;
4675}
4676
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004677void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07004678 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
4679 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
4680 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08004681 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004682
Tiger Huang721e26f2018-07-24 22:26:19 +08004683 if (!mFocusedApplicationHandlesByDisplay.empty()) {
4684 dump += StringPrintf(INDENT "FocusedApplications:\n");
4685 for (auto& it : mFocusedApplicationHandlesByDisplay) {
4686 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07004687 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05004688 const std::chrono::duration timeout =
4689 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004690 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004691 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05004692 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08004693 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004694 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08004695 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004696 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004697
Vishnu Nairad321cd2020-08-20 16:40:21 -07004698 dump += dumpFocusedWindowsLocked();
Siarhei Vishniakouad991402020-10-28 11:40:09 -05004699 dump += dumpPendingFocusRequestsLocked();
Prabir Pradhan99987712020-11-10 18:43:05 -08004700 dump += dumpPointerCaptureStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004701
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004702 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004703 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004704 for (const std::pair<int32_t, TouchState>& pair : mTouchStatesByDisplay) {
4705 const TouchState& state = pair.second;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004706 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004707 state.displayId, toString(state.down), toString(state.split),
4708 state.deviceId, state.source);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004709 if (!state.windows.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004710 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004711 for (size_t i = 0; i < state.windows.size(); i++) {
4712 const TouchedWindow& touchedWindow = state.windows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004713 dump += StringPrintf(INDENT4
4714 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
4715 i, touchedWindow.windowHandle->getName().c_str(),
4716 touchedWindow.pointerIds.value, touchedWindow.targetFlags);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004717 }
4718 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004719 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004720 }
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004721 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004722 dump += INDENT3 "Portal windows:\n";
4723 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004724 const sp<InputWindowHandle> portalWindowHandle = state.portalWindows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004725 dump += StringPrintf(INDENT4 "%zu: name='%s'\n", i,
4726 portalWindowHandle->getName().c_str());
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004727 }
4728 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004729 }
4730 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004731 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004732 }
4733
Arthur Hungb92218b2018-08-14 12:00:21 +08004734 if (!mWindowHandlesByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004735 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004736 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
Arthur Hung3b413f22018-10-26 18:05:34 +08004737 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", it.first);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004738 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004739 dump += INDENT2 "Windows:\n";
4740 for (size_t i = 0; i < windowHandles.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004741 const sp<InputWindowHandle>& windowHandle = windowHandles[i];
Arthur Hungb92218b2018-08-14 12:00:21 +08004742 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004743
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00004744 dump += StringPrintf(INDENT3 "%zu: name='%s', id=%" PRId32 ", displayId=%d, "
Vishnu Nair47074b82020-08-14 11:54:47 -07004745 "portalToDisplayId=%d, paused=%s, focusable=%s, "
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00004746 "hasWallpaper=%s, visible=%s, alpha=%.2f, "
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00004747 "flags=%s, type=%s, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004748 "frame=[%d,%d][%d,%d], globalScale=%f, "
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004749 "applicationInfo=%s, "
chaviw1ff3d1e2020-07-01 15:53:47 -07004750 "touchableRegion=",
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00004751 i, windowInfo->name.c_str(), windowInfo->id,
4752 windowInfo->displayId, windowInfo->portalToDisplayId,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004753 toString(windowInfo->paused),
Vishnu Nair47074b82020-08-14 11:54:47 -07004754 toString(windowInfo->focusable),
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004755 toString(windowInfo->hasWallpaper),
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00004756 toString(windowInfo->visible), windowInfo->alpha,
Michael Wright8759d672020-07-21 00:46:45 +01004757 windowInfo->flags.string().c_str(),
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00004758 NamedEnum::string(windowInfo->type).c_str(),
Michael Wright44753b12020-07-08 13:48:11 +01004759 windowInfo->frameLeft, windowInfo->frameTop,
4760 windowInfo->frameRight, windowInfo->frameBottom,
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004761 windowInfo->globalScaleFactor,
4762 windowInfo->applicationInfo.name.c_str());
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00004763 dump += dumpRegion(windowInfo->touchableRegion);
Michael Wright44753b12020-07-08 13:48:11 +01004764 dump += StringPrintf(", inputFeatures=%s",
4765 windowInfo->inputFeatures.string().c_str());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004766 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%" PRId64
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00004767 "ms, trustedOverlay=%s, hasToken=%s, "
4768 "touchOcclusionMode=%s\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004769 windowInfo->ownerPid, windowInfo->ownerUid,
Bernardo Rufinoc2f1fad2020-11-04 17:30:57 +00004770 millis(windowInfo->dispatchingTimeout),
4771 toString(windowInfo->trustedOverlay),
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00004772 toString(windowInfo->token != nullptr),
4773 toString(windowInfo->touchOcclusionMode).c_str());
chaviw85b44202020-07-24 11:46:21 -07004774 windowInfo->transform.dump(dump, "transform", INDENT4);
Arthur Hungb92218b2018-08-14 12:00:21 +08004775 }
4776 } else {
4777 dump += INDENT2 "Windows: <none>\n";
4778 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004779 }
4780 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08004781 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004782 }
4783
Michael Wright3dd60e22019-03-27 22:06:44 +00004784 if (!mGlobalMonitorsByDisplay.empty() || !mGestureMonitorsByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004785 for (auto& it : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004786 const std::vector<Monitor>& monitors = it.second;
4787 dump += StringPrintf(INDENT "Global monitors in display %" PRId32 ":\n", it.first);
4788 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004789 }
4790 for (auto& it : mGestureMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004791 const std::vector<Monitor>& monitors = it.second;
4792 dump += StringPrintf(INDENT "Gesture monitors in display %" PRId32 ":\n", it.first);
4793 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004794 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004795 } else {
Michael Wright3dd60e22019-03-27 22:06:44 +00004796 dump += INDENT "Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004797 }
4798
4799 nsecs_t currentTime = now();
4800
4801 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004802 if (!mRecentQueue.empty()) {
4803 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004804 for (std::shared_ptr<EventEntry>& entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004805 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05004806 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004807 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004808 }
4809 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004810 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004811 }
4812
4813 // Dump event currently being dispatched.
4814 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004815 dump += INDENT "PendingEvent:\n";
4816 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05004817 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004818 dump += StringPrintf(", age=%" PRId64 "ms\n",
4819 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004820 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004821 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004822 }
4823
4824 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004825 if (!mInboundQueue.empty()) {
4826 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004827 for (std::shared_ptr<EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004828 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05004829 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004830 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004831 }
4832 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004833 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004834 }
4835
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004836 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004837 dump += INDENT "ReplacedKeys:\n";
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004838 for (const std::pair<KeyReplacement, int32_t>& pair : mReplacedKeys) {
4839 const KeyReplacement& replacement = pair.first;
4840 int32_t newKeyCode = pair.second;
4841 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004842 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07004843 }
4844 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004845 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07004846 }
4847
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004848 if (!mConnectionsByFd.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004849 dump += INDENT "Connections:\n";
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004850 for (const auto& pair : mConnectionsByFd) {
4851 const sp<Connection>& connection = pair.second;
4852 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004853 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004854 pair.first, connection->getInputChannelName().c_str(),
4855 connection->getWindowName().c_str(), connection->getStatusLabel(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004856 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004857
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004858 if (!connection->outboundQueue.empty()) {
4859 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
4860 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05004861 dump += dumpQueue(connection->outboundQueue, currentTime);
4862
Michael Wrightd02c5b62014-02-10 15:10:22 -08004863 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004864 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004865 }
4866
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004867 if (!connection->waitQueue.empty()) {
4868 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
4869 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05004870 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004871 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004872 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004873 }
4874 }
4875 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004876 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004877 }
4878
4879 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004880 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
4881 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004882 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004883 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004884 }
4885
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004886 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004887 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
4888 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
4889 ns2ms(mConfig.keyRepeatTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004890}
4891
Michael Wright3dd60e22019-03-27 22:06:44 +00004892void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
4893 const size_t numMonitors = monitors.size();
4894 for (size_t i = 0; i < numMonitors; i++) {
4895 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004896 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00004897 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
4898 dump += "\n";
4899 }
4900}
4901
Garfield Tan15601662020-09-22 15:32:38 -07004902base::Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(
4903 const std::string& name) {
4904#if DEBUG_CHANNEL_CREATION
4905 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004906#endif
4907
Garfield Tan15601662020-09-22 15:32:38 -07004908 std::shared_ptr<InputChannel> serverChannel;
4909 std::unique_ptr<InputChannel> clientChannel;
4910 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
4911
4912 if (result) {
4913 return base::Error(result) << "Failed to open input channel pair with name " << name;
4914 }
4915
Michael Wrightd02c5b62014-02-10 15:10:22 -08004916 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004917 std::scoped_lock _l(mLock);
Garfield Tan15601662020-09-22 15:32:38 -07004918 sp<Connection> connection = new Connection(serverChannel, false /*monitor*/, mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004919
Garfield Tan15601662020-09-22 15:32:38 -07004920 int fd = serverChannel->getFd();
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004921 mConnectionsByFd[fd] = connection;
Garfield Tan15601662020-09-22 15:32:38 -07004922 mInputChannelsByToken[serverChannel->getConnectionToken()] = serverChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004923
Michael Wrightd02c5b62014-02-10 15:10:22 -08004924 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
4925 } // release lock
4926
4927 // Wake the looper because some connections have changed.
4928 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07004929 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004930}
4931
Garfield Tan15601662020-09-22 15:32:38 -07004932base::Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(
4933 int32_t displayId, bool isGestureMonitor, const std::string& name) {
4934 std::shared_ptr<InputChannel> serverChannel;
4935 std::unique_ptr<InputChannel> clientChannel;
4936 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
4937 if (result) {
4938 return base::Error(result) << "Failed to open input channel pair with name " << name;
4939 }
4940
Michael Wright3dd60e22019-03-27 22:06:44 +00004941 { // acquire lock
4942 std::scoped_lock _l(mLock);
4943
4944 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07004945 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
4946 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00004947 }
4948
Garfield Tan15601662020-09-22 15:32:38 -07004949 sp<Connection> connection = new Connection(serverChannel, true /*monitor*/, mIdGenerator);
Michael Wright3dd60e22019-03-27 22:06:44 +00004950
Garfield Tan15601662020-09-22 15:32:38 -07004951 const int fd = serverChannel->getFd();
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004952 mConnectionsByFd[fd] = connection;
Garfield Tan15601662020-09-22 15:32:38 -07004953 mInputChannelsByToken[serverChannel->getConnectionToken()] = serverChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00004954
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004955 auto& monitorsByDisplay =
4956 isGestureMonitor ? mGestureMonitorsByDisplay : mGlobalMonitorsByDisplay;
Garfield Tan15601662020-09-22 15:32:38 -07004957 monitorsByDisplay[displayId].emplace_back(serverChannel);
Michael Wright3dd60e22019-03-27 22:06:44 +00004958
4959 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
Michael Wright3dd60e22019-03-27 22:06:44 +00004960 }
Garfield Tan15601662020-09-22 15:32:38 -07004961
Michael Wright3dd60e22019-03-27 22:06:44 +00004962 // Wake the looper because some connections have changed.
4963 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07004964 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00004965}
4966
Garfield Tan15601662020-09-22 15:32:38 -07004967status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004968 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004969 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004970
Garfield Tan15601662020-09-22 15:32:38 -07004971 status_t status = removeInputChannelLocked(connectionToken, false /*notify*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004972 if (status) {
4973 return status;
4974 }
4975 } // release lock
4976
4977 // Wake the poll loop because removing the connection may have changed the current
4978 // synchronization state.
4979 mLooper->wake();
4980 return OK;
4981}
4982
Garfield Tan15601662020-09-22 15:32:38 -07004983status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
4984 bool notify) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004985 sp<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004986 if (connection == nullptr) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004987 ALOGW("Attempted to unregister already unregistered input channel");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004988 return BAD_VALUE;
4989 }
4990
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004991 removeConnectionLocked(connection);
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004992 mInputChannelsByToken.erase(connectionToken);
Robert Carr5c8a0262018-10-03 16:30:44 -07004993
Michael Wrightd02c5b62014-02-10 15:10:22 -08004994 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004995 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004996 }
4997
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004998 mLooper->removeFd(connection->inputChannel->getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004999
5000 nsecs_t currentTime = now();
5001 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
5002
5003 connection->status = Connection::STATUS_ZOMBIE;
5004 return OK;
5005}
5006
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005007void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
5008 removeMonitorChannelLocked(connectionToken, mGlobalMonitorsByDisplay);
5009 removeMonitorChannelLocked(connectionToken, mGestureMonitorsByDisplay);
Michael Wright3dd60e22019-03-27 22:06:44 +00005010}
5011
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005012void InputDispatcher::removeMonitorChannelLocked(
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005013 const sp<IBinder>& connectionToken,
Michael Wright3dd60e22019-03-27 22:06:44 +00005014 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005015 for (auto it = monitorsByDisplay.begin(); it != monitorsByDisplay.end();) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005016 std::vector<Monitor>& monitors = it->second;
5017 const size_t numMonitors = monitors.size();
5018 for (size_t i = 0; i < numMonitors; i++) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005019 if (monitors[i].inputChannel->getConnectionToken() == connectionToken) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005020 monitors.erase(monitors.begin() + i);
5021 break;
5022 }
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005023 }
Michael Wright3dd60e22019-03-27 22:06:44 +00005024 if (monitors.empty()) {
5025 it = monitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005026 } else {
5027 ++it;
5028 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005029 }
5030}
5031
Michael Wright3dd60e22019-03-27 22:06:44 +00005032status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
5033 { // acquire lock
5034 std::scoped_lock _l(mLock);
5035 std::optional<int32_t> foundDisplayId = findGestureMonitorDisplayByTokenLocked(token);
5036
5037 if (!foundDisplayId) {
5038 ALOGW("Attempted to pilfer pointers from an un-registered monitor or invalid token");
5039 return BAD_VALUE;
5040 }
5041 int32_t displayId = foundDisplayId.value();
5042
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005043 std::unordered_map<int32_t, TouchState>::iterator stateIt =
5044 mTouchStatesByDisplay.find(displayId);
5045 if (stateIt == mTouchStatesByDisplay.end()) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005046 ALOGW("Failed to pilfer pointers: no pointers on display %" PRId32 ".", displayId);
5047 return BAD_VALUE;
5048 }
5049
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005050 TouchState& state = stateIt->second;
Michael Wright3dd60e22019-03-27 22:06:44 +00005051 std::optional<int32_t> foundDeviceId;
5052 for (const TouchedMonitor& touchedMonitor : state.gestureMonitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005053 if (touchedMonitor.monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005054 foundDeviceId = state.deviceId;
5055 }
5056 }
5057 if (!foundDeviceId || !state.down) {
5058 ALOGW("Attempted to pilfer points from a monitor without any on-going pointer streams."
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005059 " Ignoring.");
Michael Wright3dd60e22019-03-27 22:06:44 +00005060 return BAD_VALUE;
5061 }
5062 int32_t deviceId = foundDeviceId.value();
5063
5064 // Send cancel events to all the input channels we're stealing from.
5065 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005066 "gesture monitor stole pointer stream");
Michael Wright3dd60e22019-03-27 22:06:44 +00005067 options.deviceId = deviceId;
5068 options.displayId = displayId;
5069 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005070 std::shared_ptr<InputChannel> channel =
5071 getInputChannelLocked(window.windowHandle->getToken());
Michael Wright3a240c42019-12-10 20:53:41 +00005072 if (channel != nullptr) {
5073 synthesizeCancelationEventsForInputChannelLocked(channel, options);
5074 }
Michael Wright3dd60e22019-03-27 22:06:44 +00005075 }
5076 // Then clear the current touch state so we stop dispatching to them as well.
5077 state.filterNonMonitors();
5078 }
5079 return OK;
5080}
5081
Prabir Pradhan99987712020-11-10 18:43:05 -08005082void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
5083 { // acquire lock
5084 std::scoped_lock _l(mLock);
5085 if (DEBUG_FOCUS) {
5086 const sp<InputWindowHandle> windowHandle = getWindowHandleLocked(windowToken);
5087 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
5088 windowHandle != nullptr ? windowHandle->getName().c_str()
5089 : "token without window");
5090 }
5091
5092 const sp<IBinder> focusedToken =
5093 getValueByKey(mFocusedWindowTokenByDisplay, mFocusedDisplayId);
5094 if (focusedToken != windowToken) {
5095 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
5096 enabled ? "enable" : "disable");
5097 return;
5098 }
5099
5100 if (enabled == mFocusedWindowRequestedPointerCapture) {
5101 ALOGW("Ignoring request to %s Pointer Capture: "
5102 "window has %s requested pointer capture.",
5103 enabled ? "enable" : "disable", enabled ? "already" : "not");
5104 return;
5105 }
5106
5107 mFocusedWindowRequestedPointerCapture = enabled;
5108 setPointerCaptureLocked(enabled);
5109 } // release lock
5110
5111 // Wake the thread to process command entries.
5112 mLooper->wake();
5113}
5114
Michael Wright3dd60e22019-03-27 22:06:44 +00005115std::optional<int32_t> InputDispatcher::findGestureMonitorDisplayByTokenLocked(
5116 const sp<IBinder>& token) {
5117 for (const auto& it : mGestureMonitorsByDisplay) {
5118 const std::vector<Monitor>& monitors = it.second;
5119 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005120 if (monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005121 return it.first;
5122 }
5123 }
5124 }
5125 return std::nullopt;
5126}
5127
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005128sp<Connection> InputDispatcher::getConnectionLocked(const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005129 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005130 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08005131 }
5132
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005133 for (const auto& pair : mConnectionsByFd) {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005134 const sp<Connection>& connection = pair.second;
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005135 if (connection->inputChannel->getConnectionToken() == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005136 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005137 }
5138 }
Robert Carr4e670e52018-08-15 13:26:12 -07005139
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005140 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005141}
5142
Siarhei Vishniakouad991402020-10-28 11:40:09 -05005143std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
5144 sp<Connection> connection = getConnectionLocked(connectionToken);
5145 if (connection == nullptr) {
5146 return "<nullptr>";
5147 }
5148 return connection->getInputChannelName();
5149}
5150
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005151void InputDispatcher::removeConnectionLocked(const sp<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005152 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005153 removeByValue(mConnectionsByFd, connection);
5154}
5155
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005156void InputDispatcher::onDispatchCycleFinishedLocked(nsecs_t currentTime,
5157 const sp<Connection>& connection, uint32_t seq,
5158 bool handled) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005159 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5160 &InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005161 commandEntry->connection = connection;
5162 commandEntry->eventTime = currentTime;
5163 commandEntry->seq = seq;
5164 commandEntry->handled = handled;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005165 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005166}
5167
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005168void InputDispatcher::onDispatchCycleBrokenLocked(nsecs_t currentTime,
5169 const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005170 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005171 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005172
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005173 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5174 &InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005175 commandEntry->connection = connection;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005176 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005177}
5178
Vishnu Nairad321cd2020-08-20 16:40:21 -07005179void InputDispatcher::notifyFocusChangedLocked(const sp<IBinder>& oldToken,
5180 const sp<IBinder>& newToken) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005181 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5182 &InputDispatcher::doNotifyFocusChangedLockedInterruptible);
chaviw0c06c6e2019-01-09 13:27:07 -08005183 commandEntry->oldToken = oldToken;
5184 commandEntry->newToken = newToken;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005185 postCommandLocked(std::move(commandEntry));
Robert Carrf759f162018-11-13 12:57:11 -08005186}
5187
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -05005188void InputDispatcher::onAnrLocked(const Connection& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005189 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
5190 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -05005191 if (connection.waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005192 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -05005193 connection.inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005194 return;
5195 }
5196 /**
5197 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
5198 * may not be the one that caused the timeout to occur. One possibility is that window timeout
5199 * has changed. This could cause newer entries to time out before the already dispatched
5200 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
5201 * processes the events linearly. So providing information about the oldest entry seems to be
5202 * most useful.
5203 */
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -05005204 DispatchEntry* oldestEntry = *connection.waitQueue.begin();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005205 const nsecs_t currentWait = now() - oldestEntry->deliveryTime;
5206 std::string reason =
5207 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakoua72accd2020-09-22 21:43:09 -05005208 connection.inputChannel->getName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005209 ns2ms(currentWait),
5210 oldestEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06005211 sp<IBinder> connectionToken = connection.inputChannel->getConnectionToken();
5212 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005213
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005214 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5215 &InputDispatcher::doNotifyConnectionUnresponsiveLockedInterruptible);
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06005216 commandEntry->connectionToken = connectionToken;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005217 commandEntry->reason = std::move(reason);
5218 postCommandLocked(std::move(commandEntry));
5219}
5220
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005221void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
5222 std::string reason =
5223 StringPrintf("%s does not have a focused window", application->getName().c_str());
5224 updateLastAnrStateLocked(*application, reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005225
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005226 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5227 &InputDispatcher::doNotifyNoFocusedWindowAnrLockedInterruptible);
5228 commandEntry->inputApplicationHandle = std::move(application);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005229 postCommandLocked(std::move(commandEntry));
5230}
5231
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00005232void InputDispatcher::onUntrustedTouchLocked(const std::string& obscuringPackage) {
5233 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5234 &InputDispatcher::doNotifyUntrustedTouchLockedInterruptible);
5235 commandEntry->obscuringPackage = obscuringPackage;
5236 postCommandLocked(std::move(commandEntry));
5237}
5238
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005239void InputDispatcher::updateLastAnrStateLocked(const sp<InputWindowHandle>& window,
5240 const std::string& reason) {
5241 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
5242 updateLastAnrStateLocked(windowLabel, reason);
5243}
5244
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005245void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
5246 const std::string& reason) {
5247 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005248 updateLastAnrStateLocked(windowLabel, reason);
5249}
5250
5251void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
5252 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005253 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07005254 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005255 struct tm tm;
5256 localtime_r(&t, &tm);
5257 char timestr[64];
5258 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005259 mLastAnrState.clear();
5260 mLastAnrState += INDENT "ANR:\n";
5261 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005262 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
5263 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005264 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005265}
5266
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005267void InputDispatcher::doNotifyConfigurationChangedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005268 mLock.unlock();
5269
5270 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
5271
5272 mLock.lock();
5273}
5274
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005275void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005276 sp<Connection> connection = commandEntry->connection;
5277
5278 if (connection->status != Connection::STATUS_ZOMBIE) {
5279 mLock.unlock();
5280
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005281 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005282
5283 mLock.lock();
5284 }
5285}
5286
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005287void InputDispatcher::doNotifyFocusChangedLockedInterruptible(CommandEntry* commandEntry) {
chaviw0c06c6e2019-01-09 13:27:07 -08005288 sp<IBinder> oldToken = commandEntry->oldToken;
5289 sp<IBinder> newToken = commandEntry->newToken;
Robert Carrf759f162018-11-13 12:57:11 -08005290 mLock.unlock();
chaviw0c06c6e2019-01-09 13:27:07 -08005291 mPolicy->notifyFocusChanged(oldToken, newToken);
Robert Carrf759f162018-11-13 12:57:11 -08005292 mLock.lock();
5293}
5294
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005295void InputDispatcher::doNotifyNoFocusedWindowAnrLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005296 mLock.unlock();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005297
5298 mPolicy->notifyNoFocusedWindowAnr(commandEntry->inputApplicationHandle);
5299
5300 mLock.lock();
5301}
5302
5303void InputDispatcher::doNotifyConnectionUnresponsiveLockedInterruptible(
5304 CommandEntry* commandEntry) {
5305 mLock.unlock();
5306
5307 mPolicy->notifyConnectionUnresponsive(commandEntry->connectionToken, commandEntry->reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005308
5309 mLock.lock();
5310
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005311 // stop waking up for events in this connection, it is already not responding
5312 sp<Connection> connection = getConnectionLocked(commandEntry->connectionToken);
5313 if (connection == nullptr) {
5314 return;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005315 }
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005316 cancelEventsForAnrLocked(connection);
5317}
5318
5319void InputDispatcher::doNotifyConnectionResponsiveLockedInterruptible(CommandEntry* commandEntry) {
5320 mLock.unlock();
5321
5322 mPolicy->notifyConnectionResponsive(commandEntry->connectionToken);
5323
5324 mLock.lock();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005325}
5326
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00005327void InputDispatcher::doNotifyUntrustedTouchLockedInterruptible(CommandEntry* commandEntry) {
5328 mLock.unlock();
5329
5330 mPolicy->notifyUntrustedTouch(commandEntry->obscuringPackage);
5331
5332 mLock.lock();
5333}
5334
Michael Wrightd02c5b62014-02-10 15:10:22 -08005335void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
5336 CommandEntry* commandEntry) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005337 KeyEntry& entry = *(commandEntry->keyEntry);
5338 KeyEvent event = createKeyEvent(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005339
5340 mLock.unlock();
5341
Michael Wright2b3c3302018-03-02 17:19:13 +00005342 android::base::Timer t;
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06005343 const sp<IBinder>& token = commandEntry->connectionToken;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005344 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(token, &event, entry.policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00005345 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
5346 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005347 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00005348 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005349
5350 mLock.lock();
5351
5352 if (delay < 0) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005353 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005354 } else if (!delay) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005355 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005356 } else {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005357 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
5358 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005359 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005360}
5361
chaviwfd6d3512019-03-25 13:23:49 -07005362void InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible(CommandEntry* commandEntry) {
5363 mLock.unlock();
5364 mPolicy->onPointerDownOutsideFocus(commandEntry->newToken);
5365 mLock.lock();
5366}
5367
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005368/**
5369 * Connection is responsive if it has no events in the waitQueue that are older than the
5370 * current time.
5371 */
5372static bool isConnectionResponsive(const Connection& connection) {
5373 const nsecs_t currentTime = now();
5374 for (const DispatchEntry* entry : connection.waitQueue) {
5375 if (entry->timeoutTime < currentTime) {
5376 return false;
5377 }
5378 }
5379 return true;
5380}
5381
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005382void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005383 sp<Connection> connection = commandEntry->connection;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005384 const nsecs_t finishTime = commandEntry->eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005385 uint32_t seq = commandEntry->seq;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005386 const bool handled = commandEntry->handled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005387
5388 // Handle post-event policy actions.
Garfield Tane84e6f92019-08-29 17:28:41 -07005389 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005390 if (dispatchEntryIt == connection->waitQueue.end()) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005391 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005392 }
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005393 DispatchEntry* dispatchEntry = *dispatchEntryIt;
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07005394 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005395 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005396 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
5397 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005398 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07005399 reportDispatchStatistics(std::chrono::nanoseconds(eventDuration), *connection, handled);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005400
5401 bool restartEvent;
Siarhei Vishniakou49483272019-10-22 13:13:47 -07005402 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005403 KeyEntry& keyEntry = static_cast<KeyEntry&>(*(dispatchEntry->eventEntry));
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005404 restartEvent =
5405 afterKeyEventLockedInterruptible(connection, dispatchEntry, keyEntry, handled);
Siarhei Vishniakou49483272019-10-22 13:13:47 -07005406 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005407 MotionEntry& motionEntry = static_cast<MotionEntry&>(*(dispatchEntry->eventEntry));
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005408 restartEvent = afterMotionEventLockedInterruptible(connection, dispatchEntry, motionEntry,
5409 handled);
5410 } else {
5411 restartEvent = false;
5412 }
5413
5414 // Dequeue the event and start the next cycle.
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07005415 // Because the lock might have been released, it is possible that the
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005416 // contents of the wait queue to have been drained, so we need to double-check
5417 // a few things.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005418 dispatchEntryIt = connection->findWaitQueueEntry(seq);
5419 if (dispatchEntryIt != connection->waitQueue.end()) {
5420 dispatchEntry = *dispatchEntryIt;
5421 connection->waitQueue.erase(dispatchEntryIt);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005422 const sp<IBinder>& connectionToken = connection->inputChannel->getConnectionToken();
5423 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005424 if (!connection->responsive) {
5425 connection->responsive = isConnectionResponsive(*connection);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005426 if (connection->responsive) {
5427 // The connection was unresponsive, and now it's responsive. Tell the policy
5428 // about it so that it can stop ANR.
5429 std::unique_ptr<CommandEntry> connectionResponsiveCommand =
5430 std::make_unique<CommandEntry>(
5431 &InputDispatcher::doNotifyConnectionResponsiveLockedInterruptible);
5432 connectionResponsiveCommand->connectionToken = connectionToken;
5433 postCommandLocked(std::move(connectionResponsiveCommand));
5434 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005435 }
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005436 traceWaitQueueLength(connection);
5437 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005438 connection->outboundQueue.push_front(dispatchEntry);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005439 traceOutboundQueueLength(connection);
5440 } else {
5441 releaseDispatchEntry(dispatchEntry);
5442 }
5443 }
5444
5445 // Start the next dispatch cycle for this connection.
5446 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005447}
5448
5449bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005450 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005451 KeyEntry& keyEntry, bool handled) {
5452 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005453 if (!handled) {
5454 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005455 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005456 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005457 return false;
5458 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005459
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005460 // Get the fallback key state.
5461 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005462 int32_t originalKeyCode = keyEntry.keyCode;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005463 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005464 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005465 connection->inputState.removeFallbackKey(originalKeyCode);
5466 }
5467
5468 if (handled || !dispatchEntry->hasForegroundTarget()) {
5469 // If the application handles the original key for which we previously
5470 // generated a fallback or if the window is not a foreground window,
5471 // then cancel the associated fallback key, if any.
5472 if (fallbackKeyCode != -1) {
5473 // Dispatch the unhandled key to the policy with the cancel flag.
Michael Wrightd02c5b62014-02-10 15:10:22 -08005474#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005475 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005476 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005477 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005478#endif
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005479 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005480 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005481
5482 mLock.unlock();
5483
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005484 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005485 keyEntry.policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005486
5487 mLock.lock();
5488
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005489 // Cancel the fallback key.
5490 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005491 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005492 "application handled the original non-fallback key "
5493 "or is no longer a foreground target, "
5494 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005495 options.keyCode = fallbackKeyCode;
5496 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005497 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005498 connection->inputState.removeFallbackKey(originalKeyCode);
5499 }
5500 } else {
5501 // If the application did not handle a non-fallback key, first check
5502 // that we are in a good state to perform unhandled key event processing
5503 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005504 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005505 if (fallbackKeyCode == -1 && !initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005506#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005507 ALOGD("Unhandled key event: Skipping unhandled key event processing "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005508 "since this is not an initial down. "
5509 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005510 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005511#endif
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005512 return false;
5513 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005514
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005515 // Dispatch the unhandled key to the policy.
5516#if DEBUG_OUTBOUND_EVENT_DETAILS
5517 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005518 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005519 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005520#endif
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005521 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005522
5523 mLock.unlock();
5524
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005525 bool fallback =
5526 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005527 &event, keyEntry.policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005528
5529 mLock.lock();
5530
5531 if (connection->status != Connection::STATUS_NORMAL) {
5532 connection->inputState.removeFallbackKey(originalKeyCode);
5533 return false;
5534 }
5535
5536 // Latch the fallback keycode for this key on an initial down.
5537 // The fallback keycode cannot change at any other point in the lifecycle.
5538 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005539 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005540 fallbackKeyCode = event.getKeyCode();
5541 } else {
5542 fallbackKeyCode = AKEYCODE_UNKNOWN;
5543 }
5544 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
5545 }
5546
5547 ALOG_ASSERT(fallbackKeyCode != -1);
5548
5549 // Cancel the fallback key if the policy decides not to send it anymore.
5550 // We will continue to dispatch the key to the policy but we will no
5551 // longer dispatch a fallback key to the application.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005552 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
5553 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005554#if DEBUG_OUTBOUND_EVENT_DETAILS
5555 if (fallback) {
5556 ALOGD("Unhandled key event: Policy requested to send key %d"
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005557 "as a fallback for %d, but on the DOWN it had requested "
5558 "to send %d instead. Fallback canceled.",
5559 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005560 } else {
5561 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005562 "but on the DOWN it had requested to send %d. "
5563 "Fallback canceled.",
5564 originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005565 }
5566#endif
5567
5568 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
5569 "canceling fallback, policy no longer desires it");
5570 options.keyCode = fallbackKeyCode;
5571 synthesizeCancelationEventsForConnectionLocked(connection, options);
5572
5573 fallback = false;
5574 fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005575 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005576 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005577 }
5578 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005579
5580#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005581 {
5582 std::string msg;
5583 const KeyedVector<int32_t, int32_t>& fallbackKeys =
5584 connection->inputState.getFallbackKeys();
5585 for (size_t i = 0; i < fallbackKeys.size(); i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005586 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005587 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005588 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005589 fallbackKeys.size(), msg.c_str());
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005590 }
5591#endif
5592
5593 if (fallback) {
5594 // Restart the dispatch cycle using the fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005595 keyEntry.eventTime = event.getEventTime();
5596 keyEntry.deviceId = event.getDeviceId();
5597 keyEntry.source = event.getSource();
5598 keyEntry.displayId = event.getDisplayId();
5599 keyEntry.flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
5600 keyEntry.keyCode = fallbackKeyCode;
5601 keyEntry.scanCode = event.getScanCode();
5602 keyEntry.metaState = event.getMetaState();
5603 keyEntry.repeatCount = event.getRepeatCount();
5604 keyEntry.downTime = event.getDownTime();
5605 keyEntry.syntheticRepeat = false;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005606
5607#if DEBUG_OUTBOUND_EVENT_DETAILS
5608 ALOGD("Unhandled key event: Dispatching fallback key. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005609 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005610 originalKeyCode, fallbackKeyCode, keyEntry.metaState);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005611#endif
5612 return true; // restart the event
5613 } else {
5614#if DEBUG_OUTBOUND_EVENT_DETAILS
5615 ALOGD("Unhandled key event: No fallback key.");
5616#endif
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005617
5618 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005619 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005620 }
5621 }
5622 return false;
5623}
5624
5625bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005626 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005627 MotionEntry& motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005628 return false;
5629}
5630
5631void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
5632 mLock.unlock();
5633
5634 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType);
5635
5636 mLock.lock();
5637}
5638
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07005639KeyEvent InputDispatcher::createKeyEvent(const KeyEntry& entry) {
5640 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08005641 event.initialize(entry.id, entry.deviceId, entry.source, entry.displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08005642 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
5643 entry.repeatCount, entry.downTime, entry.eventTime);
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07005644 return event;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005645}
5646
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07005647void InputDispatcher::reportDispatchStatistics(std::chrono::nanoseconds eventDuration,
5648 const Connection& connection, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005649 // TODO Write some statistics about how long we spend waiting.
5650}
5651
Siarhei Vishniakoude4bf152019-08-16 11:12:52 -05005652/**
5653 * Report the touch event latency to the statsd server.
5654 * Input events are reported for statistics if:
5655 * - This is a touchscreen event
5656 * - InputFilter is not enabled
5657 * - Event is not injected or synthesized
5658 *
5659 * Statistics should be reported before calling addValue, to prevent a fresh new sample
5660 * from getting aggregated with the "old" data.
5661 */
5662void InputDispatcher::reportTouchEventForStatistics(const MotionEntry& motionEntry)
5663 REQUIRES(mLock) {
5664 const bool reportForStatistics = (motionEntry.source == AINPUT_SOURCE_TOUCHSCREEN) &&
5665 !(motionEntry.isSynthesized()) && !mInputFilterEnabled;
5666 if (!reportForStatistics) {
5667 return;
5668 }
5669
5670 if (mTouchStatistics.shouldReport()) {
5671 android::util::stats_write(android::util::TOUCH_EVENT_REPORTED, mTouchStatistics.getMin(),
5672 mTouchStatistics.getMax(), mTouchStatistics.getMean(),
5673 mTouchStatistics.getStDev(), mTouchStatistics.getCount());
5674 mTouchStatistics.reset();
5675 }
5676 const float latencyMicros = nanoseconds_to_microseconds(now() - motionEntry.eventTime);
5677 mTouchStatistics.addValue(latencyMicros);
5678}
5679
Michael Wrightd02c5b62014-02-10 15:10:22 -08005680void InputDispatcher::traceInboundQueueLengthLocked() {
5681 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005682 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005683 }
5684}
5685
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08005686void InputDispatcher::traceOutboundQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005687 if (ATRACE_ENABLED()) {
5688 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08005689 snprintf(counterName, sizeof(counterName), "oq:%s", connection->getWindowName().c_str());
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005690 ATRACE_INT(counterName, connection->outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005691 }
5692}
5693
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08005694void InputDispatcher::traceWaitQueueLength(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), "wq:%s", connection->getWindowName().c_str());
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005698 ATRACE_INT(counterName, connection->waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005699 }
5700}
5701
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005702void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005703 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005704
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005705 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005706 dumpDispatchStateLocked(dump);
5707
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005708 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005709 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005710 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005711 }
5712}
5713
5714void InputDispatcher::monitor() {
5715 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005716 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005717 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005718 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005719}
5720
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08005721/**
5722 * Wake up the dispatcher and wait until it processes all events and commands.
5723 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
5724 * this method can be safely called from any thread, as long as you've ensured that
5725 * the work you are interested in completing has already been queued.
5726 */
5727bool InputDispatcher::waitForIdle() {
5728 /**
5729 * Timeout should represent the longest possible time that a device might spend processing
5730 * events and commands.
5731 */
5732 constexpr std::chrono::duration TIMEOUT = 100ms;
5733 std::unique_lock lock(mLock);
5734 mLooper->wake();
5735 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
5736 return result == std::cv_status::no_timeout;
5737}
5738
Vishnu Naire798b472020-07-23 13:52:21 -07005739/**
5740 * Sets focus to the window identified by the token. This must be called
5741 * after updating any input window handles.
5742 *
5743 * Params:
5744 * request.token - input channel token used to identify the window that should gain focus.
5745 * request.focusedToken - the token that the caller expects currently to be focused. If the
5746 * specified token does not match the currently focused window, this request will be dropped.
5747 * If the specified focused token matches the currently focused window, the call will succeed.
5748 * Set this to "null" if this call should succeed no matter what the currently focused token is.
5749 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
5750 * when requesting the focus change. This determines which request gets
5751 * precedence if there is a focus change request from another source such as pointer down.
5752 */
Vishnu Nair958da932020-08-21 17:12:37 -07005753void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
5754 { // acquire lock
5755 std::scoped_lock _l(mLock);
5756
5757 const int32_t displayId = request.displayId;
5758 const sp<IBinder> oldFocusedToken = getValueByKey(mFocusedWindowTokenByDisplay, displayId);
5759 if (request.focusedToken && oldFocusedToken != request.focusedToken) {
5760 ALOGD_IF(DEBUG_FOCUS,
5761 "setFocusedWindow on display %" PRId32
5762 " ignored, reason: focusedToken is not focused",
5763 displayId);
5764 return;
5765 }
5766
5767 mPendingFocusRequests.erase(displayId);
5768 FocusResult result = handleFocusRequestLocked(request);
5769 if (result == FocusResult::NOT_VISIBLE) {
5770 // The requested window is not currently visible. Wait for the window to become visible
5771 // and then provide it focus. This is to handle situations where a user action triggers
5772 // a new window to appear. We want to be able to queue any key events after the user
5773 // action and deliver it to the newly focused window. In order for this to happen, we
5774 // take focus from the currently focused window so key events can be queued.
5775 ALOGD_IF(DEBUG_FOCUS,
5776 "setFocusedWindow on display %" PRId32
5777 " pending, reason: window is not visible",
5778 displayId);
5779 mPendingFocusRequests[displayId] = request;
5780 onFocusChangedLocked(oldFocusedToken, nullptr, displayId,
5781 "setFocusedWindow_AwaitingWindowVisibility");
5782 } else if (result != FocusResult::OK) {
5783 ALOGW("setFocusedWindow on display %" PRId32 " ignored, reason:%s", displayId,
5784 typeToString(result));
5785 }
5786 } // release lock
5787 // Wake up poll loop since it may need to make new input dispatching choices.
5788 mLooper->wake();
5789}
5790
5791InputDispatcher::FocusResult InputDispatcher::handleFocusRequestLocked(
5792 const FocusRequest& request) {
5793 const int32_t displayId = request.displayId;
5794 const sp<IBinder> newFocusedToken = request.token;
5795 const sp<IBinder> oldFocusedToken = getValueByKey(mFocusedWindowTokenByDisplay, displayId);
5796
5797 if (oldFocusedToken == request.token) {
5798 ALOGD_IF(DEBUG_FOCUS,
5799 "setFocusedWindow on display %" PRId32 " ignored, reason: already focused",
5800 displayId);
5801 return FocusResult::OK;
5802 }
5803
5804 FocusResult result = checkTokenFocusableLocked(newFocusedToken, displayId);
5805 if (result != FocusResult::OK) {
5806 return result;
5807 }
5808
5809 std::string_view reason =
5810 (request.focusedToken) ? "setFocusedWindow_FocusCheck" : "setFocusedWindow";
5811 onFocusChangedLocked(oldFocusedToken, newFocusedToken, displayId, reason);
5812 return FocusResult::OK;
5813}
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005814
Vishnu Nairad321cd2020-08-20 16:40:21 -07005815void InputDispatcher::onFocusChangedLocked(const sp<IBinder>& oldFocusedToken,
5816 const sp<IBinder>& newFocusedToken, int32_t displayId,
5817 std::string_view reason) {
5818 if (oldFocusedToken) {
5819 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(oldFocusedToken);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005820 if (focusedInputChannel) {
5821 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
5822 "focus left window");
5823 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Vishnu Nairad321cd2020-08-20 16:40:21 -07005824 enqueueFocusEventLocked(oldFocusedToken, false /*hasFocus*/, reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005825 }
Vishnu Nairad321cd2020-08-20 16:40:21 -07005826 mFocusedWindowTokenByDisplay.erase(displayId);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005827 }
Vishnu Nairad321cd2020-08-20 16:40:21 -07005828 if (newFocusedToken) {
5829 mFocusedWindowTokenByDisplay[displayId] = newFocusedToken;
5830 enqueueFocusEventLocked(newFocusedToken, true /*hasFocus*/, reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005831 }
5832
Prabir Pradhan99987712020-11-10 18:43:05 -08005833 // If a window has pointer capture, then it must have focus. We need to ensure that this
5834 // contract is upheld when pointer capture is being disabled due to a loss of window focus.
5835 // If the window loses focus before it loses pointer capture, then the window can be in a state
5836 // where it has pointer capture but not focus, violating the contract. Therefore we must
5837 // dispatch the pointer capture event before the focus event. Since focus events are added to
5838 // the front of the queue (above), we add the pointer capture event to the front of the queue
5839 // after the focus events are added. This ensures the pointer capture event ends up at the
5840 // front.
5841 disablePointerCaptureForcedLocked();
5842
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005843 if (mFocusedDisplayId == displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005844 notifyFocusChangedLocked(oldFocusedToken, newFocusedToken);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005845 }
5846}
Vishnu Nair958da932020-08-21 17:12:37 -07005847
Prabir Pradhan99987712020-11-10 18:43:05 -08005848void InputDispatcher::disablePointerCaptureForcedLocked() {
5849 if (!mFocusedWindowRequestedPointerCapture && !mWindowTokenWithPointerCapture) {
5850 return;
5851 }
5852
5853 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
5854
5855 if (mFocusedWindowRequestedPointerCapture) {
5856 mFocusedWindowRequestedPointerCapture = false;
5857 setPointerCaptureLocked(false);
5858 }
5859
5860 if (!mWindowTokenWithPointerCapture) {
5861 // No need to send capture changes because no window has capture.
5862 return;
5863 }
5864
5865 if (mPendingEvent != nullptr) {
5866 // Move the pending event to the front of the queue. This will give the chance
5867 // for the pending event to be dropped if it is a captured event.
5868 mInboundQueue.push_front(mPendingEvent);
5869 mPendingEvent = nullptr;
5870 }
5871
5872 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
5873 false /* hasCapture */);
5874 mInboundQueue.push_front(std::move(entry));
5875}
5876
Vishnu Nair958da932020-08-21 17:12:37 -07005877/**
5878 * Checks if the window token can be focused on a display. The token can be focused if there is
5879 * at least one window handle that is visible with the same token and all window handles with the
5880 * same token are focusable.
5881 *
5882 * In the case of mirroring, two windows may share the same window token and their visibility
5883 * might be different. Example, the mirrored window can cover the window its mirroring. However,
5884 * we expect the focusability of the windows to match since its hard to reason why one window can
5885 * receive focus events and the other cannot when both are backed by the same input channel.
5886 */
5887InputDispatcher::FocusResult InputDispatcher::checkTokenFocusableLocked(const sp<IBinder>& token,
5888 int32_t displayId) const {
5889 bool allWindowsAreFocusable = true;
5890 bool visibleWindowFound = false;
5891 bool windowFound = false;
5892 for (const sp<InputWindowHandle>& window : getWindowHandlesLocked(displayId)) {
5893 if (window->getToken() != token) {
5894 continue;
5895 }
5896 windowFound = true;
5897 if (window->getInfo()->visible) {
5898 // Check if at least a single window is visible.
5899 visibleWindowFound = true;
5900 }
5901 if (!window->getInfo()->focusable) {
5902 // Check if all windows with the window token are focusable.
5903 allWindowsAreFocusable = false;
5904 break;
5905 }
5906 }
5907
5908 if (!windowFound) {
5909 return FocusResult::NO_WINDOW;
5910 }
5911 if (!allWindowsAreFocusable) {
5912 return FocusResult::NOT_FOCUSABLE;
5913 }
5914 if (!visibleWindowFound) {
5915 return FocusResult::NOT_VISIBLE;
5916 }
5917
5918 return FocusResult::OK;
5919}
Prabir Pradhan99987712020-11-10 18:43:05 -08005920
5921void InputDispatcher::setPointerCaptureLocked(bool enabled) {
5922 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5923 &InputDispatcher::doSetPointerCaptureLockedInterruptible);
5924 commandEntry->enabled = enabled;
5925 postCommandLocked(std::move(commandEntry));
5926}
5927
5928void InputDispatcher::doSetPointerCaptureLockedInterruptible(
5929 android::inputdispatcher::CommandEntry* commandEntry) {
5930 mLock.unlock();
5931
5932 mPolicy->setPointerCapture(commandEntry->enabled);
5933
5934 mLock.lock();
5935}
5936
Garfield Tane84e6f92019-08-29 17:28:41 -07005937} // namespace android::inputdispatcher