blob: 19f8694a5e27e8ed965cb3645a1895540e576007 [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>
Peter Collingbourneb04b9b82021-02-08 12:09:47 -080051#include <android-base/properties.h>
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080052#include <android-base/stringprintf.h>
Siarhei Vishniakou70622952020-07-30 11:17:23 -050053#include <android/os/IInputConstants.h>
Robert Carr4e670e52018-08-15 13:26:12 -070054#include <binder/Binder.h>
Siarhei Vishniakou2508b872020-12-03 16:33:53 -100055#include <binder/IServiceManager.h>
56#include <com/android/internal/compat/IPlatformCompatNative.h>
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -080057#include <input/InputDevice.h>
Michael Wright44753b12020-07-08 13:48:11 +010058#include <input/InputWindow.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070059#include <log/log.h>
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +000060#include <log/log_event_list.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070061#include <powermanager/PowerManager.h>
Michael Wright44753b12020-07-08 13:48:11 +010062#include <statslog.h>
63#include <unistd.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070064#include <utils/Trace.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080065
Michael Wright44753b12020-07-08 13:48:11 +010066#include <cerrno>
67#include <cinttypes>
68#include <climits>
69#include <cstddef>
70#include <ctime>
71#include <queue>
72#include <sstream>
73
74#include "Connection.h"
Chris Yef59a2f42020-10-16 12:55:26 -070075#include "InputDispatcher.h"
Michael Wright44753b12020-07-08 13:48:11 +010076
Michael Wrightd02c5b62014-02-10 15:10:22 -080077#define INDENT " "
78#define INDENT2 " "
79#define INDENT3 " "
80#define INDENT4 " "
81
Peter Collingbourneb04b9b82021-02-08 12:09:47 -080082using android::base::HwTimeoutMultiplier;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080083using android::base::StringPrintf;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -080084using android::os::BlockUntrustedTouchesMode;
Siarhei Vishniakou2508b872020-12-03 16:33:53 -100085using android::os::IInputConstants;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -080086using android::os::InputEventInjectionResult;
87using android::os::InputEventInjectionSync;
Siarhei Vishniakou2508b872020-12-03 16:33:53 -100088using com::android::internal::compat::IPlatformCompatNative;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080089
Garfield Tane84e6f92019-08-29 17:28:41 -070090namespace android::inputdispatcher {
Michael Wrightd02c5b62014-02-10 15:10:22 -080091
92// Default input dispatching timeout if there is no focused application or paused window
93// from which to determine an appropriate dispatching timeout.
Peter Collingbourneb04b9b82021-02-08 12:09:47 -080094const std::chrono::duration DEFAULT_INPUT_DISPATCHING_TIMEOUT = std::chrono::milliseconds(
95 android::os::IInputConstants::UNMULTIPLIED_DEFAULT_DISPATCHING_TIMEOUT_MILLIS *
96 HwTimeoutMultiplier());
Michael Wrightd02c5b62014-02-10 15:10:22 -080097
98// Amount of time to allow for all pending events to be processed when an app switch
99// key is on the way. This is used to preempt input dispatch and drop input events
100// when an application takes too long to respond and the user has pressed an app switch key.
Michael Wright2b3c3302018-03-02 17:19:13 +0000101constexpr nsecs_t APP_SWITCH_TIMEOUT = 500 * 1000000LL; // 0.5sec
Michael Wrightd02c5b62014-02-10 15:10:22 -0800102
103// Amount of time to allow for an event to be dispatched (measured since its eventTime)
104// before considering it stale and dropping it.
Michael Wright2b3c3302018-03-02 17:19:13 +0000105constexpr nsecs_t STALE_EVENT_TIMEOUT = 10000 * 1000000LL; // 10sec
Michael Wrightd02c5b62014-02-10 15:10:22 -0800106
Michael Wrightd02c5b62014-02-10 15:10:22 -0800107// 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 +0000108constexpr nsecs_t SLOW_EVENT_PROCESSING_WARNING_TIMEOUT = 2000 * 1000000LL; // 2sec
109
110// Log a warning when an interception call takes longer than this to process.
111constexpr std::chrono::milliseconds SLOW_INTERCEPTION_THRESHOLD = 50ms;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800112
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700113// Additional key latency in case a connection is still processing some motion events.
114// This will help with the case when a user touched a button that opens a new window,
115// and gives us the chance to dispatch the key to this new window.
116constexpr std::chrono::nanoseconds KEY_WAITING_FOR_EVENTS_TIMEOUT = 500ms;
117
Michael Wrightd02c5b62014-02-10 15:10:22 -0800118// Number of recent events to keep for debugging purposes.
Michael Wright2b3c3302018-03-02 17:19:13 +0000119constexpr size_t RECENT_QUEUE_MAX_SIZE = 10;
120
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +0000121// Event log tags. See EventLogTags.logtags for reference
122constexpr int LOGTAG_INPUT_INTERACTION = 62000;
123constexpr int LOGTAG_INPUT_FOCUS = 62001;
124
Michael Wrightd02c5b62014-02-10 15:10:22 -0800125static inline nsecs_t now() {
126 return systemTime(SYSTEM_TIME_MONOTONIC);
127}
128
129static inline const char* toString(bool value) {
130 return value ? "true" : "false";
131}
132
Bernardo Rufino49d99e42021-01-18 15:16:59 +0000133static inline const std::string toString(sp<IBinder> binder) {
134 if (binder == nullptr) {
135 return "<null>";
136 }
137 return StringPrintf("%p", binder.get());
138}
139
Michael Wrightd02c5b62014-02-10 15:10:22 -0800140static inline int32_t getMotionEventActionPointerIndex(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700141 return (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) >>
142 AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800143}
144
145static bool isValidKeyAction(int32_t action) {
146 switch (action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700147 case AKEY_EVENT_ACTION_DOWN:
148 case AKEY_EVENT_ACTION_UP:
149 return true;
150 default:
151 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800152 }
153}
154
155static bool validateKeyEvent(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700156 if (!isValidKeyAction(action)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800157 ALOGE("Key event has invalid action code 0x%x", action);
158 return false;
159 }
160 return true;
161}
162
Michael Wright7b159c92015-05-14 14:48:03 +0100163static bool isValidMotionAction(int32_t action, int32_t actionButton, int32_t pointerCount) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800164 switch (action & AMOTION_EVENT_ACTION_MASK) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700165 case AMOTION_EVENT_ACTION_DOWN:
166 case AMOTION_EVENT_ACTION_UP:
167 case AMOTION_EVENT_ACTION_CANCEL:
168 case AMOTION_EVENT_ACTION_MOVE:
169 case AMOTION_EVENT_ACTION_OUTSIDE:
170 case AMOTION_EVENT_ACTION_HOVER_ENTER:
171 case AMOTION_EVENT_ACTION_HOVER_MOVE:
172 case AMOTION_EVENT_ACTION_HOVER_EXIT:
173 case AMOTION_EVENT_ACTION_SCROLL:
174 return true;
175 case AMOTION_EVENT_ACTION_POINTER_DOWN:
176 case AMOTION_EVENT_ACTION_POINTER_UP: {
177 int32_t index = getMotionEventActionPointerIndex(action);
178 return index >= 0 && index < pointerCount;
179 }
180 case AMOTION_EVENT_ACTION_BUTTON_PRESS:
181 case AMOTION_EVENT_ACTION_BUTTON_RELEASE:
182 return actionButton != 0;
183 default:
184 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800185 }
186}
187
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -0500188static int64_t millis(std::chrono::nanoseconds t) {
189 return std::chrono::duration_cast<std::chrono::milliseconds>(t).count();
190}
191
Michael Wright7b159c92015-05-14 14:48:03 +0100192static bool validateMotionEvent(int32_t action, int32_t actionButton, size_t pointerCount,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700193 const PointerProperties* pointerProperties) {
194 if (!isValidMotionAction(action, actionButton, pointerCount)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800195 ALOGE("Motion event has invalid action code 0x%x", action);
196 return false;
197 }
198 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
Narayan Kamath37764c72014-03-27 14:21:09 +0000199 ALOGE("Motion event has invalid pointer count %zu; value must be between 1 and %d.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700200 pointerCount, MAX_POINTERS);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800201 return false;
202 }
203 BitSet32 pointerIdBits;
204 for (size_t i = 0; i < pointerCount; i++) {
205 int32_t id = pointerProperties[i].id;
206 if (id < 0 || id > MAX_POINTER_ID) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700207 ALOGE("Motion event has invalid pointer id %d; value must be between 0 and %d", id,
208 MAX_POINTER_ID);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800209 return false;
210 }
211 if (pointerIdBits.hasBit(id)) {
212 ALOGE("Motion event has duplicate pointer id %d", id);
213 return false;
214 }
215 pointerIdBits.markBit(id);
216 }
217 return true;
218}
219
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000220static std::string dumpRegion(const Region& region) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800221 if (region.isEmpty()) {
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000222 return "<empty>";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800223 }
224
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000225 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800226 bool first = true;
227 Region::const_iterator cur = region.begin();
228 Region::const_iterator const tail = region.end();
229 while (cur != tail) {
230 if (first) {
231 first = false;
232 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800233 dump += "|";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800234 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800235 dump += StringPrintf("[%d,%d][%d,%d]", cur->left, cur->top, cur->right, cur->bottom);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800236 cur++;
237 }
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000238 return dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800239}
240
Siarhei Vishniakou14411c92020-09-18 21:15:05 -0500241static std::string dumpQueue(const std::deque<DispatchEntry*>& queue, nsecs_t currentTime) {
242 constexpr size_t maxEntries = 50; // max events to print
243 constexpr size_t skipBegin = maxEntries / 2;
244 const size_t skipEnd = queue.size() - maxEntries / 2;
245 // skip from maxEntries / 2 ... size() - maxEntries/2
246 // only print from 0 .. skipBegin and then from skipEnd .. size()
247
248 std::string dump;
249 for (size_t i = 0; i < queue.size(); i++) {
250 const DispatchEntry& entry = *queue[i];
251 if (i >= skipBegin && i < skipEnd) {
252 dump += StringPrintf(INDENT4 "<skipped %zu entries>\n", skipEnd - skipBegin);
253 i = skipEnd - 1; // it will be incremented to "skipEnd" by 'continue'
254 continue;
255 }
256 dump.append(INDENT4);
257 dump += entry.eventEntry->getDescription();
258 dump += StringPrintf(", seq=%" PRIu32
259 ", targetFlags=0x%08x, resolvedAction=%d, age=%" PRId64 "ms",
260 entry.seq, entry.targetFlags, entry.resolvedAction,
261 ns2ms(currentTime - entry.eventEntry->eventTime));
262 if (entry.deliveryTime != 0) {
263 // This entry was delivered, so add information on how long we've been waiting
264 dump += StringPrintf(", wait=%" PRId64 "ms", ns2ms(currentTime - entry.deliveryTime));
265 }
266 dump.append("\n");
267 }
268 return dump;
269}
270
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700271/**
272 * Find the entry in std::unordered_map by key, and return it.
273 * If the entry is not found, return a default constructed entry.
274 *
275 * Useful when the entries are vectors, since an empty vector will be returned
276 * if the entry is not found.
277 * Also useful when the entries are sp<>. If an entry is not found, nullptr is returned.
278 */
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700279template <typename K, typename V>
280static V getValueByKey(const std::unordered_map<K, V>& map, K key) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700281 auto it = map.find(key);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700282 return it != map.end() ? it->second : V{};
Tiger Huang721e26f2018-07-24 22:26:19 +0800283}
284
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700285/**
286 * Find the entry in std::unordered_map by value, and remove it.
287 * If more than one entry has the same value, then all matching
288 * key-value pairs will be removed.
289 *
290 * Return true if at least one value has been removed.
291 */
292template <typename K, typename V>
293static bool removeByValue(std::unordered_map<K, V>& map, const V& value) {
294 bool removed = false;
295 for (auto it = map.begin(); it != map.end();) {
296 if (it->second == value) {
297 it = map.erase(it);
298 removed = true;
299 } else {
300 it++;
301 }
302 }
303 return removed;
304}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800305
chaviwaf87b3e2019-10-01 16:59:28 -0700306static bool haveSameToken(const sp<InputWindowHandle>& first, const sp<InputWindowHandle>& second) {
307 if (first == second) {
308 return true;
309 }
310
311 if (first == nullptr || second == nullptr) {
312 return false;
313 }
314
315 return first->getToken() == second->getToken();
316}
317
Bernardo Rufino1ff9d592021-01-18 16:58:57 +0000318static bool haveSameApplicationToken(const InputWindowInfo* first, const InputWindowInfo* second) {
319 if (first == nullptr || second == nullptr) {
320 return false;
321 }
322 return first->applicationInfo.token != nullptr &&
323 first->applicationInfo.token == second->applicationInfo.token;
324}
325
Siarhei Vishniakouadfd4fa2019-12-20 11:02:58 -0800326static bool isStaleEvent(nsecs_t currentTime, const EventEntry& entry) {
327 return currentTime - entry.eventTime >= STALE_EVENT_TIMEOUT;
328}
329
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000330static std::unique_ptr<DispatchEntry> createDispatchEntry(const InputTarget& inputTarget,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700331 std::shared_ptr<EventEntry> eventEntry,
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000332 int32_t inputTargetFlags) {
yunho.shinf4a80b82020-11-16 21:13:57 +0900333 if (eventEntry->type == EventEntry::Type::MOTION) {
334 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
335 if (motionEntry.source & AINPUT_SOURCE_CLASS_JOYSTICK) {
336 const ui::Transform identityTransform;
337 // Use identity transform for joystick events events because they don't depend on
338 // the window info
339 return std::make_unique<DispatchEntry>(eventEntry, inputTargetFlags, identityTransform,
340 1.0f /*globalScaleFactor*/);
341 }
342 }
343
chaviw1ff3d1e2020-07-01 15:53:47 -0700344 if (inputTarget.useDefaultPointerTransform()) {
345 const ui::Transform& transform = inputTarget.getDefaultPointerTransform();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700346 return std::make_unique<DispatchEntry>(eventEntry, inputTargetFlags, transform,
chaviw1ff3d1e2020-07-01 15:53:47 -0700347 inputTarget.globalScaleFactor);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000348 }
349
350 ALOG_ASSERT(eventEntry->type == EventEntry::Type::MOTION);
351 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
352
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700353 std::vector<PointerCoords> pointerCoords;
354 pointerCoords.resize(motionEntry.pointerCount);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000355
356 // Use the first pointer information to normalize all other pointers. This could be any pointer
357 // as long as all other pointers are normalized to the same value and the final DispatchEntry
chaviw1ff3d1e2020-07-01 15:53:47 -0700358 // uses the transform for the normalized pointer.
359 const ui::Transform& firstPointerTransform =
360 inputTarget.pointerTransforms[inputTarget.pointerIds.firstMarkedBit()];
361 ui::Transform inverseFirstTransform = firstPointerTransform.inverse();
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000362
363 // Iterate through all pointers in the event to normalize against the first.
364 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.pointerCount; pointerIndex++) {
365 const PointerProperties& pointerProperties = motionEntry.pointerProperties[pointerIndex];
366 uint32_t pointerId = uint32_t(pointerProperties.id);
chaviw1ff3d1e2020-07-01 15:53:47 -0700367 const ui::Transform& currTransform = inputTarget.pointerTransforms[pointerId];
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000368
369 pointerCoords[pointerIndex].copyFrom(motionEntry.pointerCoords[pointerIndex]);
chaviw1ff3d1e2020-07-01 15:53:47 -0700370 // First, apply the current pointer's transform to update the coordinates into
371 // window space.
372 pointerCoords[pointerIndex].transform(currTransform);
373 // Next, apply the inverse transform of the normalized coordinates so the
374 // current coordinates are transformed into the normalized coordinate space.
375 pointerCoords[pointerIndex].transform(inverseFirstTransform);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000376 }
377
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700378 std::unique_ptr<MotionEntry> combinedMotionEntry =
379 std::make_unique<MotionEntry>(motionEntry.id, motionEntry.eventTime,
380 motionEntry.deviceId, motionEntry.source,
381 motionEntry.displayId, motionEntry.policyFlags,
382 motionEntry.action, motionEntry.actionButton,
383 motionEntry.flags, motionEntry.metaState,
384 motionEntry.buttonState, motionEntry.classification,
385 motionEntry.edgeFlags, motionEntry.xPrecision,
386 motionEntry.yPrecision, motionEntry.xCursorPosition,
387 motionEntry.yCursorPosition, motionEntry.downTime,
388 motionEntry.pointerCount, motionEntry.pointerProperties,
389 pointerCoords.data(), 0 /* xOffset */, 0 /* yOffset */);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000390
391 if (motionEntry.injectionState) {
392 combinedMotionEntry->injectionState = motionEntry.injectionState;
393 combinedMotionEntry->injectionState->refCount += 1;
394 }
395
396 std::unique_ptr<DispatchEntry> dispatchEntry =
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700397 std::make_unique<DispatchEntry>(std::move(combinedMotionEntry), inputTargetFlags,
398 firstPointerTransform, inputTarget.globalScaleFactor);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000399 return dispatchEntry;
400}
401
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -0700402static void addGestureMonitors(const std::vector<Monitor>& monitors,
403 std::vector<TouchedMonitor>& outTouchedMonitors, float xOffset = 0,
404 float yOffset = 0) {
405 if (monitors.empty()) {
406 return;
407 }
408 outTouchedMonitors.reserve(monitors.size() + outTouchedMonitors.size());
409 for (const Monitor& monitor : monitors) {
410 outTouchedMonitors.emplace_back(monitor, xOffset, yOffset);
411 }
412}
413
Garfield Tan15601662020-09-22 15:32:38 -0700414static status_t openInputChannelPair(const std::string& name,
415 std::shared_ptr<InputChannel>& serverChannel,
416 std::unique_ptr<InputChannel>& clientChannel) {
417 std::unique_ptr<InputChannel> uniqueServerChannel;
418 status_t result = InputChannel::openInputChannelPair(name, uniqueServerChannel, clientChannel);
419
420 serverChannel = std::move(uniqueServerChannel);
421 return result;
422}
423
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500424template <typename T>
425static bool sharedPointersEqual(const std::shared_ptr<T>& lhs, const std::shared_ptr<T>& rhs) {
426 if (lhs == nullptr && rhs == nullptr) {
427 return true;
428 }
429 if (lhs == nullptr || rhs == nullptr) {
430 return false;
431 }
432 return *lhs == *rhs;
433}
434
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000435static sp<IPlatformCompatNative> getCompatService() {
436 sp<IBinder> service(defaultServiceManager()->getService(String16("platform_compat_native")));
437 if (service == nullptr) {
438 ALOGE("Failed to link to compat service");
439 return nullptr;
440 }
441 return interface_cast<IPlatformCompatNative>(service);
442}
443
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +0000444static KeyEvent createKeyEvent(const KeyEntry& entry) {
445 KeyEvent event;
446 event.initialize(entry.id, entry.deviceId, entry.source, entry.displayId, INVALID_HMAC,
447 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
448 entry.repeatCount, entry.downTime, entry.eventTime);
449 return event;
450}
451
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000452static std::optional<int32_t> findMonitorPidByToken(
453 const std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay,
454 const sp<IBinder>& token) {
455 for (const auto& it : monitorsByDisplay) {
456 const std::vector<Monitor>& monitors = it.second;
457 for (const Monitor& monitor : monitors) {
458 if (monitor.inputChannel->getConnectionToken() == token) {
459 return monitor.pid;
460 }
461 }
462 }
463 return std::nullopt;
464}
465
Michael Wrightd02c5b62014-02-10 15:10:22 -0800466// --- InputDispatcher ---
467
Garfield Tan00f511d2019-06-12 16:55:40 -0700468InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy)
469 : mPolicy(policy),
470 mPendingEvent(nullptr),
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700471 mLastDropReason(DropReason::NOT_DROPPED),
Garfield Tanff1f1bb2020-01-28 13:24:04 -0800472 mIdGenerator(IdGenerator::Source::INPUT_DISPATCHER),
Garfield Tan00f511d2019-06-12 16:55:40 -0700473 mAppSwitchSawKeyDown(false),
474 mAppSwitchDueTime(LONG_LONG_MAX),
475 mNextUnblockedEvent(nullptr),
476 mDispatchEnabled(false),
477 mDispatchFrozen(false),
478 mInputFilterEnabled(false),
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -0800479 // mInTouchMode will be initialized by the WindowManager to the default device config.
480 // To avoid leaking stack in case that call never comes, and for tests,
481 // initialize it here anyways.
482 mInTouchMode(true),
Bernardo Rufinoea97d182020-08-19 14:43:14 +0100483 mMaximumObscuringOpacityForTouch(1.0f),
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000484 mFocusedDisplayId(ADISPLAY_ID_DEFAULT),
Prabir Pradhan99987712020-11-10 18:43:05 -0800485 mFocusedWindowRequestedPointerCapture(false),
486 mWindowTokenWithPointerCapture(nullptr),
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000487 mCompatService(getCompatService()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800488 mLooper = new Looper(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800489 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800490
Yi Kong9b14ac62018-07-17 13:48:38 -0700491 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800492
493 policy->getDispatcherConfiguration(&mConfig);
494}
495
496InputDispatcher::~InputDispatcher() {
497 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800498 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800499
500 resetKeyRepeatLocked();
501 releasePendingEventLocked();
502 drainInboundQueueLocked();
503 }
504
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700505 while (!mConnectionsByFd.empty()) {
506 sp<Connection> connection = mConnectionsByFd.begin()->second;
Garfield Tan15601662020-09-22 15:32:38 -0700507 removeInputChannel(connection->inputChannel->getConnectionToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800508 }
509}
510
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700511status_t InputDispatcher::start() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700512 if (mThread) {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700513 return ALREADY_EXISTS;
514 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700515 mThread = std::make_unique<InputThread>(
516 "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
517 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700518}
519
520status_t InputDispatcher::stop() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700521 if (mThread && mThread->isCallingThread()) {
522 ALOGE("InputDispatcher cannot be stopped from its own thread!");
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700523 return INVALID_OPERATION;
524 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700525 mThread.reset();
526 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700527}
528
Michael Wrightd02c5b62014-02-10 15:10:22 -0800529void InputDispatcher::dispatchOnce() {
530 nsecs_t nextWakeupTime = LONG_LONG_MAX;
531 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800532 std::scoped_lock _l(mLock);
533 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800534
535 // Run a dispatch loop if there are no pending commands.
536 // The dispatch loop might enqueue commands to run afterwards.
537 if (!haveCommandsLocked()) {
538 dispatchOnceInnerLocked(&nextWakeupTime);
539 }
540
541 // Run all pending commands if there are any.
542 // If any commands were run then force the next poll to wake up immediately.
543 if (runCommandsLockedInterruptible()) {
544 nextWakeupTime = LONG_LONG_MIN;
545 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800546
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700547 // If we are still waiting for ack on some events,
548 // we might have to wake up earlier to check if an app is anr'ing.
549 const nsecs_t nextAnrCheck = processAnrsLocked();
550 nextWakeupTime = std::min(nextWakeupTime, nextAnrCheck);
551
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800552 // We are about to enter an infinitely long sleep, because we have no commands or
553 // pending or queued events
554 if (nextWakeupTime == LONG_LONG_MAX) {
555 mDispatcherEnteredIdle.notify_all();
556 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800557 } // release lock
558
559 // Wait for callback or timeout or wake. (make sure we round up, not down)
560 nsecs_t currentTime = now();
561 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
562 mLooper->pollOnce(timeoutMillis);
563}
564
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700565/**
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500566 * Raise ANR if there is no focused window.
567 * Before the ANR is raised, do a final state check:
568 * 1. The currently focused application must be the same one we are waiting for.
569 * 2. Ensure we still don't have a focused window.
570 */
571void InputDispatcher::processNoFocusedWindowAnrLocked() {
572 // Check if the application that we are waiting for is still focused.
573 std::shared_ptr<InputApplicationHandle> focusedApplication =
574 getValueByKey(mFocusedApplicationHandlesByDisplay, mAwaitedApplicationDisplayId);
575 if (focusedApplication == nullptr ||
576 focusedApplication->getApplicationToken() !=
577 mAwaitedFocusedApplication->getApplicationToken()) {
578 // Unexpected because we should have reset the ANR timer when focused application changed
579 ALOGE("Waited for a focused window, but focused application has already changed to %s",
580 focusedApplication->getName().c_str());
581 return; // The focused application has changed.
582 }
583
584 const sp<InputWindowHandle>& focusedWindowHandle =
585 getFocusedWindowHandleLocked(mAwaitedApplicationDisplayId);
586 if (focusedWindowHandle != nullptr) {
587 return; // We now have a focused window. No need for ANR.
588 }
589 onAnrLocked(mAwaitedFocusedApplication);
590}
591
592/**
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700593 * Check if any of the connections' wait queues have events that are too old.
594 * If we waited for events to be ack'ed for more than the window timeout, raise an ANR.
595 * Return the time at which we should wake up next.
596 */
597nsecs_t InputDispatcher::processAnrsLocked() {
598 const nsecs_t currentTime = now();
599 nsecs_t nextAnrCheck = LONG_LONG_MAX;
600 // Check if we are waiting for a focused window to appear. Raise ANR if waited too long
601 if (mNoFocusedWindowTimeoutTime.has_value() && mAwaitedFocusedApplication != nullptr) {
602 if (currentTime >= *mNoFocusedWindowTimeoutTime) {
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500603 processNoFocusedWindowAnrLocked();
Chris Yea209fde2020-07-22 13:54:51 -0700604 mAwaitedFocusedApplication.reset();
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500605 mNoFocusedWindowTimeoutTime = std::nullopt;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700606 return LONG_LONG_MIN;
607 } else {
Siarhei Vishniakou38a6d272020-10-20 20:29:33 -0500608 // Keep waiting. We will drop the event when mNoFocusedWindowTimeoutTime comes.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700609 nextAnrCheck = *mNoFocusedWindowTimeoutTime;
610 }
611 }
612
613 // Check if any connection ANRs are due
614 nextAnrCheck = std::min(nextAnrCheck, mAnrTracker.firstTimeout());
615 if (currentTime < nextAnrCheck) { // most likely scenario
616 return nextAnrCheck; // everything is normal. Let's check again at nextAnrCheck
617 }
618
619 // If we reached here, we have an unresponsive connection.
620 sp<Connection> connection = getConnectionLocked(mAnrTracker.firstToken());
621 if (connection == nullptr) {
622 ALOGE("Could not find connection for entry %" PRId64, mAnrTracker.firstTimeout());
623 return nextAnrCheck;
624 }
625 connection->responsive = false;
626 // Stop waking up for this unresponsive connection
627 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000628 onAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700629 return LONG_LONG_MIN;
630}
631
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500632std::chrono::nanoseconds InputDispatcher::getDispatchingTimeoutLocked(const sp<IBinder>& token) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700633 sp<InputWindowHandle> window = getWindowHandleLocked(token);
634 if (window != nullptr) {
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500635 return window->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700636 }
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500637 return DEFAULT_INPUT_DISPATCHING_TIMEOUT;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700638}
639
Michael Wrightd02c5b62014-02-10 15:10:22 -0800640void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
641 nsecs_t currentTime = now();
642
Jeff Browndc5992e2014-04-11 01:27:26 -0700643 // Reset the key repeat timer whenever normal dispatch is suspended while the
644 // device is in a non-interactive state. This is to ensure that we abort a key
645 // repeat if the device is just coming out of sleep.
646 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800647 resetKeyRepeatLocked();
648 }
649
650 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
651 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +0100652 if (DEBUG_FOCUS) {
653 ALOGD("Dispatch frozen. Waiting some more.");
654 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800655 return;
656 }
657
658 // Optimize latency of app switches.
659 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
660 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
661 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
662 if (mAppSwitchDueTime < *nextWakeupTime) {
663 *nextWakeupTime = mAppSwitchDueTime;
664 }
665
666 // Ready to start a new event.
667 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700668 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700669 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800670 if (isAppSwitchDue) {
671 // The inbound queue is empty so the app switch key we were waiting
672 // for will never arrive. Stop waiting for it.
673 resetPendingAppSwitchLocked(false);
674 isAppSwitchDue = false;
675 }
676
677 // Synthesize a key repeat if appropriate.
678 if (mKeyRepeatState.lastKeyEntry) {
679 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
680 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
681 } else {
682 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
683 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
684 }
685 }
686 }
687
688 // Nothing to do if there is no pending event.
689 if (!mPendingEvent) {
690 return;
691 }
692 } else {
693 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700694 mPendingEvent = mInboundQueue.front();
695 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800696 traceInboundQueueLengthLocked();
697 }
698
699 // Poke user activity for this event.
700 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700701 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800702 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800703 }
704
705 // Now we have an event to dispatch.
706 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700707 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800708 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700709 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800710 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700711 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800712 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700713 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800714 }
715
716 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700717 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800718 }
719
720 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700721 case EventEntry::Type::CONFIGURATION_CHANGED: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700722 const ConfigurationChangedEntry& typedEntry =
723 static_cast<const ConfigurationChangedEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700724 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700725 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700726 break;
727 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800728
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700729 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700730 const DeviceResetEntry& typedEntry =
731 static_cast<const DeviceResetEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700732 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700733 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700734 break;
735 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800736
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100737 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700738 std::shared_ptr<FocusEntry> typedEntry =
739 std::static_pointer_cast<FocusEntry>(mPendingEvent);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100740 dispatchFocusLocked(currentTime, typedEntry);
741 done = true;
742 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
743 break;
744 }
745
Prabir Pradhan99987712020-11-10 18:43:05 -0800746 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
747 const auto typedEntry =
748 std::static_pointer_cast<PointerCaptureChangedEntry>(mPendingEvent);
749 dispatchPointerCaptureChangedLocked(currentTime, typedEntry, dropReason);
750 done = true;
751 break;
752 }
753
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700754 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700755 std::shared_ptr<KeyEntry> keyEntry = std::static_pointer_cast<KeyEntry>(mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700756 if (isAppSwitchDue) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700757 if (isAppSwitchKeyEvent(*keyEntry)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700758 resetPendingAppSwitchLocked(true);
759 isAppSwitchDue = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700760 } else if (dropReason == DropReason::NOT_DROPPED) {
761 dropReason = DropReason::APP_SWITCH;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700762 }
763 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700764 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *keyEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700765 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700766 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700767 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
768 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700769 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700770 done = dispatchKeyLocked(currentTime, keyEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700771 break;
772 }
773
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700774 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700775 std::shared_ptr<MotionEntry> motionEntry =
776 std::static_pointer_cast<MotionEntry>(mPendingEvent);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700777 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
778 dropReason = DropReason::APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800779 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700780 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *motionEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700781 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700782 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700783 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
784 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700785 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700786 done = dispatchMotionLocked(currentTime, motionEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700787 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800788 }
Chris Yef59a2f42020-10-16 12:55:26 -0700789
790 case EventEntry::Type::SENSOR: {
791 std::shared_ptr<SensorEntry> sensorEntry =
792 std::static_pointer_cast<SensorEntry>(mPendingEvent);
793 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
794 dropReason = DropReason::APP_SWITCH;
795 }
796 // Sensor timestamps use SYSTEM_TIME_BOOTTIME time base, so we can't use
797 // 'currentTime' here, get SYSTEM_TIME_BOOTTIME instead.
798 nsecs_t bootTime = systemTime(SYSTEM_TIME_BOOTTIME);
799 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(bootTime, *sensorEntry)) {
800 dropReason = DropReason::STALE;
801 }
802 dispatchSensorLocked(currentTime, sensorEntry, &dropReason, nextWakeupTime);
803 done = true;
804 break;
805 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800806 }
807
808 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700809 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700810 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800811 }
Michael Wright3a981722015-06-10 15:26:13 +0100812 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800813
814 releasePendingEventLocked();
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700815 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -0800816 }
817}
818
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700819/**
820 * Return true if the events preceding this incoming motion event should be dropped
821 * Return false otherwise (the default behaviour)
822 */
823bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700824 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700825 (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700826
827 // Optimize case where the current application is unresponsive and the user
828 // decides to touch a window in a different application.
829 // If the application takes too long to catch up then we drop all events preceding
830 // the touch into the other window.
831 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700832 int32_t displayId = motionEntry.displayId;
833 int32_t x = static_cast<int32_t>(
834 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
835 int32_t y = static_cast<int32_t>(
836 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
837 sp<InputWindowHandle> touchedWindowHandle =
838 findTouchedWindowAtLocked(displayId, x, y, nullptr);
839 if (touchedWindowHandle != nullptr &&
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700840 touchedWindowHandle->getApplicationToken() !=
841 mAwaitedFocusedApplication->getApplicationToken()) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700842 // User touched a different application than the one we are waiting on.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700843 ALOGI("Pruning input queue because user touched a different application while waiting "
844 "for %s",
845 mAwaitedFocusedApplication->getName().c_str());
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700846 return true;
847 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700848
849 // Alternatively, maybe there's a gesture monitor that could handle this event
850 std::vector<TouchedMonitor> gestureMonitors =
851 findTouchedGestureMonitorsLocked(displayId, {});
852 for (TouchedMonitor& gestureMonitor : gestureMonitors) {
853 sp<Connection> connection =
854 getConnectionLocked(gestureMonitor.monitor.inputChannel->getConnectionToken());
Siarhei Vishniakou34ed4d42020-06-18 00:43:02 +0000855 if (connection != nullptr && connection->responsive) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700856 // This monitor could take more input. Drop all events preceding this
857 // event, so that gesture monitor could get a chance to receive the stream
858 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
859 "responsive gesture monitor that may handle the event",
860 mAwaitedFocusedApplication->getName().c_str());
861 return true;
862 }
863 }
864 }
865
866 // Prevent getting stuck: if we have a pending key event, and some motion events that have not
867 // yet been processed by some connections, the dispatcher will wait for these motion
868 // events to be processed before dispatching the key event. This is because these motion events
869 // may cause a new window to be launched, which the user might expect to receive focus.
870 // To prevent waiting forever for such events, just send the key to the currently focused window
871 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
872 ALOGD("Received a new pointer down event, stop waiting for events to process and "
873 "just send the pending key event to the focused window.");
874 mKeyIsWaitingForEventsTimeout = now();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700875 }
876 return false;
877}
878
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700879bool InputDispatcher::enqueueInboundEventLocked(std::unique_ptr<EventEntry> newEntry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700880 bool needWake = mInboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700881 mInboundQueue.push_back(std::move(newEntry));
882 EventEntry& entry = *(mInboundQueue.back());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800883 traceInboundQueueLengthLocked();
884
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700885 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700886 case EventEntry::Type::KEY: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700887 // Optimize app switch latency.
888 // If the application takes too long to catch up then we drop all events preceding
889 // the app switch key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700890 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700891 if (isAppSwitchKeyEvent(keyEntry)) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700892 if (keyEntry.action == AKEY_EVENT_ACTION_DOWN) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700893 mAppSwitchSawKeyDown = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700894 } else if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700895 if (mAppSwitchSawKeyDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800896#if DEBUG_APP_SWITCH
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700897 ALOGD("App switch is pending!");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800898#endif
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700899 mAppSwitchDueTime = keyEntry.eventTime + APP_SWITCH_TIMEOUT;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700900 mAppSwitchSawKeyDown = false;
901 needWake = true;
902 }
903 }
904 }
905 break;
906 }
907
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700908 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700909 if (shouldPruneInboundQueueLocked(static_cast<MotionEntry&>(entry))) {
910 mNextUnblockedEvent = mInboundQueue.back();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700911 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800912 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700913 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800914 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100915 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700916 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
917 break;
918 }
919 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -0800920 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -0700921 case EventEntry::Type::SENSOR:
Prabir Pradhan99987712020-11-10 18:43:05 -0800922 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700923 // nothing to do
924 break;
925 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800926 }
927
928 return needWake;
929}
930
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700931void InputDispatcher::addRecentEventLocked(std::shared_ptr<EventEntry> entry) {
Chris Yef59a2f42020-10-16 12:55:26 -0700932 // Do not store sensor event in recent queue to avoid flooding the queue.
933 if (entry->type != EventEntry::Type::SENSOR) {
934 mRecentQueue.push_back(entry);
935 }
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700936 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700937 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800938 }
939}
940
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700941sp<InputWindowHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, int32_t x,
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700942 int32_t y, TouchState* touchState,
943 bool addOutsideTargets,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700944 bool addPortalWindows) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700945 if ((addPortalWindows || addOutsideTargets) && touchState == nullptr) {
946 LOG_ALWAYS_FATAL(
947 "Must provide a valid touch state if adding portal windows or outside targets");
948 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800949 // Traverse windows from front to back to find touched window.
Vishnu Nairad321cd2020-08-20 16:40:21 -0700950 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800951 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800952 const InputWindowInfo* windowInfo = windowHandle->getInfo();
953 if (windowInfo->displayId == displayId) {
Michael Wright44753b12020-07-08 13:48:11 +0100954 auto flags = windowInfo->flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800955
956 if (windowInfo->visible) {
Michael Wright44753b12020-07-08 13:48:11 +0100957 if (!flags.test(InputWindowInfo::Flag::NOT_TOUCHABLE)) {
958 bool isTouchModal = !flags.test(InputWindowInfo::Flag::NOT_FOCUSABLE) &&
959 !flags.test(InputWindowInfo::Flag::NOT_TOUCH_MODAL);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800960 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800961 int32_t portalToDisplayId = windowInfo->portalToDisplayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700962 if (portalToDisplayId != ADISPLAY_ID_NONE &&
963 portalToDisplayId != displayId) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800964 if (addPortalWindows) {
965 // For the monitoring channels of the display.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700966 touchState->addPortalWindow(windowHandle);
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800967 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700968 return findTouchedWindowAtLocked(portalToDisplayId, x, y, touchState,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700969 addOutsideTargets, addPortalWindows);
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800970 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800971 // Found window.
972 return windowHandle;
973 }
974 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800975
Michael Wright44753b12020-07-08 13:48:11 +0100976 if (addOutsideTargets && flags.test(InputWindowInfo::Flag::WATCH_OUTSIDE_TOUCH)) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700977 touchState->addOrUpdateWindow(windowHandle,
978 InputTarget::FLAG_DISPATCH_AS_OUTSIDE,
979 BitSet32(0));
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800980 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800981 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800982 }
983 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700984 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800985}
986
Garfield Tane84e6f92019-08-29 17:28:41 -0700987std::vector<TouchedMonitor> InputDispatcher::findTouchedGestureMonitorsLocked(
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -0700988 int32_t displayId, const std::vector<sp<InputWindowHandle>>& portalWindows) const {
Michael Wright3dd60e22019-03-27 22:06:44 +0000989 std::vector<TouchedMonitor> touchedMonitors;
990
991 std::vector<Monitor> monitors = getValueByKey(mGestureMonitorsByDisplay, displayId);
992 addGestureMonitors(monitors, touchedMonitors);
993 for (const sp<InputWindowHandle>& portalWindow : portalWindows) {
994 const InputWindowInfo* windowInfo = portalWindow->getInfo();
995 monitors = getValueByKey(mGestureMonitorsByDisplay, windowInfo->portalToDisplayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700996 addGestureMonitors(monitors, touchedMonitors, -windowInfo->frameLeft,
997 -windowInfo->frameTop);
Michael Wright3dd60e22019-03-27 22:06:44 +0000998 }
999 return touchedMonitors;
1000}
1001
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001002void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001003 const char* reason;
1004 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001005 case DropReason::POLICY:
Michael Wrightd02c5b62014-02-10 15:10:22 -08001006#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001007 ALOGD("Dropped event because policy consumed it.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001008#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001009 reason = "inbound event was dropped because the policy consumed it";
1010 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001011 case DropReason::DISABLED:
1012 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001013 ALOGI("Dropped event because input dispatch is disabled.");
1014 }
1015 reason = "inbound event was dropped because input dispatch is disabled";
1016 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001017 case DropReason::APP_SWITCH:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001018 ALOGI("Dropped event because of pending overdue app switch.");
1019 reason = "inbound event was dropped because of pending overdue app switch";
1020 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001021 case DropReason::BLOCKED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001022 ALOGI("Dropped event because the current application is not responding and the user "
1023 "has started interacting with a different application.");
1024 reason = "inbound event was dropped because the current application is not responding "
1025 "and the user has started interacting with a different application";
1026 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001027 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001028 ALOGI("Dropped event because it is stale.");
1029 reason = "inbound event was dropped because it is stale";
1030 break;
Prabir Pradhan99987712020-11-10 18:43:05 -08001031 case DropReason::NO_POINTER_CAPTURE:
1032 ALOGI("Dropped event because there is no window with Pointer Capture.");
1033 reason = "inbound event was dropped because there is no window with Pointer Capture";
1034 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001035 case DropReason::NOT_DROPPED: {
1036 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001037 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001038 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001039 }
1040
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001041 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001042 case EventEntry::Type::KEY: {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001043 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
1044 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001045 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001046 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001047 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001048 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1049 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001050 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
1051 synthesizeCancelationEventsForAllConnectionsLocked(options);
1052 } else {
1053 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
1054 synthesizeCancelationEventsForAllConnectionsLocked(options);
1055 }
1056 break;
1057 }
Chris Yef59a2f42020-10-16 12:55:26 -07001058 case EventEntry::Type::SENSOR: {
1059 break;
1060 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001061 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
1062 break;
1063 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001064 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001065 case EventEntry::Type::CONFIGURATION_CHANGED:
1066 case EventEntry::Type::DEVICE_RESET: {
Chris Yef59a2f42020-10-16 12:55:26 -07001067 LOG_ALWAYS_FATAL("Should not drop %s events", NamedEnum::string(entry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001068 break;
1069 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001070 }
1071}
1072
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001073static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001074 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
1075 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001076}
1077
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001078bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
1079 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
1080 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
1081 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001082}
1083
1084bool InputDispatcher::isAppSwitchPendingLocked() {
1085 return mAppSwitchDueTime != LONG_LONG_MAX;
1086}
1087
1088void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
1089 mAppSwitchDueTime = LONG_LONG_MAX;
1090
1091#if DEBUG_APP_SWITCH
1092 if (handled) {
1093 ALOGD("App switch has arrived.");
1094 } else {
1095 ALOGD("App switch was abandoned.");
1096 }
1097#endif
1098}
1099
Michael Wrightd02c5b62014-02-10 15:10:22 -08001100bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001101 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001102}
1103
1104bool InputDispatcher::runCommandsLockedInterruptible() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001105 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001106 return false;
1107 }
1108
1109 do {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001110 std::unique_ptr<CommandEntry> commandEntry = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001111 mCommandQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001112 Command command = commandEntry->command;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001113 command(*this, commandEntry.get()); // commands are implicitly 'LockedInterruptible'
Michael Wrightd02c5b62014-02-10 15:10:22 -08001114
1115 commandEntry->connection.clear();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001116 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001117 return true;
1118}
1119
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001120void InputDispatcher::postCommandLocked(std::unique_ptr<CommandEntry> commandEntry) {
1121 mCommandQueue.push_back(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001122}
1123
1124void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001125 while (!mInboundQueue.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001126 std::shared_ptr<EventEntry> entry = mInboundQueue.front();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001127 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001128 releaseInboundEventLocked(entry);
1129 }
1130 traceInboundQueueLengthLocked();
1131}
1132
1133void InputDispatcher::releasePendingEventLocked() {
1134 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001135 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -07001136 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001137 }
1138}
1139
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001140void InputDispatcher::releaseInboundEventLocked(std::shared_ptr<EventEntry> entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001141 InjectionState* injectionState = entry->injectionState;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001142 if (injectionState && injectionState->injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001143#if DEBUG_DISPATCH_CYCLE
1144 ALOGD("Injected inbound event was dropped.");
1145#endif
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001146 setInjectionResult(*entry, InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001147 }
1148 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001149 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001150 }
1151 addRecentEventLocked(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001152}
1153
1154void InputDispatcher::resetKeyRepeatLocked() {
1155 if (mKeyRepeatState.lastKeyEntry) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001156 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001157 }
1158}
1159
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001160std::shared_ptr<KeyEntry> InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
1161 std::shared_ptr<KeyEntry> entry = mKeyRepeatState.lastKeyEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001162
Michael Wright2e732952014-09-24 13:26:59 -07001163 uint32_t policyFlags = entry->policyFlags &
1164 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001165
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001166 std::shared_ptr<KeyEntry> newEntry =
1167 std::make_unique<KeyEntry>(mIdGenerator.nextId(), currentTime, entry->deviceId,
1168 entry->source, entry->displayId, policyFlags, entry->action,
1169 entry->flags, entry->keyCode, entry->scanCode,
1170 entry->metaState, entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001171
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001172 newEntry->syntheticRepeat = true;
1173 mKeyRepeatState.lastKeyEntry = newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001174 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001175 return newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001176}
1177
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001178bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001179 const ConfigurationChangedEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001180#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001181 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry.eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001182#endif
1183
1184 // Reset key repeating in case a keyboard device was added or removed or something.
1185 resetKeyRepeatLocked();
1186
1187 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001188 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
1189 &InputDispatcher::doNotifyConfigurationChangedLockedInterruptible);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001190 commandEntry->eventTime = entry.eventTime;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001191 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001192 return true;
1193}
1194
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001195bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime,
1196 const DeviceResetEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001197#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001198 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry.eventTime,
1199 entry.deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001200#endif
1201
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001202 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, "device was reset");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001203 options.deviceId = entry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001204 synthesizeCancelationEventsForAllConnectionsLocked(options);
1205 return true;
1206}
1207
Vishnu Nairad321cd2020-08-20 16:40:21 -07001208void InputDispatcher::enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus,
Vishnu Nairc519ff72021-01-21 08:23:08 -08001209 const std::string& reason) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001210 if (mPendingEvent != nullptr) {
1211 // Move the pending event to the front of the queue. This will give the chance
1212 // for the pending event to get dispatched to the newly focused window
1213 mInboundQueue.push_front(mPendingEvent);
1214 mPendingEvent = nullptr;
1215 }
1216
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001217 std::unique_ptr<FocusEntry> focusEntry =
1218 std::make_unique<FocusEntry>(mIdGenerator.nextId(), now(), windowToken, hasFocus,
1219 reason);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001220
1221 // This event should go to the front of the queue, but behind all other focus events
1222 // Find the last focus event, and insert right after it
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001223 std::deque<std::shared_ptr<EventEntry>>::reverse_iterator it =
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001224 std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001225 [](const std::shared_ptr<EventEntry>& event) {
1226 return event->type == EventEntry::Type::FOCUS;
1227 });
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001228
1229 // Maintain the order of focus events. Insert the entry after all other focus events.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001230 mInboundQueue.insert(it.base(), std::move(focusEntry));
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001231}
1232
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001233void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime, std::shared_ptr<FocusEntry> entry) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05001234 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001235 if (channel == nullptr) {
1236 return; // Window has gone away
1237 }
1238 InputTarget target;
1239 target.inputChannel = channel;
1240 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1241 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001242 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
1243 channel->getName();
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001244 std::string reason = std::string("reason=").append(entry->reason);
1245 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001246 dispatchEventLocked(currentTime, entry, {target});
1247}
1248
Prabir Pradhan99987712020-11-10 18:43:05 -08001249void InputDispatcher::dispatchPointerCaptureChangedLocked(
1250 nsecs_t currentTime, const std::shared_ptr<PointerCaptureChangedEntry>& entry,
1251 DropReason& dropReason) {
1252 const bool haveWindowWithPointerCapture = mWindowTokenWithPointerCapture != nullptr;
Prabir Pradhan167e6d92021-02-04 16:18:17 -08001253 if (entry->pointerCaptureEnabled && haveWindowWithPointerCapture) {
1254 LOG_ALWAYS_FATAL("Pointer Capture has already been enabled for the window.");
1255 }
1256 if (!entry->pointerCaptureEnabled && !haveWindowWithPointerCapture) {
Prabir Pradhan99987712020-11-10 18:43:05 -08001257 // Pointer capture was already forcefully disabled because of focus change.
1258 dropReason = DropReason::NOT_DROPPED;
1259 return;
1260 }
1261
1262 // Set drop reason for early returns
1263 dropReason = DropReason::NO_POINTER_CAPTURE;
1264
1265 sp<IBinder> token;
1266 if (entry->pointerCaptureEnabled) {
1267 // Enable Pointer Capture
1268 if (!mFocusedWindowRequestedPointerCapture) {
1269 // This can happen if a window requests capture and immediately releases capture.
1270 ALOGW("No window requested Pointer Capture.");
1271 return;
1272 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08001273 token = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08001274 LOG_ALWAYS_FATAL_IF(!token, "Cannot find focused window for Pointer Capture.");
1275 mWindowTokenWithPointerCapture = token;
1276 } else {
1277 // Disable Pointer Capture
1278 token = mWindowTokenWithPointerCapture;
1279 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan7d030382020-12-21 07:58:35 -08001280 if (mFocusedWindowRequestedPointerCapture) {
1281 mFocusedWindowRequestedPointerCapture = false;
1282 setPointerCaptureLocked(false);
1283 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001284 }
1285
1286 auto channel = getInputChannelLocked(token);
1287 if (channel == nullptr) {
1288 // Window has gone away, clean up Pointer Capture state.
1289 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan7d030382020-12-21 07:58:35 -08001290 if (mFocusedWindowRequestedPointerCapture) {
1291 mFocusedWindowRequestedPointerCapture = false;
1292 setPointerCaptureLocked(false);
1293 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001294 return;
1295 }
1296 InputTarget target;
1297 target.inputChannel = channel;
1298 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1299 entry->dispatchInProgress = true;
1300 dispatchEventLocked(currentTime, entry, {target});
1301
1302 dropReason = DropReason::NOT_DROPPED;
1303}
1304
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001305bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, std::shared_ptr<KeyEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001306 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001307 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001308 if (!entry->dispatchInProgress) {
1309 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1310 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1311 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1312 if (mKeyRepeatState.lastKeyEntry &&
Chris Ye2ad95392020-09-01 13:44:44 -07001313 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode &&
Michael Wrightd02c5b62014-02-10 15:10:22 -08001314 // We have seen two identical key downs in a row which indicates that the device
1315 // driver is automatically generating key repeats itself. We take note of the
1316 // repeat here, but we disable our own next key repeat timer since it is clear that
1317 // we will not need to synthesize key repeats ourselves.
Chris Ye2ad95392020-09-01 13:44:44 -07001318 mKeyRepeatState.lastKeyEntry->deviceId == entry->deviceId) {
1319 // Make sure we don't get key down from a different device. If a different
1320 // device Id has same key pressed down, the new device Id will replace the
1321 // current one to hold the key repeat with repeat count reset.
1322 // In the future when got a KEY_UP on the device id, drop it and do not
1323 // stop the key repeat on current device.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001324 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1325 resetKeyRepeatLocked();
1326 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
1327 } else {
1328 // Not a repeat. Save key down state in case we do see a repeat later.
1329 resetKeyRepeatLocked();
1330 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1331 }
1332 mKeyRepeatState.lastKeyEntry = entry;
Chris Ye2ad95392020-09-01 13:44:44 -07001333 } else if (entry->action == AKEY_EVENT_ACTION_UP && mKeyRepeatState.lastKeyEntry &&
1334 mKeyRepeatState.lastKeyEntry->deviceId != entry->deviceId) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001335 // The key on device 'deviceId' is still down, do not stop key repeat
Chris Ye2ad95392020-09-01 13:44:44 -07001336#if DEBUG_INBOUND_EVENT_DETAILS
1337 ALOGD("deviceId=%d got KEY_UP as stale", entry->deviceId);
1338#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001339 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001340 resetKeyRepeatLocked();
1341 }
1342
1343 if (entry->repeatCount == 1) {
1344 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1345 } else {
1346 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1347 }
1348
1349 entry->dispatchInProgress = true;
1350
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001351 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001352 }
1353
1354 // Handle case where the policy asked us to try again later last time.
1355 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
1356 if (currentTime < entry->interceptKeyWakeupTime) {
1357 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1358 *nextWakeupTime = entry->interceptKeyWakeupTime;
1359 }
1360 return false; // wait until next wakeup
1361 }
1362 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
1363 entry->interceptKeyWakeupTime = 0;
1364 }
1365
1366 // Give the policy a chance to intercept the key.
1367 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
1368 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001369 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
Siarhei Vishniakou49a350a2019-07-26 18:44:23 -07001370 &InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible);
Vishnu Nairad321cd2020-08-20 16:40:21 -07001371 sp<IBinder> focusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08001372 mFocusResolver.getFocusedWindowToken(getTargetDisplayId(*entry));
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06001373 commandEntry->connectionToken = focusedWindowToken;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001374 commandEntry->keyEntry = entry;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001375 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001376 return false; // wait for the command to run
1377 } else {
1378 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
1379 }
1380 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001381 if (*dropReason == DropReason::NOT_DROPPED) {
1382 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001383 }
1384 }
1385
1386 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001387 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001388 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001389 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1390 : InputEventInjectionResult::FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001391 mReporter->reportDroppedKey(entry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001392 return true;
1393 }
1394
1395 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001396 std::vector<InputTarget> inputTargets;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001397 InputEventInjectionResult injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001398 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001399 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001400 return false;
1401 }
1402
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001403 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001404 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001405 return true;
1406 }
1407
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001408 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001409 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001410
1411 // Dispatch the key.
1412 dispatchEventLocked(currentTime, entry, inputTargets);
1413 return true;
1414}
1415
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001416void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001417#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01001418 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001419 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1420 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001421 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1422 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
1423 entry.repeatCount, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001424#endif
1425}
1426
Chris Yef59a2f42020-10-16 12:55:26 -07001427void InputDispatcher::doNotifySensorLockedInterruptible(CommandEntry* commandEntry) {
1428 mLock.unlock();
1429
1430 const std::shared_ptr<SensorEntry>& entry = commandEntry->sensorEntry;
1431 if (entry->accuracyChanged) {
1432 mPolicy->notifySensorAccuracy(entry->deviceId, entry->sensorType, entry->accuracy);
1433 }
1434 mPolicy->notifySensorEvent(entry->deviceId, entry->sensorType, entry->accuracy,
1435 entry->hwTimestamp, entry->values);
1436 mLock.lock();
1437}
1438
1439void InputDispatcher::dispatchSensorLocked(nsecs_t currentTime, std::shared_ptr<SensorEntry> entry,
1440 DropReason* dropReason, nsecs_t* nextWakeupTime) {
1441#if DEBUG_OUTBOUND_EVENT_DETAILS
1442 ALOGD("notifySensorEvent eventTime=%" PRId64 ", hwTimestamp=%" PRId64 ", deviceId=%d, "
1443 "source=0x%x, sensorType=%s",
1444 entry->eventTime, entry->hwTimestamp, entry->deviceId, entry->source,
Prabir Pradhanbe05b5b2021-02-24 16:39:43 -08001445 NamedEnum::string(entry->sensorType).c_str());
Chris Yef59a2f42020-10-16 12:55:26 -07001446#endif
1447 std::unique_ptr<CommandEntry> commandEntry =
1448 std::make_unique<CommandEntry>(&InputDispatcher::doNotifySensorLockedInterruptible);
1449 commandEntry->sensorEntry = entry;
1450 postCommandLocked(std::move(commandEntry));
1451}
1452
1453bool InputDispatcher::flushSensor(int deviceId, InputDeviceSensorType sensorType) {
1454#if DEBUG_OUTBOUND_EVENT_DETAILS
1455 ALOGD("flushSensor deviceId=%d, sensorType=%s", deviceId,
1456 NamedEnum::string(sensorType).c_str());
1457#endif
1458 { // acquire lock
1459 std::scoped_lock _l(mLock);
1460
1461 for (auto it = mInboundQueue.begin(); it != mInboundQueue.end(); it++) {
1462 std::shared_ptr<EventEntry> entry = *it;
1463 if (entry->type == EventEntry::Type::SENSOR) {
1464 it = mInboundQueue.erase(it);
1465 releaseInboundEventLocked(entry);
1466 }
1467 }
1468 }
1469 return true;
1470}
1471
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001472bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, std::shared_ptr<MotionEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001473 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001474 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001475 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001476 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001477 entry->dispatchInProgress = true;
1478
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001479 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001480 }
1481
1482 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001483 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001484 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001485 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1486 : InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001487 return true;
1488 }
1489
1490 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
1491
1492 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001493 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001494
1495 bool conflictingPointerActions = false;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001496 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001497 if (isPointerEvent) {
1498 // Pointer event. (eg. touchscreen)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001499 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001500 findTouchedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001501 &conflictingPointerActions);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001502 } else {
1503 // Non touch event. (eg. trackball)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001504 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001505 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001506 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001507 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001508 return false;
1509 }
1510
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001511 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001512 if (injectionResult == InputEventInjectionResult::PERMISSION_DENIED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001513 ALOGW("Permission denied, dropping the motion (isPointer=%s)", toString(isPointerEvent));
1514 return true;
1515 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001516 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001517 CancelationOptions::Mode mode(isPointerEvent
1518 ? CancelationOptions::CANCEL_POINTER_EVENTS
1519 : CancelationOptions::CANCEL_NON_POINTER_EVENTS);
1520 CancelationOptions options(mode, "input event injection failed");
1521 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001522 return true;
1523 }
1524
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001525 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001526 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001527
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001528 if (isPointerEvent) {
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07001529 std::unordered_map<int32_t, TouchState>::iterator it =
1530 mTouchStatesByDisplay.find(entry->displayId);
1531 if (it != mTouchStatesByDisplay.end()) {
1532 const TouchState& state = it->second;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001533 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001534 // The event has gone through these portal windows, so we add monitoring targets of
1535 // the corresponding displays as well.
1536 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001537 const InputWindowInfo* windowInfo = state.portalWindows[i]->getInfo();
Michael Wright3dd60e22019-03-27 22:06:44 +00001538 addGlobalMonitoringTargetsLocked(inputTargets, windowInfo->portalToDisplayId,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001539 -windowInfo->frameLeft, -windowInfo->frameTop);
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001540 }
1541 }
1542 }
1543 }
1544
Michael Wrightd02c5b62014-02-10 15:10:22 -08001545 // Dispatch the motion.
1546 if (conflictingPointerActions) {
1547 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001548 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001549 synthesizeCancelationEventsForAllConnectionsLocked(options);
1550 }
1551 dispatchEventLocked(currentTime, entry, inputTargets);
1552 return true;
1553}
1554
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001555void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001556#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08001557 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001558 ", policyFlags=0x%x, "
1559 "action=0x%x, actionButton=0x%x, flags=0x%x, "
1560 "metaState=0x%x, buttonState=0x%x,"
1561 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001562 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1563 entry.action, entry.actionButton, entry.flags, entry.metaState, entry.buttonState,
1564 entry.edgeFlags, entry.xPrecision, entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001565
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001566 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001567 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001568 "x=%f, y=%f, pressure=%f, size=%f, "
1569 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1570 "orientation=%f",
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001571 i, entry.pointerProperties[i].id, entry.pointerProperties[i].toolType,
1572 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1573 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1574 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1575 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1576 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1577 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1578 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1579 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1580 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001581 }
1582#endif
1583}
1584
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001585void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
1586 std::shared_ptr<EventEntry> eventEntry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001587 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001588 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001589#if DEBUG_DISPATCH_CYCLE
1590 ALOGD("dispatchEventToCurrentInputTargets");
1591#endif
1592
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001593 updateInteractionTokensLocked(*eventEntry, inputTargets);
1594
Michael Wrightd02c5b62014-02-10 15:10:22 -08001595 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1596
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001597 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001598
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001599 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001600 sp<Connection> connection =
1601 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001602 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08001603 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001604 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001605 if (DEBUG_FOCUS) {
1606 ALOGD("Dropping event delivery to target with channel '%s' because it "
1607 "is no longer registered with the input dispatcher.",
1608 inputTarget.inputChannel->getName().c_str());
1609 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001610 }
1611 }
1612}
1613
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001614void InputDispatcher::cancelEventsForAnrLocked(const sp<Connection>& connection) {
1615 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
1616 // If the policy decides to close the app, we will get a channel removal event via
1617 // unregisterInputChannel, and will clean up the connection that way. We are already not
1618 // sending new pointers to the connection when it blocked, but focused events will continue to
1619 // pile up.
1620 ALOGW("Canceling events for %s because it is unresponsive",
1621 connection->inputChannel->getName().c_str());
1622 if (connection->status == Connection::STATUS_NORMAL) {
1623 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1624 "application not responding");
1625 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001626 }
1627}
1628
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001629void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001630 if (DEBUG_FOCUS) {
1631 ALOGD("Resetting ANR timeouts.");
1632 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001633
1634 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001635 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07001636 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001637}
1638
Tiger Huang721e26f2018-07-24 22:26:19 +08001639/**
1640 * Get the display id that the given event should go to. If this event specifies a valid display id,
1641 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1642 * Focused display is the display that the user most recently interacted with.
1643 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001644int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001645 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001646 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001647 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001648 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1649 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001650 break;
1651 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001652 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001653 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1654 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001655 break;
1656 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001657 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001658 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001659 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07001660 case EventEntry::Type::DEVICE_RESET:
1661 case EventEntry::Type::SENSOR: {
1662 ALOGE("%s events do not have a target display", NamedEnum::string(entry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001663 return ADISPLAY_ID_NONE;
1664 }
Tiger Huang721e26f2018-07-24 22:26:19 +08001665 }
1666 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1667}
1668
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001669bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
1670 const char* focusedWindowName) {
1671 if (mAnrTracker.empty()) {
1672 // already processed all events that we waited for
1673 mKeyIsWaitingForEventsTimeout = std::nullopt;
1674 return false;
1675 }
1676
1677 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
1678 // Start the timer
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00001679 // Wait to send key because there are unprocessed events that may cause focus to change
Siarhei Vishniakou70622952020-07-30 11:17:23 -05001680 mKeyIsWaitingForEventsTimeout = currentTime +
1681 std::chrono::duration_cast<std::chrono::nanoseconds>(KEY_WAITING_FOR_EVENTS_TIMEOUT)
1682 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001683 return true;
1684 }
1685
1686 // We still have pending events, and already started the timer
1687 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
1688 return true; // Still waiting
1689 }
1690
1691 // Waited too long, and some connection still hasn't processed all motions
1692 // Just send the key to the focused window
1693 ALOGW("Dispatching key to %s even though there are other unprocessed events",
1694 focusedWindowName);
1695 mKeyIsWaitingForEventsTimeout = std::nullopt;
1696 return false;
1697}
1698
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001699InputEventInjectionResult InputDispatcher::findFocusedWindowTargetsLocked(
1700 nsecs_t currentTime, const EventEntry& entry, std::vector<InputTarget>& inputTargets,
1701 nsecs_t* nextWakeupTime) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001702 std::string reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001703
Tiger Huang721e26f2018-07-24 22:26:19 +08001704 int32_t displayId = getTargetDisplayId(entry);
Vishnu Nairad321cd2020-08-20 16:40:21 -07001705 sp<InputWindowHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07001706 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08001707 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1708
Michael Wrightd02c5b62014-02-10 15:10:22 -08001709 // If there is no currently focused window and no focused application
1710 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001711 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
1712 ALOGI("Dropping %s event because there is no focused window or focused application in "
1713 "display %" PRId32 ".",
Chris Yef59a2f42020-10-16 12:55:26 -07001714 NamedEnum::string(entry.type).c_str(), displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001715 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001716 }
1717
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001718 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
1719 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
1720 // start interacting with another application via touch (app switch). This code can be removed
1721 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
1722 // an app is expected to have a focused window.
1723 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
1724 if (!mNoFocusedWindowTimeoutTime.has_value()) {
1725 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001726 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
1727 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
1728 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001729 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05001730 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001731 ALOGW("Waiting because no window has focus but %s may eventually add a "
1732 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001733 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001734 *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001735 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001736 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
1737 // Already raised ANR. Drop the event
1738 ALOGE("Dropping %s event because there is no focused window",
Chris Yef59a2f42020-10-16 12:55:26 -07001739 NamedEnum::string(entry.type).c_str());
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001740 return InputEventInjectionResult::FAILED;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001741 } else {
1742 // Still waiting for the focused window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001743 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001744 }
1745 }
1746
1747 // we have a valid, non-null focused window
1748 resetNoFocusedWindowTimeoutLocked();
1749
Michael Wrightd02c5b62014-02-10 15:10:22 -08001750 // Check permissions.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001751 if (!checkInjectionPermission(focusedWindowHandle, entry.injectionState)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001752 return InputEventInjectionResult::PERMISSION_DENIED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001753 }
1754
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001755 if (focusedWindowHandle->getInfo()->paused) {
1756 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001757 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001758 }
1759
1760 // If the event is a key event, then we must wait for all previous events to
1761 // complete before delivering it because previous events may have the
1762 // side-effect of transferring focus to a different window and we want to
1763 // ensure that the following keys are sent to the new window.
1764 //
1765 // Suppose the user touches a button in a window then immediately presses "A".
1766 // If the button causes a pop-up window to appear then we want to ensure that
1767 // the "A" key is delivered to the new pop-up window. This is because users
1768 // often anticipate pending UI changes when typing on a keyboard.
1769 // To obtain this behavior, we must serialize key events with respect to all
1770 // prior input events.
1771 if (entry.type == EventEntry::Type::KEY) {
1772 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
1773 *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001774 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001775 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001776 }
1777
1778 // Success! Output targets.
Tiger Huang721e26f2018-07-24 22:26:19 +08001779 addWindowTargetLocked(focusedWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001780 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS,
1781 BitSet32(0), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001782
1783 // Done.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001784 return InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001785}
1786
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001787/**
1788 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
1789 * that are currently unresponsive.
1790 */
1791std::vector<TouchedMonitor> InputDispatcher::selectResponsiveMonitorsLocked(
1792 const std::vector<TouchedMonitor>& monitors) const {
1793 std::vector<TouchedMonitor> responsiveMonitors;
1794 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
1795 [this](const TouchedMonitor& monitor) REQUIRES(mLock) {
1796 sp<Connection> connection = getConnectionLocked(
1797 monitor.monitor.inputChannel->getConnectionToken());
1798 if (connection == nullptr) {
1799 ALOGE("Could not find connection for monitor %s",
1800 monitor.monitor.inputChannel->getName().c_str());
1801 return false;
1802 }
1803 if (!connection->responsive) {
1804 ALOGW("Unresponsive monitor %s will not get the new gesture",
1805 connection->inputChannel->getName().c_str());
1806 return false;
1807 }
1808 return true;
1809 });
1810 return responsiveMonitors;
1811}
1812
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001813InputEventInjectionResult InputDispatcher::findTouchedWindowTargetsLocked(
1814 nsecs_t currentTime, const MotionEntry& entry, std::vector<InputTarget>& inputTargets,
1815 nsecs_t* nextWakeupTime, bool* outConflictingPointerActions) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001816 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001817 enum InjectionPermission {
1818 INJECTION_PERMISSION_UNKNOWN,
1819 INJECTION_PERMISSION_GRANTED,
1820 INJECTION_PERMISSION_DENIED
1821 };
1822
Michael Wrightd02c5b62014-02-10 15:10:22 -08001823 // For security reasons, we defer updating the touch state until we are sure that
1824 // event injection will be allowed.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001825 int32_t displayId = entry.displayId;
1826 int32_t action = entry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001827 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
1828
1829 // Update the touch state as needed based on the properties of the touch event.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001830 InputEventInjectionResult injectionResult = InputEventInjectionResult::PENDING;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001831 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
Garfield Tandf26e862020-07-01 20:18:19 -07001832 sp<InputWindowHandle> newHoverWindowHandle(mLastHoverWindowHandle);
1833 sp<InputWindowHandle> newTouchedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001834
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001835 // Copy current touch state into tempTouchState.
1836 // This state will be used to update mTouchStatesByDisplay at the end of this function.
1837 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07001838 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001839 TouchState tempTouchState;
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07001840 std::unordered_map<int32_t, TouchState>::iterator oldStateIt =
1841 mTouchStatesByDisplay.find(displayId);
1842 if (oldStateIt != mTouchStatesByDisplay.end()) {
1843 oldState = &(oldStateIt->second);
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001844 tempTouchState.copyFrom(*oldState);
Jeff Brownf086ddb2014-02-11 14:28:48 -08001845 }
1846
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001847 bool isSplit = tempTouchState.split;
1848 bool switchedDevice = tempTouchState.deviceId >= 0 && tempTouchState.displayId >= 0 &&
1849 (tempTouchState.deviceId != entry.deviceId || tempTouchState.source != entry.source ||
1850 tempTouchState.displayId != displayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001851 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
1852 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
1853 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
1854 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN ||
1855 maskedAction == AMOTION_EVENT_ACTION_SCROLL || isHoverAction);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001856 const bool isFromMouse = entry.source == AINPUT_SOURCE_MOUSE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001857 bool wrongDevice = false;
1858 if (newGesture) {
1859 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001860 if (switchedDevice && tempTouchState.down && !down && !isHoverAction) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001861 ALOGI("Dropping event because a pointer for a different device is already down "
1862 "in display %" PRId32,
1863 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001864 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001865 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001866 switchedDevice = false;
1867 wrongDevice = true;
1868 goto Failed;
1869 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001870 tempTouchState.reset();
1871 tempTouchState.down = down;
1872 tempTouchState.deviceId = entry.deviceId;
1873 tempTouchState.source = entry.source;
1874 tempTouchState.displayId = displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001875 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001876 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001877 ALOGI("Dropping move event because a pointer for a different device is already active "
1878 "in display %" PRId32,
1879 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001880 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001881 injectionResult = InputEventInjectionResult::PERMISSION_DENIED;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001882 switchedDevice = false;
1883 wrongDevice = true;
1884 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001885 }
1886
1887 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
1888 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
1889
Garfield Tan00f511d2019-06-12 16:55:40 -07001890 int32_t x;
1891 int32_t y;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001892 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Garfield Tan00f511d2019-06-12 16:55:40 -07001893 // Always dispatch mouse events to cursor position.
1894 if (isFromMouse) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001895 x = int32_t(entry.xCursorPosition);
1896 y = int32_t(entry.yCursorPosition);
Garfield Tan00f511d2019-06-12 16:55:40 -07001897 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001898 x = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X));
1899 y = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y));
Garfield Tan00f511d2019-06-12 16:55:40 -07001900 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001901 bool isDown = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Garfield Tandf26e862020-07-01 20:18:19 -07001902 newTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001903 findTouchedWindowAtLocked(displayId, x, y, &tempTouchState,
1904 isDown /*addOutsideTargets*/, true /*addPortalWindows*/);
Michael Wright3dd60e22019-03-27 22:06:44 +00001905
1906 std::vector<TouchedMonitor> newGestureMonitors = isDown
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001907 ? findTouchedGestureMonitorsLocked(displayId, tempTouchState.portalWindows)
Michael Wright3dd60e22019-03-27 22:06:44 +00001908 : std::vector<TouchedMonitor>{};
Michael Wrightd02c5b62014-02-10 15:10:22 -08001909
Michael Wrightd02c5b62014-02-10 15:10:22 -08001910 // Figure out whether splitting will be allowed for this window.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001911 if (newTouchedWindowHandle != nullptr &&
1912 newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Garfield Tanaddb02b2019-06-25 16:36:13 -07001913 // New window supports splitting, but we should never split mouse events.
1914 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001915 } else if (isSplit) {
1916 // New window does not support splitting but we have already split events.
1917 // Ignore the new window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001918 newTouchedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001919 }
1920
1921 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001922 if (newTouchedWindowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001923 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001924 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001925 }
1926
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001927 if (newTouchedWindowHandle != nullptr && newTouchedWindowHandle->getInfo()->paused) {
1928 ALOGI("Not sending touch event to %s because it is paused",
1929 newTouchedWindowHandle->getName().c_str());
1930 newTouchedWindowHandle = nullptr;
1931 }
1932
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001933 // Ensure the window has a connection and the connection is responsive
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001934 if (newTouchedWindowHandle != nullptr) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001935 const bool isResponsive = hasResponsiveConnectionLocked(*newTouchedWindowHandle);
1936 if (!isResponsive) {
1937 ALOGW("%s will not receive the new gesture at %" PRIu64,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001938 newTouchedWindowHandle->getName().c_str(), entry.eventTime);
1939 newTouchedWindowHandle = nullptr;
1940 }
1941 }
1942
Bernardo Rufinoea97d182020-08-19 14:43:14 +01001943 // Drop events that can't be trusted due to occlusion
1944 if (newTouchedWindowHandle != nullptr &&
1945 mBlockUntrustedTouchesMode != BlockUntrustedTouchesMode::DISABLED) {
1946 TouchOcclusionInfo occlusionInfo =
1947 computeTouchOcclusionInfoLocked(newTouchedWindowHandle, x, y);
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00001948 if (!isTouchTrustedLocked(occlusionInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00001949 if (DEBUG_TOUCH_OCCLUSION) {
1950 ALOGD("Stack of obscuring windows during untrusted touch (%d, %d):", x, y);
1951 for (const auto& log : occlusionInfo.debugInfo) {
1952 ALOGD("%s", log.c_str());
1953 }
1954 }
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00001955 onUntrustedTouchLocked(occlusionInfo.obscuringPackage);
1956 if (mBlockUntrustedTouchesMode == BlockUntrustedTouchesMode::BLOCK) {
1957 ALOGW("Dropping untrusted touch event due to %s/%d",
1958 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid);
1959 newTouchedWindowHandle = nullptr;
1960 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01001961 }
1962 }
1963
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001964 // Also don't send the new touch event to unresponsive gesture monitors
1965 newGestureMonitors = selectResponsiveMonitorsLocked(newGestureMonitors);
1966
Michael Wright3dd60e22019-03-27 22:06:44 +00001967 if (newTouchedWindowHandle == nullptr && newGestureMonitors.empty()) {
1968 ALOGI("Dropping event because there is no touchable window or gesture monitor at "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001969 "(%d, %d) in display %" PRId32 ".",
1970 x, y, displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001971 injectionResult = InputEventInjectionResult::FAILED;
Michael Wright3dd60e22019-03-27 22:06:44 +00001972 goto Failed;
1973 }
1974
1975 if (newTouchedWindowHandle != nullptr) {
1976 // Set target flags.
1977 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
1978 if (isSplit) {
1979 targetFlags |= InputTarget::FLAG_SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001980 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001981 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1982 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1983 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
1984 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1985 }
1986
1987 // Update hover state.
Garfield Tandf26e862020-07-01 20:18:19 -07001988 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
1989 newHoverWindowHandle = nullptr;
1990 } else if (isHoverAction) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001991 newHoverWindowHandle = newTouchedWindowHandle;
Michael Wright3dd60e22019-03-27 22:06:44 +00001992 }
1993
1994 // Update the temporary touch state.
1995 BitSet32 pointerIds;
1996 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001997 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wright3dd60e22019-03-27 22:06:44 +00001998 pointerIds.markBit(pointerId);
1999 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002000 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002001 }
2002
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002003 tempTouchState.addGestureMonitors(newGestureMonitors);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002004 } else {
2005 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
2006
2007 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002008 if (!tempTouchState.down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002009 if (DEBUG_FOCUS) {
2010 ALOGD("Dropping event because the pointer is not down or we previously "
2011 "dropped the pointer down event in display %" PRId32,
2012 displayId);
2013 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002014 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002015 goto Failed;
2016 }
2017
2018 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002019 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002020 tempTouchState.isSlippery()) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002021 int32_t x = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
2022 int32_t y = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002023
2024 sp<InputWindowHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002025 tempTouchState.getFirstForegroundWindowHandle();
Garfield Tandf26e862020-07-01 20:18:19 -07002026 newTouchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y, &tempTouchState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002027 if (oldTouchedWindowHandle != newTouchedWindowHandle &&
2028 oldTouchedWindowHandle != nullptr && newTouchedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002029 if (DEBUG_FOCUS) {
2030 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
2031 oldTouchedWindowHandle->getName().c_str(),
2032 newTouchedWindowHandle->getName().c_str(), displayId);
2033 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002034 // Make a slippery exit from the old window.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002035 tempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
2036 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT,
2037 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002038
2039 // Make a slippery entrance into the new window.
2040 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
2041 isSplit = true;
2042 }
2043
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002044 int32_t targetFlags =
2045 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002046 if (isSplit) {
2047 targetFlags |= InputTarget::FLAG_SPLIT;
2048 }
2049 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
2050 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002051 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
2052 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002053 }
2054
2055 BitSet32 pointerIds;
2056 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002057 pointerIds.markBit(entry.pointerProperties[0].id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002058 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002059 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002060 }
2061 }
2062 }
2063
2064 if (newHoverWindowHandle != mLastHoverWindowHandle) {
Garfield Tandf26e862020-07-01 20:18:19 -07002065 // Let the previous window know that the hover sequence is over, unless we already did it
2066 // when dispatching it as is to newTouchedWindowHandle.
2067 if (mLastHoverWindowHandle != nullptr &&
2068 (maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT ||
2069 mLastHoverWindowHandle != newTouchedWindowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002070#if DEBUG_HOVER
2071 ALOGD("Sending hover exit event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002072 mLastHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002073#endif
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002074 tempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
2075 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002076 }
2077
Garfield Tandf26e862020-07-01 20:18:19 -07002078 // Let the new window know that the hover sequence is starting, unless we already did it
2079 // when dispatching it as is to newTouchedWindowHandle.
2080 if (newHoverWindowHandle != nullptr &&
2081 (maskedAction != AMOTION_EVENT_ACTION_HOVER_ENTER ||
2082 newHoverWindowHandle != newTouchedWindowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002083#if DEBUG_HOVER
2084 ALOGD("Sending hover enter event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002085 newHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002086#endif
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002087 tempTouchState.addOrUpdateWindow(newHoverWindowHandle,
2088 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER,
2089 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002090 }
2091 }
2092
2093 // Check permission to inject into all touched foreground windows and ensure there
2094 // is at least one touched foreground window.
2095 {
2096 bool haveForegroundWindow = false;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002097 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002098 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
2099 haveForegroundWindow = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002100 if (!checkInjectionPermission(touchedWindow.windowHandle, entry.injectionState)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002101 injectionResult = InputEventInjectionResult::PERMISSION_DENIED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002102 injectionPermission = INJECTION_PERMISSION_DENIED;
2103 goto Failed;
2104 }
2105 }
2106 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002107 bool hasGestureMonitor = !tempTouchState.gestureMonitors.empty();
Michael Wright3dd60e22019-03-27 22:06:44 +00002108 if (!haveForegroundWindow && !hasGestureMonitor) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002109 ALOGI("Dropping event because there is no touched foreground window in display "
2110 "%" PRId32 " or gesture monitor to receive it.",
2111 displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002112 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002113 goto Failed;
2114 }
2115
2116 // Permission granted to injection into all touched foreground windows.
2117 injectionPermission = INJECTION_PERMISSION_GRANTED;
2118 }
2119
2120 // Check whether windows listening for outside touches are owned by the same UID. If it is
2121 // set the policy flag that we will not reveal coordinate information to this window.
2122 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2123 sp<InputWindowHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002124 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002125 if (foregroundWindowHandle) {
2126 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002127 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002128 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2129 sp<InputWindowHandle> inputWindowHandle = touchedWindow.windowHandle;
2130 if (inputWindowHandle->getInfo()->ownerUid != foregroundWindowUid) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002131 tempTouchState.addOrUpdateWindow(inputWindowHandle,
2132 InputTarget::FLAG_ZERO_COORDS,
2133 BitSet32(0));
Michael Wright3dd60e22019-03-27 22:06:44 +00002134 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002135 }
2136 }
2137 }
2138 }
2139
Michael Wrightd02c5b62014-02-10 15:10:22 -08002140 // If this is the first pointer going down and the touched window has a wallpaper
2141 // then also add the touched wallpaper windows so they are locked in for the duration
2142 // of the touch gesture.
2143 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
2144 // engine only supports touch events. We would need to add a mechanism similar
2145 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
2146 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2147 sp<InputWindowHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002148 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002149 if (foregroundWindowHandle && foregroundWindowHandle->getInfo()->hasWallpaper) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07002150 const std::vector<sp<InputWindowHandle>>& windowHandles =
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002151 getWindowHandlesLocked(displayId);
2152 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002153 const InputWindowInfo* info = windowHandle->getInfo();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002154 if (info->displayId == displayId &&
Michael Wright44753b12020-07-08 13:48:11 +01002155 windowHandle->getInfo()->type == InputWindowInfo::Type::WALLPAPER) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002156 tempTouchState
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002157 .addOrUpdateWindow(windowHandle,
2158 InputTarget::FLAG_WINDOW_IS_OBSCURED |
2159 InputTarget::
2160 FLAG_WINDOW_IS_PARTIALLY_OBSCURED |
2161 InputTarget::FLAG_DISPATCH_AS_IS,
2162 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002163 }
2164 }
2165 }
2166 }
2167
2168 // Success! Output targets.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002169 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002170
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002171 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002172 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002173 touchedWindow.pointerIds, inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002174 }
2175
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002176 for (const TouchedMonitor& touchedMonitor : tempTouchState.gestureMonitors) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002177 addMonitoringTargetLocked(touchedMonitor.monitor, touchedMonitor.xOffset,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002178 touchedMonitor.yOffset, inputTargets);
Michael Wright3dd60e22019-03-27 22:06:44 +00002179 }
2180
Michael Wrightd02c5b62014-02-10 15:10:22 -08002181 // Drop the outside or hover touch windows since we will not care about them
2182 // in the next iteration.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002183 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002184
2185Failed:
2186 // Check injection permission once and for all.
2187 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002188 if (checkInjectionPermission(nullptr, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002189 injectionPermission = INJECTION_PERMISSION_GRANTED;
2190 } else {
2191 injectionPermission = INJECTION_PERMISSION_DENIED;
2192 }
2193 }
2194
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002195 if (injectionPermission != INJECTION_PERMISSION_GRANTED) {
2196 return injectionResult;
2197 }
2198
Michael Wrightd02c5b62014-02-10 15:10:22 -08002199 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002200 if (!wrongDevice) {
2201 if (switchedDevice) {
2202 if (DEBUG_FOCUS) {
2203 ALOGD("Conflicting pointer actions: Switched to a different device.");
2204 }
2205 *outConflictingPointerActions = true;
2206 }
2207
2208 if (isHoverAction) {
2209 // Started hovering, therefore no longer down.
2210 if (oldState && oldState->down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002211 if (DEBUG_FOCUS) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002212 ALOGD("Conflicting pointer actions: Hover received while pointer was "
2213 "down.");
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002214 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002215 *outConflictingPointerActions = true;
2216 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002217 tempTouchState.reset();
2218 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2219 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
2220 tempTouchState.deviceId = entry.deviceId;
2221 tempTouchState.source = entry.source;
2222 tempTouchState.displayId = displayId;
2223 }
2224 } else if (maskedAction == AMOTION_EVENT_ACTION_UP ||
2225 maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
2226 // All pointers up or canceled.
2227 tempTouchState.reset();
2228 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2229 // First pointer went down.
2230 if (oldState && oldState->down) {
2231 if (DEBUG_FOCUS) {
2232 ALOGD("Conflicting pointer actions: Down received while already down.");
2233 }
2234 *outConflictingPointerActions = true;
2235 }
2236 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2237 // One pointer went up.
2238 if (isSplit) {
2239 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2240 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002241
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002242 for (size_t i = 0; i < tempTouchState.windows.size();) {
2243 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2244 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
2245 touchedWindow.pointerIds.clearBit(pointerId);
2246 if (touchedWindow.pointerIds.isEmpty()) {
2247 tempTouchState.windows.erase(tempTouchState.windows.begin() + i);
2248 continue;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002249 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002250 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002251 i += 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002252 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002253 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002254 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002255
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002256 // Save changes unless the action was scroll in which case the temporary touch
2257 // state was only valid for this one action.
2258 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
2259 if (tempTouchState.displayId >= 0) {
2260 mTouchStatesByDisplay[displayId] = tempTouchState;
2261 } else {
2262 mTouchStatesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002263 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002264 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002265
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002266 // Update hover state.
2267 mLastHoverWindowHandle = newHoverWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002268 }
2269
Michael Wrightd02c5b62014-02-10 15:10:22 -08002270 return injectionResult;
2271}
2272
2273void InputDispatcher::addWindowTargetLocked(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002274 int32_t targetFlags, BitSet32 pointerIds,
2275 std::vector<InputTarget>& inputTargets) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002276 std::vector<InputTarget>::iterator it =
2277 std::find_if(inputTargets.begin(), inputTargets.end(),
2278 [&windowHandle](const InputTarget& inputTarget) {
2279 return inputTarget.inputChannel->getConnectionToken() ==
2280 windowHandle->getToken();
2281 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002282
Chavi Weingarten114b77f2020-01-15 22:35:10 +00002283 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002284
2285 if (it == inputTargets.end()) {
2286 InputTarget inputTarget;
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05002287 std::shared_ptr<InputChannel> inputChannel =
2288 getInputChannelLocked(windowHandle->getToken());
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002289 if (inputChannel == nullptr) {
2290 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
2291 return;
2292 }
2293 inputTarget.inputChannel = inputChannel;
2294 inputTarget.flags = targetFlags;
2295 inputTarget.globalScaleFactor = windowInfo->globalScaleFactor;
2296 inputTargets.push_back(inputTarget);
2297 it = inputTargets.end() - 1;
2298 }
2299
2300 ALOG_ASSERT(it->flags == targetFlags);
2301 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
2302
chaviw1ff3d1e2020-07-01 15:53:47 -07002303 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002304}
2305
Michael Wright3dd60e22019-03-27 22:06:44 +00002306void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002307 int32_t displayId, float xOffset,
2308 float yOffset) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002309 std::unordered_map<int32_t, std::vector<Monitor>>::const_iterator it =
2310 mGlobalMonitorsByDisplay.find(displayId);
2311
2312 if (it != mGlobalMonitorsByDisplay.end()) {
2313 const std::vector<Monitor>& monitors = it->second;
2314 for (const Monitor& monitor : monitors) {
2315 addMonitoringTargetLocked(monitor, xOffset, yOffset, inputTargets);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002316 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002317 }
2318}
2319
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002320void InputDispatcher::addMonitoringTargetLocked(const Monitor& monitor, float xOffset,
2321 float yOffset,
2322 std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002323 InputTarget target;
2324 target.inputChannel = monitor.inputChannel;
2325 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
chaviw1ff3d1e2020-07-01 15:53:47 -07002326 ui::Transform t;
2327 t.set(xOffset, yOffset);
2328 target.setDefaultPointerTransform(t);
Michael Wright3dd60e22019-03-27 22:06:44 +00002329 inputTargets.push_back(target);
2330}
2331
Michael Wrightd02c5b62014-02-10 15:10:22 -08002332bool InputDispatcher::checkInjectionPermission(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002333 const InjectionState* injectionState) {
2334 if (injectionState &&
2335 (windowHandle == nullptr ||
2336 windowHandle->getInfo()->ownerUid != injectionState->injectorUid) &&
2337 !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002338 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002339 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002340 "owned by uid %d",
2341 injectionState->injectorPid, injectionState->injectorUid,
2342 windowHandle->getName().c_str(), windowHandle->getInfo()->ownerUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002343 } else {
2344 ALOGW("Permission denied: injecting event from pid %d uid %d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002345 injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002346 }
2347 return false;
2348 }
2349 return true;
2350}
2351
Robert Carrc9bf1d32020-04-13 17:21:08 -07002352/**
2353 * Indicate whether one window handle should be considered as obscuring
2354 * another window handle. We only check a few preconditions. Actually
2355 * checking the bounds is left to the caller.
2356 */
2357static bool canBeObscuredBy(const sp<InputWindowHandle>& windowHandle,
2358 const sp<InputWindowHandle>& otherHandle) {
2359 // Compare by token so cloned layers aren't counted
2360 if (haveSameToken(windowHandle, otherHandle)) {
2361 return false;
2362 }
2363 auto info = windowHandle->getInfo();
2364 auto otherInfo = otherHandle->getInfo();
2365 if (!otherInfo->visible) {
2366 return false;
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002367 } else if (otherInfo->alpha == 0 &&
2368 otherInfo->flags.test(InputWindowInfo::Flag::NOT_TOUCHABLE)) {
2369 // Those act as if they were invisible, so we don't need to flag them.
2370 // We do want to potentially flag touchable windows even if they have 0
2371 // opacity, since they can consume touches and alter the effects of the
2372 // user interaction (eg. apps that rely on
2373 // FLAG_WINDOW_IS_PARTIALLY_OBSCURED should still be told about those
2374 // windows), hence we also check for FLAG_NOT_TOUCHABLE.
2375 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00002376 } else if (info->ownerUid == otherInfo->ownerUid) {
2377 // If ownerUid is the same we don't generate occlusion events as there
2378 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002379 return false;
Chris Yefcdff3e2020-05-10 15:16:04 -07002380 } else if (otherInfo->trustedOverlay) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002381 return false;
2382 } else if (otherInfo->displayId != info->displayId) {
2383 return false;
2384 }
2385 return true;
2386}
2387
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002388/**
2389 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
2390 * untrusted, one should check:
2391 *
2392 * 1. If result.hasBlockingOcclusion is true.
2393 * If it's, it means the touch should be blocked due to a window with occlusion mode of
2394 * BLOCK_UNTRUSTED.
2395 *
2396 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
2397 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
2398 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
2399 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
2400 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
2401 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
2402 *
2403 * If neither of those is true, then it means the touch can be allowed.
2404 */
2405InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
2406 const sp<InputWindowHandle>& windowHandle, int32_t x, int32_t y) const {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002407 const InputWindowInfo* windowInfo = windowHandle->getInfo();
2408 int32_t displayId = windowInfo->displayId;
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002409 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2410 TouchOcclusionInfo info;
2411 info.hasBlockingOcclusion = false;
2412 info.obscuringOpacity = 0;
2413 info.obscuringUid = -1;
2414 std::map<int32_t, float> opacityByUid;
2415 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
2416 if (windowHandle == otherHandle) {
2417 break; // All future windows are below us. Exit early.
2418 }
2419 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Bernardo Rufino1ff9d592021-01-18 16:58:57 +00002420 if (canBeObscuredBy(windowHandle, otherHandle) && otherInfo->frameContainsPoint(x, y) &&
2421 !haveSameApplicationToken(windowInfo, otherInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002422 if (DEBUG_TOUCH_OCCLUSION) {
2423 info.debugInfo.push_back(
2424 dumpWindowForTouchOcclusion(otherInfo, /* isTouchedWindow */ false));
2425 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002426 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
2427 // we perform the checks below to see if the touch can be propagated or not based on the
2428 // window's touch occlusion mode
2429 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
2430 info.hasBlockingOcclusion = true;
2431 info.obscuringUid = otherInfo->ownerUid;
2432 info.obscuringPackage = otherInfo->packageName;
2433 break;
2434 }
2435 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
2436 uint32_t uid = otherInfo->ownerUid;
2437 float opacity =
2438 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
2439 // Given windows A and B:
2440 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
2441 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
2442 opacityByUid[uid] = opacity;
2443 if (opacity > info.obscuringOpacity) {
2444 info.obscuringOpacity = opacity;
2445 info.obscuringUid = uid;
2446 info.obscuringPackage = otherInfo->packageName;
2447 }
2448 }
2449 }
2450 }
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002451 if (DEBUG_TOUCH_OCCLUSION) {
2452 info.debugInfo.push_back(
2453 dumpWindowForTouchOcclusion(windowInfo, /* isTouchedWindow */ true));
2454 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002455 return info;
2456}
2457
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002458std::string InputDispatcher::dumpWindowForTouchOcclusion(const InputWindowInfo* info,
2459 bool isTouchedWindow) const {
Bernardo Rufino49d99e42021-01-18 15:16:59 +00002460 return StringPrintf(INDENT2
2461 "* %stype=%s, package=%s/%" PRId32 ", id=%" PRId32 ", mode=%s, alpha=%.2f, "
2462 "frame=[%" PRId32 ",%" PRId32 "][%" PRId32 ",%" PRId32
2463 "], touchableRegion=%s, window={%s}, flags={%s}, inputFeatures={%s}, "
2464 "hasToken=%s, applicationInfo.name=%s, applicationInfo.token=%s\n",
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002465 (isTouchedWindow) ? "[TOUCHED] " : "",
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00002466 NamedEnum::string(info->type, "%" PRId32).c_str(),
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00002467 info->packageName.c_str(), info->ownerUid, info->id,
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00002468 toString(info->touchOcclusionMode).c_str(), info->alpha, info->frameLeft,
2469 info->frameTop, info->frameRight, info->frameBottom,
2470 dumpRegion(info->touchableRegion).c_str(), info->name.c_str(),
Bernardo Rufino49d99e42021-01-18 15:16:59 +00002471 info->flags.string().c_str(), info->inputFeatures.string().c_str(),
2472 toString(info->token != nullptr), info->applicationInfo.name.c_str(),
2473 toString(info->applicationInfo.token).c_str());
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002474}
2475
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002476bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
2477 if (occlusionInfo.hasBlockingOcclusion) {
2478 ALOGW("Untrusted touch due to occlusion by %s/%d", occlusionInfo.obscuringPackage.c_str(),
2479 occlusionInfo.obscuringUid);
2480 return false;
2481 }
2482 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
2483 ALOGW("Untrusted touch due to occlusion by %s/%d (obscuring opacity = "
2484 "%.2f, maximum allowed = %.2f)",
2485 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid,
2486 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
2487 return false;
2488 }
2489 return true;
2490}
2491
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002492bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<InputWindowHandle>& windowHandle,
2493 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002494 int32_t displayId = windowHandle->getInfo()->displayId;
Vishnu Nairad321cd2020-08-20 16:40:21 -07002495 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002496 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002497 if (windowHandle == otherHandle) {
2498 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002499 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002500 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002501 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002502 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002503 return true;
2504 }
2505 }
2506 return false;
2507}
2508
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002509bool InputDispatcher::isWindowObscuredLocked(const sp<InputWindowHandle>& windowHandle) const {
2510 int32_t displayId = windowHandle->getInfo()->displayId;
Vishnu Nairad321cd2020-08-20 16:40:21 -07002511 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002512 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002513 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002514 if (windowHandle == otherHandle) {
2515 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002516 }
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002517 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002518 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002519 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002520 return true;
2521 }
2522 }
2523 return false;
2524}
2525
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002526std::string InputDispatcher::getApplicationWindowLabel(
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05002527 const InputApplicationHandle* applicationHandle,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002528 const sp<InputWindowHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002529 if (applicationHandle != nullptr) {
2530 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002531 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002532 } else {
2533 return applicationHandle->getName();
2534 }
Yi Kong9b14ac62018-07-17 13:48:38 -07002535 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002536 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002537 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002538 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002539 }
2540}
2541
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002542void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Prabir Pradhan99987712020-11-10 18:43:05 -08002543 if (eventEntry.type == EventEntry::Type::FOCUS ||
2544 eventEntry.type == EventEntry::Type::POINTER_CAPTURE_CHANGED) {
2545 // Focus or pointer capture changed events are passed to apps, but do not represent user
2546 // activity.
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002547 return;
2548 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002549 int32_t displayId = getTargetDisplayId(eventEntry);
Vishnu Nairad321cd2020-08-20 16:40:21 -07002550 sp<InputWindowHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Tiger Huang721e26f2018-07-24 22:26:19 +08002551 if (focusedWindowHandle != nullptr) {
2552 const InputWindowInfo* info = focusedWindowHandle->getInfo();
Michael Wright44753b12020-07-08 13:48:11 +01002553 if (info->inputFeatures.test(InputWindowInfo::Feature::DISABLE_USER_ACTIVITY)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002554#if DEBUG_DISPATCH_CYCLE
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002555 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002556#endif
2557 return;
2558 }
2559 }
2560
2561 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002562 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002563 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002564 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
2565 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002566 return;
2567 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002568
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002569 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002570 eventType = USER_ACTIVITY_EVENT_TOUCH;
2571 }
2572 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002573 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002574 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002575 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
2576 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002577 return;
2578 }
2579 eventType = USER_ACTIVITY_EVENT_BUTTON;
2580 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002581 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002582 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002583 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08002584 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07002585 case EventEntry::Type::SENSOR:
Prabir Pradhan99987712020-11-10 18:43:05 -08002586 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002587 LOG_ALWAYS_FATAL("%s events are not user activity",
Chris Yef59a2f42020-10-16 12:55:26 -07002588 NamedEnum::string(eventEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002589 break;
2590 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002591 }
2592
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002593 std::unique_ptr<CommandEntry> commandEntry =
2594 std::make_unique<CommandEntry>(&InputDispatcher::doPokeUserActivityLockedInterruptible);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002595 commandEntry->eventTime = eventEntry.eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002596 commandEntry->userActivityEventType = eventType;
Sean Stoutb4e0a592021-02-23 07:34:53 -08002597 commandEntry->displayId = displayId;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002598 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002599}
2600
2601void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002602 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002603 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002604 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002605 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002606 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002607 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002608 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002609 ATRACE_NAME(message.c_str());
2610 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002611#if DEBUG_DISPATCH_CYCLE
2612 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002613 "globalScaleFactor=%f, pointerIds=0x%x %s",
2614 connection->getInputChannelName().c_str(), inputTarget.flags,
2615 inputTarget.globalScaleFactor, inputTarget.pointerIds.value,
2616 inputTarget.getPointerInfoString().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002617#endif
2618
2619 // Skip this event if the connection status is not normal.
2620 // We don't want to enqueue additional outbound events if the connection is broken.
2621 if (connection->status != Connection::STATUS_NORMAL) {
2622#if DEBUG_DISPATCH_CYCLE
2623 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002624 connection->getInputChannelName().c_str(), connection->getStatusLabel());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002625#endif
2626 return;
2627 }
2628
2629 // Split a motion event if needed.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002630 if (inputTarget.flags & InputTarget::FLAG_SPLIT) {
2631 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
2632 "Entry type %s should not have FLAG_SPLIT",
Chris Yef59a2f42020-10-16 12:55:26 -07002633 NamedEnum::string(eventEntry->type).c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002634
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002635 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002636 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002637 std::unique_ptr<MotionEntry> splitMotionEntry =
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002638 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002639 if (!splitMotionEntry) {
2640 return; // split event was dropped
2641 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002642 if (DEBUG_FOCUS) {
2643 ALOGD("channel '%s' ~ Split motion event.",
2644 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002645 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002646 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002647 enqueueDispatchEntriesLocked(currentTime, connection, std::move(splitMotionEntry),
2648 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002649 return;
2650 }
2651 }
2652
2653 // Not splitting. Enqueue dispatch entries for the event as is.
2654 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
2655}
2656
2657void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002658 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002659 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002660 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002661 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002662 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002663 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002664 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002665 ATRACE_NAME(message.c_str());
2666 }
2667
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002668 bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002669
2670 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07002671 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002672 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002673 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002674 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07002675 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002676 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07002677 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002678 InputTarget::FLAG_DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07002679 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002680 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002681 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002682 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002683
2684 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002685 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002686 startDispatchCycleLocked(currentTime, connection);
2687 }
2688}
2689
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002690void InputDispatcher::enqueueDispatchEntryLocked(const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002691 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002692 const InputTarget& inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002693 int32_t dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002694 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002695 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
2696 connection->getInputChannelName().c_str(),
2697 dispatchModeToString(dispatchMode).c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002698 ATRACE_NAME(message.c_str());
2699 }
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002700 int32_t inputTargetFlags = inputTarget.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002701 if (!(inputTargetFlags & dispatchMode)) {
2702 return;
2703 }
2704 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
2705
2706 // This is a new event.
2707 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002708 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002709 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002710
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002711 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
2712 // different EventEntry than what was passed in.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002713 EventEntry& newEntry = *(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002714 // Apply target flags and update the connection's input state.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002715 switch (newEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002716 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002717 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002718 dispatchEntry->resolvedEventId = keyEntry.id;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002719 dispatchEntry->resolvedAction = keyEntry.action;
2720 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002721
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002722 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
2723 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002724#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002725 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key event",
2726 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002727#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002728 return; // skip the inconsistent event
2729 }
2730 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002731 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002732
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002733 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002734 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002735 // Assign a default value to dispatchEntry that will never be generated by InputReader,
2736 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
2737 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
2738 static_cast<int32_t>(IdGenerator::Source::OTHER);
2739 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002740 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2741 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
2742 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
2743 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
2744 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
2745 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2746 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
2747 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
2748 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
2749 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
2750 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002751 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002752 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002753 }
2754 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002755 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
2756 motionEntry.displayId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002757#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002758 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover enter "
2759 "event",
2760 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002761#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002762 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2763 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002764
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002765 dispatchEntry->resolvedFlags = motionEntry.flags;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002766 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
2767 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
2768 }
2769 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
2770 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2771 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002772
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002773 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
2774 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002775#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002776 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
2777 "event",
2778 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002779#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002780 return; // skip the inconsistent event
2781 }
2782
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002783 dispatchEntry->resolvedEventId =
2784 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
2785 ? mIdGenerator.nextId()
2786 : motionEntry.id;
2787 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
2788 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
2789 ") to MotionEvent(id=0x%" PRIx32 ").",
2790 motionEntry.id, dispatchEntry->resolvedEventId);
2791 ATRACE_NAME(message.c_str());
2792 }
2793
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002794 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002795 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002796
2797 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002798 }
Prabir Pradhan99987712020-11-10 18:43:05 -08002799 case EventEntry::Type::FOCUS:
2800 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002801 break;
2802 }
Chris Yef59a2f42020-10-16 12:55:26 -07002803 case EventEntry::Type::SENSOR: {
2804 LOG_ALWAYS_FATAL("SENSOR events should not go to apps via input channel");
2805 break;
2806 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002807 case EventEntry::Type::CONFIGURATION_CHANGED:
2808 case EventEntry::Type::DEVICE_RESET: {
2809 LOG_ALWAYS_FATAL("%s events should not go to apps",
Chris Yef59a2f42020-10-16 12:55:26 -07002810 NamedEnum::string(newEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002811 break;
2812 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002813 }
2814
2815 // Remember that we are waiting for this dispatch to complete.
2816 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002817 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002818 }
2819
2820 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002821 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002822 traceOutboundQueueLength(connection);
chaviw8c9cf542019-03-25 13:02:48 -07002823}
2824
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00002825/**
2826 * This function is purely for debugging. It helps us understand where the user interaction
2827 * was taking place. For example, if user is touching launcher, we will see a log that user
2828 * started interacting with launcher. In that example, the event would go to the wallpaper as well.
2829 * We will see both launcher and wallpaper in that list.
2830 * Once the interaction with a particular set of connections starts, no new logs will be printed
2831 * until the set of interacted connections changes.
2832 *
2833 * The following items are skipped, to reduce the logspam:
2834 * ACTION_OUTSIDE: any windows that are receiving ACTION_OUTSIDE are not logged
2835 * ACTION_UP: any windows that receive ACTION_UP are not logged (for both keys and motions).
2836 * This includes situations like the soft BACK button key. When the user releases (lifts up the
2837 * finger) the back button, then navigation bar will inject KEYCODE_BACK with ACTION_UP.
2838 * Both of those ACTION_UP events would not be logged
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00002839 */
2840void InputDispatcher::updateInteractionTokensLocked(const EventEntry& entry,
2841 const std::vector<InputTarget>& targets) {
2842 // Skip ACTION_UP events, and all events other than keys and motions
2843 if (entry.type == EventEntry::Type::KEY) {
2844 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
2845 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
2846 return;
2847 }
2848 } else if (entry.type == EventEntry::Type::MOTION) {
2849 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
2850 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
2851 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
2852 return;
2853 }
2854 } else {
2855 return; // Not a key or a motion
2856 }
2857
2858 std::unordered_set<sp<IBinder>, IBinderHash> newConnectionTokens;
2859 std::vector<sp<Connection>> newConnections;
2860 for (const InputTarget& target : targets) {
2861 if ((target.flags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) ==
2862 InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2863 continue; // Skip windows that receive ACTION_OUTSIDE
2864 }
2865
2866 sp<IBinder> token = target.inputChannel->getConnectionToken();
2867 sp<Connection> connection = getConnectionLocked(token);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00002868 if (connection == nullptr) {
2869 continue;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00002870 }
2871 newConnectionTokens.insert(std::move(token));
2872 newConnections.emplace_back(connection);
2873 }
2874 if (newConnectionTokens == mInteractionConnectionTokens) {
2875 return; // no change
2876 }
2877 mInteractionConnectionTokens = newConnectionTokens;
2878
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00002879 std::string targetList;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00002880 for (const sp<Connection>& connection : newConnections) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00002881 targetList += connection->getWindowName() + ", ";
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00002882 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00002883 std::string message = "Interaction with: " + targetList;
2884 if (targetList.empty()) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00002885 message += "<none>";
2886 }
2887 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
2888}
2889
chaviwfd6d3512019-03-25 13:23:49 -07002890void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07002891 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07002892 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07002893 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
2894 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07002895 return;
2896 }
2897
Vishnu Nairc519ff72021-01-21 08:23:08 -08002898 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07002899 if (focusedToken == token) {
2900 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07002901 return;
2902 }
2903
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002904 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
2905 &InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible);
Vishnu Nairad321cd2020-08-20 16:40:21 -07002906 commandEntry->newToken = token;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002907 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002908}
2909
2910void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002911 const sp<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002912 if (ATRACE_ENABLED()) {
2913 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002914 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002915 ATRACE_NAME(message.c_str());
2916 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002917#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002918 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002919#endif
2920
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002921 while (connection->status == Connection::STATUS_NORMAL && !connection->outboundQueue.empty()) {
2922 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002923 dispatchEntry->deliveryTime = currentTime;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05002924 const std::chrono::nanoseconds timeout =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002925 getDispatchingTimeoutLocked(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou70622952020-07-30 11:17:23 -05002926 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002927
2928 // Publish the event.
2929 status_t status;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002930 const EventEntry& eventEntry = *(dispatchEntry->eventEntry);
2931 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002932 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002933 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
2934 std::array<uint8_t, 32> hmac = getSignature(keyEntry, *dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002935
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002936 // Publish the key event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002937 status = connection->inputPublisher
2938 .publishKeyEvent(dispatchEntry->seq,
2939 dispatchEntry->resolvedEventId, keyEntry.deviceId,
2940 keyEntry.source, keyEntry.displayId,
2941 std::move(hmac), dispatchEntry->resolvedAction,
2942 dispatchEntry->resolvedFlags, keyEntry.keyCode,
2943 keyEntry.scanCode, keyEntry.metaState,
2944 keyEntry.repeatCount, keyEntry.downTime,
2945 keyEntry.eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002946 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002947 }
2948
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002949 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002950 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002951
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002952 PointerCoords scaledCoords[MAX_POINTERS];
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002953 const PointerCoords* usingCoords = motionEntry.pointerCoords;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002954
chaviw82357092020-01-28 13:13:06 -08002955 // Set the X and Y offset and X and Y scale depending on the input source.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002956 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) &&
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002957 !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
2958 float globalScaleFactor = dispatchEntry->globalScaleFactor;
chaviw82357092020-01-28 13:13:06 -08002959 if (globalScaleFactor != 1.0f) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002960 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
2961 scaledCoords[i] = motionEntry.pointerCoords[i];
chaviw82357092020-01-28 13:13:06 -08002962 // Don't apply window scale here since we don't want scale to affect raw
2963 // coordinates. The scale will be sent back to the client and applied
2964 // later when requesting relative coordinates.
2965 scaledCoords[i].scale(globalScaleFactor, 1 /* windowXScale */,
2966 1 /* windowYScale */);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002967 }
2968 usingCoords = scaledCoords;
2969 }
2970 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002971 // We don't want the dispatch target to know.
2972 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002973 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002974 scaledCoords[i].clear();
2975 }
2976 usingCoords = scaledCoords;
2977 }
2978 }
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07002979
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002980 std::array<uint8_t, 32> hmac = getSignature(motionEntry, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002981
2982 // Publish the motion event.
2983 status = connection->inputPublisher
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002984 .publishMotionEvent(dispatchEntry->seq,
2985 dispatchEntry->resolvedEventId,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002986 motionEntry.deviceId, motionEntry.source,
2987 motionEntry.displayId, std::move(hmac),
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002988 dispatchEntry->resolvedAction,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002989 motionEntry.actionButton,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002990 dispatchEntry->resolvedFlags,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002991 motionEntry.edgeFlags, motionEntry.metaState,
2992 motionEntry.buttonState,
2993 motionEntry.classification,
chaviw9eaa22c2020-07-01 16:21:27 -07002994 dispatchEntry->transform,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002995 motionEntry.xPrecision, motionEntry.yPrecision,
2996 motionEntry.xCursorPosition,
2997 motionEntry.yCursorPosition,
2998 motionEntry.downTime, motionEntry.eventTime,
2999 motionEntry.pointerCount,
3000 motionEntry.pointerProperties, usingCoords);
3001 reportTouchEventForStatistics(motionEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003002 break;
3003 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003004
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003005 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003006 const FocusEntry& focusEntry = static_cast<const FocusEntry&>(eventEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003007 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003008 focusEntry.id,
3009 focusEntry.hasFocus,
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003010 mInTouchMode);
3011 break;
3012 }
3013
Prabir Pradhan99987712020-11-10 18:43:05 -08003014 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3015 const auto& captureEntry =
3016 static_cast<const PointerCaptureChangedEntry&>(eventEntry);
3017 status = connection->inputPublisher
3018 .publishCaptureEvent(dispatchEntry->seq, captureEntry.id,
3019 captureEntry.pointerCaptureEnabled);
3020 break;
3021 }
3022
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003023 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003024 case EventEntry::Type::DEVICE_RESET:
3025 case EventEntry::Type::SENSOR: {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003026 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
Chris Yef59a2f42020-10-16 12:55:26 -07003027 NamedEnum::string(eventEntry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003028 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003029 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003030 }
3031
3032 // Check the result.
3033 if (status) {
3034 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003035 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003036 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003037 "This is unexpected because the wait queue is empty, so the pipe "
3038 "should be empty and we shouldn't have any problems writing an "
3039 "event to it, status=%d",
3040 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003041 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3042 } else {
3043 // Pipe is full and we are waiting for the app to finish process some events
3044 // before sending more events to it.
3045#if DEBUG_DISPATCH_CYCLE
3046 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003047 "waiting for the application to catch up",
3048 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003049#endif
Michael Wrightd02c5b62014-02-10 15:10:22 -08003050 }
3051 } else {
3052 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003053 "status=%d",
3054 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003055 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3056 }
3057 return;
3058 }
3059
3060 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003061 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
3062 connection->outboundQueue.end(),
3063 dispatchEntry));
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003064 traceOutboundQueueLength(connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003065 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003066 if (connection->responsive) {
3067 mAnrTracker.insert(dispatchEntry->timeoutTime,
3068 connection->inputChannel->getConnectionToken());
3069 }
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003070 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003071 }
3072}
3073
chaviw09c8d2d2020-08-24 15:48:26 -07003074std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
3075 size_t size;
3076 switch (event.type) {
3077 case VerifiedInputEvent::Type::KEY: {
3078 size = sizeof(VerifiedKeyEvent);
3079 break;
3080 }
3081 case VerifiedInputEvent::Type::MOTION: {
3082 size = sizeof(VerifiedMotionEvent);
3083 break;
3084 }
3085 }
3086 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
3087 return mHmacKeyManager.sign(start, size);
3088}
3089
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003090const std::array<uint8_t, 32> InputDispatcher::getSignature(
3091 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
3092 int32_t actionMasked = dispatchEntry.resolvedAction & AMOTION_EVENT_ACTION_MASK;
3093 if ((actionMasked == AMOTION_EVENT_ACTION_UP) || (actionMasked == AMOTION_EVENT_ACTION_DOWN)) {
3094 // Only sign events up and down events as the purely move events
3095 // are tied to their up/down counterparts so signing would be redundant.
3096 VerifiedMotionEvent verifiedEvent = verifiedMotionEventFromMotionEntry(motionEntry);
3097 verifiedEvent.actionMasked = actionMasked;
3098 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
chaviw09c8d2d2020-08-24 15:48:26 -07003099 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003100 }
3101 return INVALID_HMAC;
3102}
3103
3104const std::array<uint8_t, 32> InputDispatcher::getSignature(
3105 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
3106 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
3107 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
3108 verifiedEvent.action = dispatchEntry.resolvedAction;
chaviw09c8d2d2020-08-24 15:48:26 -07003109 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003110}
3111
Michael Wrightd02c5b62014-02-10 15:10:22 -08003112void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003113 const sp<Connection>& connection, uint32_t seq,
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10003114 bool handled, nsecs_t consumeTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003115#if DEBUG_DISPATCH_CYCLE
3116 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003117 connection->getInputChannelName().c_str(), seq, toString(handled));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003118#endif
3119
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003120 if (connection->status == Connection::STATUS_BROKEN ||
3121 connection->status == Connection::STATUS_ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003122 return;
3123 }
3124
3125 // Notify other system components and prepare to start the next dispatch cycle.
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10003126 onDispatchCycleFinishedLocked(currentTime, connection, seq, handled, consumeTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003127}
3128
3129void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003130 const sp<Connection>& connection,
3131 bool notify) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003132#if DEBUG_DISPATCH_CYCLE
3133 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003134 connection->getInputChannelName().c_str(), toString(notify));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003135#endif
3136
3137 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003138 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003139 traceOutboundQueueLength(connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003140 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003141 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003142
3143 // The connection appears to be unrecoverably broken.
3144 // Ignore already broken or zombie connections.
3145 if (connection->status == Connection::STATUS_NORMAL) {
3146 connection->status = Connection::STATUS_BROKEN;
3147
3148 if (notify) {
3149 // Notify other system components.
3150 onDispatchCycleBrokenLocked(currentTime, connection);
3151 }
3152 }
3153}
3154
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003155void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
3156 while (!queue.empty()) {
3157 DispatchEntry* dispatchEntry = queue.front();
3158 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003159 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003160 }
3161}
3162
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003163void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003164 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003165 decrementPendingForegroundDispatches(*(dispatchEntry->eventEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003166 }
3167 delete dispatchEntry;
3168}
3169
3170int InputDispatcher::handleReceiveCallback(int fd, int events, void* data) {
3171 InputDispatcher* d = static_cast<InputDispatcher*>(data);
3172
3173 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003174 std::scoped_lock _l(d->mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003175
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003176 if (d->mConnectionsByFd.find(fd) == d->mConnectionsByFd.end()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003177 ALOGE("Received spurious receive callback for unknown input channel. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003178 "fd=%d, events=0x%x",
3179 fd, events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003180 return 0; // remove the callback
3181 }
3182
3183 bool notify;
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003184 sp<Connection> connection = d->mConnectionsByFd[fd];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003185 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
3186 if (!(events & ALOOPER_EVENT_INPUT)) {
3187 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003188 "events=0x%x",
3189 connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003190 return 1;
3191 }
3192
3193 nsecs_t currentTime = now();
3194 bool gotOne = false;
3195 status_t status;
3196 for (;;) {
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10003197 std::function<void(uint32_t seq, bool handled, nsecs_t consumeTime)> callback =
3198 std::bind(&InputDispatcher::finishDispatchCycleLocked, d, currentTime,
3199 connection, std::placeholders::_1, std::placeholders::_2,
3200 std::placeholders::_3);
3201
3202 status = connection->inputPublisher.receiveFinishedSignal(callback);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003203 if (status) {
3204 break;
3205 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003206 gotOne = true;
3207 }
3208 if (gotOne) {
3209 d->runCommandsLockedInterruptible();
3210 if (status == WOULD_BLOCK) {
3211 return 1;
3212 }
3213 }
3214
3215 notify = status != DEAD_OBJECT || !connection->monitor;
3216 if (notify) {
3217 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003218 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003219 }
3220 } else {
3221 // Monitor channels are never explicitly unregistered.
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003222 // We do it automatically when the remote endpoint is closed so don't warn about them.
arthurhungd352cb32020-04-28 17:09:28 +08003223 const bool stillHaveWindowHandle =
3224 d->getWindowHandleLocked(connection->inputChannel->getConnectionToken()) !=
3225 nullptr;
3226 notify = !connection->monitor && stillHaveWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003227 if (notify) {
3228 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003229 "events=0x%x",
3230 connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003231 }
3232 }
3233
Garfield Tan15601662020-09-22 15:32:38 -07003234 // Remove the channel.
3235 d->removeInputChannelLocked(connection->inputChannel->getConnectionToken(), notify);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003236 return 0; // remove the callback
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003237 } // release lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08003238}
3239
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003240void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08003241 const CancelationOptions& options) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +00003242 for (const auto& [fd, connection] : mConnectionsByFd) {
3243 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003244 }
3245}
3246
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003247void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003248 const CancelationOptions& options) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003249 synthesizeCancelationEventsForMonitorsLocked(options, mGlobalMonitorsByDisplay);
3250 synthesizeCancelationEventsForMonitorsLocked(options, mGestureMonitorsByDisplay);
3251}
3252
3253void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
3254 const CancelationOptions& options,
3255 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
3256 for (const auto& it : monitorsByDisplay) {
3257 const std::vector<Monitor>& monitors = it.second;
3258 for (const Monitor& monitor : monitors) {
3259 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003260 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003261 }
3262}
3263
Michael Wrightd02c5b62014-02-10 15:10:22 -08003264void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003265 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07003266 sp<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003267 if (connection == nullptr) {
3268 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003269 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003270
3271 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003272}
3273
3274void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
3275 const sp<Connection>& connection, const CancelationOptions& options) {
3276 if (connection->status == Connection::STATUS_BROKEN) {
3277 return;
3278 }
3279
3280 nsecs_t currentTime = now();
3281
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003282 std::vector<std::unique_ptr<EventEntry>> cancelationEvents =
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07003283 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003284
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003285 if (cancelationEvents.empty()) {
3286 return;
3287 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003288#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003289 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
3290 "with reality: %s, mode=%d.",
3291 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
3292 options.mode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003293#endif
Svet Ganov5d3bc372020-01-26 23:11:07 -08003294
3295 InputTarget target;
3296 sp<InputWindowHandle> windowHandle =
3297 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3298 if (windowHandle != nullptr) {
3299 const InputWindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003300 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003301 target.globalScaleFactor = windowInfo->globalScaleFactor;
3302 }
3303 target.inputChannel = connection->inputChannel;
3304 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3305
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003306 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003307 std::unique_ptr<EventEntry> cancelationEventEntry = std::move(cancelationEvents[i]);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003308 switch (cancelationEventEntry->type) {
3309 case EventEntry::Type::KEY: {
3310 logOutboundKeyDetails("cancel - ",
3311 static_cast<const KeyEntry&>(*cancelationEventEntry));
3312 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003313 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003314 case EventEntry::Type::MOTION: {
3315 logOutboundMotionDetails("cancel - ",
3316 static_cast<const MotionEntry&>(*cancelationEventEntry));
3317 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003318 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003319 case EventEntry::Type::FOCUS:
3320 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3321 LOG_ALWAYS_FATAL("Canceling %s events is not supported",
Chris Yef59a2f42020-10-16 12:55:26 -07003322 NamedEnum::string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003323 break;
3324 }
3325 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003326 case EventEntry::Type::DEVICE_RESET:
3327 case EventEntry::Type::SENSOR: {
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003328 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Chris Yef59a2f42020-10-16 12:55:26 -07003329 NamedEnum::string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003330 break;
3331 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003332 }
3333
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003334 enqueueDispatchEntryLocked(connection, std::move(cancelationEventEntry), target,
3335 InputTarget::FLAG_DISPATCH_AS_IS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003336 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003337
3338 startDispatchCycleLocked(currentTime, connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003339}
3340
Svet Ganov5d3bc372020-01-26 23:11:07 -08003341void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
3342 const sp<Connection>& connection) {
3343 if (connection->status == Connection::STATUS_BROKEN) {
3344 return;
3345 }
3346
3347 nsecs_t currentTime = now();
3348
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003349 std::vector<std::unique_ptr<EventEntry>> downEvents =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003350 connection->inputState.synthesizePointerDownEvents(currentTime);
3351
3352 if (downEvents.empty()) {
3353 return;
3354 }
3355
3356#if DEBUG_OUTBOUND_EVENT_DETAILS
3357 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
3358 connection->getInputChannelName().c_str(), downEvents.size());
3359#endif
3360
3361 InputTarget target;
3362 sp<InputWindowHandle> windowHandle =
3363 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3364 if (windowHandle != nullptr) {
3365 const InputWindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003366 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003367 target.globalScaleFactor = windowInfo->globalScaleFactor;
3368 }
3369 target.inputChannel = connection->inputChannel;
3370 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3371
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003372 for (std::unique_ptr<EventEntry>& downEventEntry : downEvents) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003373 switch (downEventEntry->type) {
3374 case EventEntry::Type::MOTION: {
3375 logOutboundMotionDetails("down - ",
3376 static_cast<const MotionEntry&>(*downEventEntry));
3377 break;
3378 }
3379
3380 case EventEntry::Type::KEY:
3381 case EventEntry::Type::FOCUS:
3382 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08003383 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07003384 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3385 case EventEntry::Type::SENSOR: {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003386 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Chris Yef59a2f42020-10-16 12:55:26 -07003387 NamedEnum::string(downEventEntry->type).c_str());
Svet Ganov5d3bc372020-01-26 23:11:07 -08003388 break;
3389 }
3390 }
3391
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003392 enqueueDispatchEntryLocked(connection, std::move(downEventEntry), target,
3393 InputTarget::FLAG_DISPATCH_AS_IS);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003394 }
3395
3396 startDispatchCycleLocked(currentTime, connection);
3397}
3398
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003399std::unique_ptr<MotionEntry> InputDispatcher::splitMotionEvent(
3400 const MotionEntry& originalMotionEntry, BitSet32 pointerIds) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003401 ALOG_ASSERT(pointerIds.value != 0);
3402
3403 uint32_t splitPointerIndexMap[MAX_POINTERS];
3404 PointerProperties splitPointerProperties[MAX_POINTERS];
3405 PointerCoords splitPointerCoords[MAX_POINTERS];
3406
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003407 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003408 uint32_t splitPointerCount = 0;
3409
3410 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003411 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003412 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003413 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003414 uint32_t pointerId = uint32_t(pointerProperties.id);
3415 if (pointerIds.hasBit(pointerId)) {
3416 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
3417 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
3418 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003419 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003420 splitPointerCount += 1;
3421 }
3422 }
3423
3424 if (splitPointerCount != pointerIds.count()) {
3425 // This is bad. We are missing some of the pointers that we expected to deliver.
3426 // Most likely this indicates that we received an ACTION_MOVE events that has
3427 // different pointer ids than we expected based on the previous ACTION_DOWN
3428 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
3429 // in this way.
3430 ALOGW("Dropping split motion event because the pointer count is %d but "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003431 "we expected there to be %d pointers. This probably means we received "
3432 "a broken sequence of pointer ids from the input device.",
3433 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07003434 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003435 }
3436
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003437 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003438 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003439 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
3440 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003441 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
3442 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003443 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003444 uint32_t pointerId = uint32_t(pointerProperties.id);
3445 if (pointerIds.hasBit(pointerId)) {
3446 if (pointerIds.count() == 1) {
3447 // The first/last pointer went down/up.
3448 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003449 ? AMOTION_EVENT_ACTION_DOWN
arthurhungea3f4fc2020-12-21 23:18:53 +08003450 : (originalMotionEntry.flags & AMOTION_EVENT_FLAG_CANCELED) != 0
3451 ? AMOTION_EVENT_ACTION_CANCEL
3452 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003453 } else {
3454 // A secondary pointer went down/up.
3455 uint32_t splitPointerIndex = 0;
3456 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
3457 splitPointerIndex += 1;
3458 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003459 action = maskedAction |
3460 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003461 }
3462 } else {
3463 // An unrelated pointer changed.
3464 action = AMOTION_EVENT_ACTION_MOVE;
3465 }
3466 }
3467
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003468 int32_t newId = mIdGenerator.nextId();
3469 if (ATRACE_ENABLED()) {
3470 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
3471 ") to MotionEvent(id=0x%" PRIx32 ").",
3472 originalMotionEntry.id, newId);
3473 ATRACE_NAME(message.c_str());
3474 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003475 std::unique_ptr<MotionEntry> splitMotionEntry =
3476 std::make_unique<MotionEntry>(newId, originalMotionEntry.eventTime,
3477 originalMotionEntry.deviceId, originalMotionEntry.source,
3478 originalMotionEntry.displayId,
3479 originalMotionEntry.policyFlags, action,
3480 originalMotionEntry.actionButton,
3481 originalMotionEntry.flags, originalMotionEntry.metaState,
3482 originalMotionEntry.buttonState,
3483 originalMotionEntry.classification,
3484 originalMotionEntry.edgeFlags,
3485 originalMotionEntry.xPrecision,
3486 originalMotionEntry.yPrecision,
3487 originalMotionEntry.xCursorPosition,
3488 originalMotionEntry.yCursorPosition,
3489 originalMotionEntry.downTime, splitPointerCount,
3490 splitPointerProperties, splitPointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003491
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003492 if (originalMotionEntry.injectionState) {
3493 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003494 splitMotionEntry->injectionState->refCount += 1;
3495 }
3496
3497 return splitMotionEntry;
3498}
3499
3500void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
3501#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003502 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003503#endif
3504
3505 bool needWake;
3506 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003507 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003508
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003509 std::unique_ptr<ConfigurationChangedEntry> newEntry =
3510 std::make_unique<ConfigurationChangedEntry>(args->id, args->eventTime);
3511 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003512 } // release lock
3513
3514 if (needWake) {
3515 mLooper->wake();
3516 }
3517}
3518
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003519/**
3520 * If one of the meta shortcuts is detected, process them here:
3521 * Meta + Backspace -> generate BACK
3522 * Meta + Enter -> generate HOME
3523 * This will potentially overwrite keyCode and metaState.
3524 */
3525void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003526 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003527 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
3528 int32_t newKeyCode = AKEYCODE_UNKNOWN;
3529 if (keyCode == AKEYCODE_DEL) {
3530 newKeyCode = AKEYCODE_BACK;
3531 } else if (keyCode == AKEYCODE_ENTER) {
3532 newKeyCode = AKEYCODE_HOME;
3533 }
3534 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003535 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003536 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003537 mReplacedKeys[replacement] = newKeyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003538 keyCode = newKeyCode;
3539 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3540 }
3541 } else if (action == AKEY_EVENT_ACTION_UP) {
3542 // In order to maintain a consistent stream of up and down events, check to see if the key
3543 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
3544 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003545 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003546 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003547 auto replacementIt = mReplacedKeys.find(replacement);
3548 if (replacementIt != mReplacedKeys.end()) {
3549 keyCode = replacementIt->second;
3550 mReplacedKeys.erase(replacementIt);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003551 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3552 }
3553 }
3554}
3555
Michael Wrightd02c5b62014-02-10 15:10:22 -08003556void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
3557#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003558 ALOGD("notifyKey - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
3559 "policyFlags=0x%x, action=0x%x, "
3560 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
3561 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
3562 args->action, args->flags, args->keyCode, args->scanCode, args->metaState,
3563 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003564#endif
3565 if (!validateKeyEvent(args->action)) {
3566 return;
3567 }
3568
3569 uint32_t policyFlags = args->policyFlags;
3570 int32_t flags = args->flags;
3571 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07003572 // InputDispatcher tracks and generates key repeats on behalf of
3573 // whatever notifies it, so repeatCount should always be set to 0
3574 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003575 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
3576 policyFlags |= POLICY_FLAG_VIRTUAL;
3577 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
3578 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003579 if (policyFlags & POLICY_FLAG_FUNCTION) {
3580 metaState |= AMETA_FUNCTION_ON;
3581 }
3582
3583 policyFlags |= POLICY_FLAG_TRUSTED;
3584
Michael Wright78f24442014-08-06 15:55:28 -07003585 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003586 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07003587
Michael Wrightd02c5b62014-02-10 15:10:22 -08003588 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003589 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08003590 args->action, flags, keyCode, args->scanCode, metaState, repeatCount,
3591 args->downTime, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003592
Michael Wright2b3c3302018-03-02 17:19:13 +00003593 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003594 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003595 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3596 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003597 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003598 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003599
Michael Wrightd02c5b62014-02-10 15:10:22 -08003600 bool needWake;
3601 { // acquire lock
3602 mLock.lock();
3603
3604 if (shouldSendKeyToInputFilterLocked(args)) {
3605 mLock.unlock();
3606
3607 policyFlags |= POLICY_FLAG_FILTERED;
3608 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3609 return; // event was consumed by the filter
3610 }
3611
3612 mLock.lock();
3613 }
3614
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003615 std::unique_ptr<KeyEntry> newEntry =
3616 std::make_unique<KeyEntry>(args->id, args->eventTime, args->deviceId, args->source,
3617 args->displayId, policyFlags, args->action, flags,
3618 keyCode, args->scanCode, metaState, repeatCount,
3619 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003620
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003621 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003622 mLock.unlock();
3623 } // release lock
3624
3625 if (needWake) {
3626 mLooper->wake();
3627 }
3628}
3629
3630bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
3631 return mInputFilterEnabled;
3632}
3633
3634void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
3635#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003636 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
3637 "displayId=%" PRId32 ", policyFlags=0x%x, "
Garfield Tan00f511d2019-06-12 16:55:40 -07003638 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
3639 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
Garfield Tanab0ab9c2019-07-10 18:58:28 -07003640 "yCursorPosition=%f, downTime=%" PRId64,
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003641 args->id, args->eventTime, args->deviceId, args->source, args->displayId,
3642 args->policyFlags, args->action, args->actionButton, args->flags, args->metaState,
3643 args->buttonState, args->edgeFlags, args->xPrecision, args->yPrecision,
3644 args->xCursorPosition, args->yCursorPosition, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003645 for (uint32_t i = 0; i < args->pointerCount; i++) {
3646 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003647 "x=%f, y=%f, pressure=%f, size=%f, "
3648 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
3649 "orientation=%f",
3650 i, args->pointerProperties[i].id, args->pointerProperties[i].toolType,
3651 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
3652 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
3653 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
3654 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
3655 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
3656 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
3657 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
3658 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
3659 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003660 }
3661#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003662 if (!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
3663 args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003664 return;
3665 }
3666
3667 uint32_t policyFlags = args->policyFlags;
3668 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003669
3670 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08003671 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003672 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3673 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003674 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003675 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003676
3677 bool needWake;
3678 { // acquire lock
3679 mLock.lock();
3680
3681 if (shouldSendMotionToInputFilterLocked(args)) {
3682 mLock.unlock();
3683
3684 MotionEvent event;
chaviw9eaa22c2020-07-01 16:21:27 -07003685 ui::Transform transform;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003686 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
3687 args->action, args->actionButton, args->flags, args->edgeFlags,
chaviw9eaa22c2020-07-01 16:21:27 -07003688 args->metaState, args->buttonState, args->classification, transform,
3689 args->xPrecision, args->yPrecision, args->xCursorPosition,
3690 args->yCursorPosition, args->downTime, args->eventTime,
3691 args->pointerCount, args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003692
3693 policyFlags |= POLICY_FLAG_FILTERED;
3694 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3695 return; // event was consumed by the filter
3696 }
3697
3698 mLock.lock();
3699 }
3700
3701 // Just enqueue a new motion event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003702 std::unique_ptr<MotionEntry> newEntry =
3703 std::make_unique<MotionEntry>(args->id, args->eventTime, args->deviceId,
3704 args->source, args->displayId, policyFlags,
3705 args->action, args->actionButton, args->flags,
3706 args->metaState, args->buttonState,
3707 args->classification, args->edgeFlags,
3708 args->xPrecision, args->yPrecision,
3709 args->xCursorPosition, args->yCursorPosition,
3710 args->downTime, args->pointerCount,
3711 args->pointerProperties, args->pointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003712
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003713 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003714 mLock.unlock();
3715 } // release lock
3716
3717 if (needWake) {
3718 mLooper->wake();
3719 }
3720}
3721
Chris Yef59a2f42020-10-16 12:55:26 -07003722void InputDispatcher::notifySensor(const NotifySensorArgs* args) {
3723#if DEBUG_INBOUND_EVENT_DETAILS
3724 ALOGD("notifySensor - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
3725 " sensorType=%s",
3726 args->id, args->eventTime, args->deviceId, args->source,
3727 NamedEnum::string(args->sensorType).c_str());
3728#endif
3729
3730 bool needWake;
3731 { // acquire lock
3732 mLock.lock();
3733
3734 // Just enqueue a new sensor event.
3735 std::unique_ptr<SensorEntry> newEntry =
3736 std::make_unique<SensorEntry>(args->id, args->eventTime, args->deviceId,
3737 args->source, 0 /* policyFlags*/, args->hwTimestamp,
3738 args->sensorType, args->accuracy,
3739 args->accuracyChanged, args->values);
3740
3741 needWake = enqueueInboundEventLocked(std::move(newEntry));
3742 mLock.unlock();
3743 } // release lock
3744
3745 if (needWake) {
3746 mLooper->wake();
3747 }
3748}
3749
Chris Yefb552902021-02-03 17:18:37 -08003750void InputDispatcher::notifyVibratorState(const NotifyVibratorStateArgs* args) {
3751#if DEBUG_INBOUND_EVENT_DETAILS
3752 ALOGD("notifyVibratorState - eventTime=%" PRId64 ", device=%d, isOn=%d", args->eventTime,
3753 args->deviceId, args->isOn);
3754#endif
3755 mPolicy->notifyVibratorState(args->deviceId, args->isOn);
3756}
3757
Michael Wrightd02c5b62014-02-10 15:10:22 -08003758bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08003759 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003760}
3761
3762void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
3763#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003764 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003765 "switchMask=0x%08x",
3766 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003767#endif
3768
3769 uint32_t policyFlags = args->policyFlags;
3770 policyFlags |= POLICY_FLAG_TRUSTED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003771 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003772}
3773
3774void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
3775#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003776 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
3777 args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003778#endif
3779
3780 bool needWake;
3781 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003782 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003783
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003784 std::unique_ptr<DeviceResetEntry> newEntry =
3785 std::make_unique<DeviceResetEntry>(args->id, args->eventTime, args->deviceId);
3786 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003787 } // release lock
3788
3789 if (needWake) {
3790 mLooper->wake();
3791 }
3792}
3793
Prabir Pradhan7e186182020-11-10 13:56:45 -08003794void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs* args) {
3795#if DEBUG_INBOUND_EVENT_DETAILS
3796 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args->eventTime,
3797 args->enabled ? "true" : "false");
3798#endif
3799
Prabir Pradhan99987712020-11-10 18:43:05 -08003800 bool needWake;
3801 { // acquire lock
3802 std::scoped_lock _l(mLock);
3803 auto entry = std::make_unique<PointerCaptureChangedEntry>(args->id, args->eventTime,
3804 args->enabled);
3805 needWake = enqueueInboundEventLocked(std::move(entry));
3806 } // release lock
3807
3808 if (needWake) {
3809 mLooper->wake();
3810 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08003811}
3812
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003813InputEventInjectionResult InputDispatcher::injectInputEvent(
3814 const InputEvent* event, int32_t injectorPid, int32_t injectorUid,
3815 InputEventInjectionSync syncMode, std::chrono::milliseconds timeout, uint32_t policyFlags) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003816#if DEBUG_INBOUND_EVENT_DETAILS
3817 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003818 "syncMode=%d, timeout=%lld, policyFlags=0x%08x",
3819 event->getType(), injectorPid, injectorUid, syncMode, timeout.count(), policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003820#endif
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003821 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003822
3823 policyFlags |= POLICY_FLAG_INJECTED;
3824 if (hasInjectionPermission(injectorPid, injectorUid)) {
3825 policyFlags |= POLICY_FLAG_TRUSTED;
3826 }
3827
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003828 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003829 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003830 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003831 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
3832 int32_t action = incomingKey.getAction();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003833 if (!validateKeyEvent(action)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003834 return InputEventInjectionResult::FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003835 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003836
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003837 int32_t flags = incomingKey.getFlags();
3838 int32_t keyCode = incomingKey.getKeyCode();
3839 int32_t metaState = incomingKey.getMetaState();
3840 accelerateMetaShortcuts(VIRTUAL_KEYBOARD_ID, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003841 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003842 KeyEvent keyEvent;
Garfield Tan4cc839f2020-01-24 11:26:14 -08003843 keyEvent.initialize(incomingKey.getId(), VIRTUAL_KEYBOARD_ID, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003844 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
3845 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
3846 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003847
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003848 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
3849 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00003850 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003851
3852 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
3853 android::base::Timer t;
3854 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
3855 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3856 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
3857 std::to_string(t.duration().count()).c_str());
3858 }
3859 }
3860
3861 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003862 std::unique_ptr<KeyEntry> injectedEntry =
3863 std::make_unique<KeyEntry>(incomingKey.getId(), incomingKey.getEventTime(),
3864 VIRTUAL_KEYBOARD_ID, incomingKey.getSource(),
3865 incomingKey.getDisplayId(), policyFlags, action,
3866 flags, keyCode, incomingKey.getScanCode(), metaState,
3867 incomingKey.getRepeatCount(),
3868 incomingKey.getDownTime());
3869 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003870 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003871 }
3872
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003873 case AINPUT_EVENT_TYPE_MOTION: {
3874 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
3875 int32_t action = motionEvent->getAction();
3876 size_t pointerCount = motionEvent->getPointerCount();
3877 const PointerProperties* pointerProperties = motionEvent->getPointerProperties();
3878 int32_t actionButton = motionEvent->getActionButton();
3879 int32_t displayId = motionEvent->getDisplayId();
3880 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003881 return InputEventInjectionResult::FAILED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003882 }
3883
3884 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
3885 nsecs_t eventTime = motionEvent->getEventTime();
3886 android::base::Timer t;
3887 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
3888 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3889 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
3890 std::to_string(t.duration().count()).c_str());
3891 }
3892 }
3893
3894 mLock.lock();
3895 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
3896 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003897 std::unique_ptr<MotionEntry> injectedEntry =
3898 std::make_unique<MotionEntry>(motionEvent->getId(), *sampleEventTimes,
3899 VIRTUAL_KEYBOARD_ID, motionEvent->getSource(),
3900 motionEvent->getDisplayId(), policyFlags, action,
3901 actionButton, motionEvent->getFlags(),
3902 motionEvent->getMetaState(),
3903 motionEvent->getButtonState(),
3904 motionEvent->getClassification(),
3905 motionEvent->getEdgeFlags(),
3906 motionEvent->getXPrecision(),
3907 motionEvent->getYPrecision(),
3908 motionEvent->getRawXCursorPosition(),
3909 motionEvent->getRawYCursorPosition(),
3910 motionEvent->getDownTime(),
3911 uint32_t(pointerCount), pointerProperties,
3912 samplePointerCoords, motionEvent->getXOffset(),
3913 motionEvent->getYOffset());
3914 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003915 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
3916 sampleEventTimes += 1;
3917 samplePointerCoords += pointerCount;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003918 std::unique_ptr<MotionEntry> nextInjectedEntry =
3919 std::make_unique<MotionEntry>(motionEvent->getId(), *sampleEventTimes,
3920 VIRTUAL_KEYBOARD_ID, motionEvent->getSource(),
3921 motionEvent->getDisplayId(), policyFlags,
3922 action, actionButton, motionEvent->getFlags(),
3923 motionEvent->getMetaState(),
3924 motionEvent->getButtonState(),
3925 motionEvent->getClassification(),
3926 motionEvent->getEdgeFlags(),
3927 motionEvent->getXPrecision(),
3928 motionEvent->getYPrecision(),
3929 motionEvent->getRawXCursorPosition(),
3930 motionEvent->getRawYCursorPosition(),
3931 motionEvent->getDownTime(),
3932 uint32_t(pointerCount), pointerProperties,
3933 samplePointerCoords,
3934 motionEvent->getXOffset(),
3935 motionEvent->getYOffset());
3936 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003937 }
3938 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003939 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003940
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003941 default:
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08003942 ALOGW("Cannot inject %s events", inputEventTypeToString(event->getType()));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003943 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003944 }
3945
3946 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003947 if (syncMode == InputEventInjectionSync::NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003948 injectionState->injectionIsAsync = true;
3949 }
3950
3951 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003952 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003953
3954 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003955 while (!injectedEntries.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003956 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003957 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003958 }
3959
3960 mLock.unlock();
3961
3962 if (needWake) {
3963 mLooper->wake();
3964 }
3965
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003966 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003967 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003968 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003969
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003970 if (syncMode == InputEventInjectionSync::NONE) {
3971 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003972 } else {
3973 for (;;) {
3974 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003975 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003976 break;
3977 }
3978
3979 nsecs_t remainingTimeout = endTime - now();
3980 if (remainingTimeout <= 0) {
3981#if DEBUG_INJECTION
3982 ALOGD("injectInputEvent - Timed out waiting for injection result "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003983 "to become available.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003984#endif
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003985 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003986 break;
3987 }
3988
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003989 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003990 }
3991
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003992 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
3993 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003994 while (injectionState->pendingForegroundDispatches != 0) {
3995#if DEBUG_INJECTION
3996 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003997 injectionState->pendingForegroundDispatches);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003998#endif
3999 nsecs_t remainingTimeout = endTime - now();
4000 if (remainingTimeout <= 0) {
4001#if DEBUG_INJECTION
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004002 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
4003 "dispatches to finish.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004004#endif
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004005 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004006 break;
4007 }
4008
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004009 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004010 }
4011 }
4012 }
4013
4014 injectionState->release();
4015 } // release lock
4016
4017#if DEBUG_INJECTION
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004018 ALOGD("injectInputEvent - Finished with result %d. injectorPid=%d, injectorUid=%d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004019 injectionResult, injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004020#endif
4021
4022 return injectionResult;
4023}
4024
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004025std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05004026 std::array<uint8_t, 32> calculatedHmac;
4027 std::unique_ptr<VerifiedInputEvent> result;
4028 switch (event.getType()) {
4029 case AINPUT_EVENT_TYPE_KEY: {
4030 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
4031 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
4032 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004033 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05004034 break;
4035 }
4036 case AINPUT_EVENT_TYPE_MOTION: {
4037 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
4038 VerifiedMotionEvent verifiedMotionEvent =
4039 verifiedMotionEventFromMotionEvent(motionEvent);
4040 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004041 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05004042 break;
4043 }
4044 default: {
4045 ALOGE("Cannot verify events of type %" PRId32, event.getType());
4046 return nullptr;
4047 }
4048 }
4049 if (calculatedHmac == INVALID_HMAC) {
4050 return nullptr;
4051 }
4052 if (calculatedHmac != event.getHmac()) {
4053 return nullptr;
4054 }
4055 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004056}
4057
Michael Wrightd02c5b62014-02-10 15:10:22 -08004058bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004059 return injectorUid == 0 ||
4060 mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004061}
4062
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004063void InputDispatcher::setInjectionResult(EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004064 InputEventInjectionResult injectionResult) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004065 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004066 if (injectionState) {
4067#if DEBUG_INJECTION
4068 ALOGD("Setting input event injection result to %d. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004069 "injectorPid=%d, injectorUid=%d",
4070 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004071#endif
4072
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004073 if (injectionState->injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004074 // Log the outcome since the injector did not wait for the injection result.
4075 switch (injectionResult) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004076 case InputEventInjectionResult::SUCCEEDED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004077 ALOGV("Asynchronous input event injection succeeded.");
4078 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004079 case InputEventInjectionResult::FAILED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004080 ALOGW("Asynchronous input event injection failed.");
4081 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004082 case InputEventInjectionResult::PERMISSION_DENIED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004083 ALOGW("Asynchronous input event injection permission denied.");
4084 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004085 case InputEventInjectionResult::TIMED_OUT:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004086 ALOGW("Asynchronous input event injection timed out.");
4087 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004088 case InputEventInjectionResult::PENDING:
4089 ALOGE("Setting result to 'PENDING' for asynchronous injection");
4090 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004091 }
4092 }
4093
4094 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004095 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004096 }
4097}
4098
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004099void InputDispatcher::incrementPendingForegroundDispatches(EventEntry& entry) {
4100 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004101 if (injectionState) {
4102 injectionState->pendingForegroundDispatches += 1;
4103 }
4104}
4105
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004106void InputDispatcher::decrementPendingForegroundDispatches(EventEntry& entry) {
4107 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004108 if (injectionState) {
4109 injectionState->pendingForegroundDispatches -= 1;
4110
4111 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004112 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004113 }
4114 }
4115}
4116
Vishnu Nairad321cd2020-08-20 16:40:21 -07004117const std::vector<sp<InputWindowHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004118 int32_t displayId) const {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004119 static const std::vector<sp<InputWindowHandle>> EMPTY_WINDOW_HANDLES;
4120 auto it = mWindowHandlesByDisplay.find(displayId);
4121 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08004122}
4123
Michael Wrightd02c5b62014-02-10 15:10:22 -08004124sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08004125 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08004126 if (windowHandleToken == nullptr) {
4127 return nullptr;
4128 }
4129
Arthur Hungb92218b2018-08-14 12:00:21 +08004130 for (auto& it : mWindowHandlesByDisplay) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004131 const std::vector<sp<InputWindowHandle>>& windowHandles = it.second;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004132 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004133 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004134 return windowHandle;
4135 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004136 }
4137 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004138 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004139}
4140
Vishnu Nairad321cd2020-08-20 16:40:21 -07004141sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(const sp<IBinder>& windowHandleToken,
4142 int displayId) const {
4143 if (windowHandleToken == nullptr) {
4144 return nullptr;
4145 }
4146
4147 for (const sp<InputWindowHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
4148 if (windowHandle->getToken() == windowHandleToken) {
4149 return windowHandle;
4150 }
4151 }
4152 return nullptr;
4153}
4154
4155sp<InputWindowHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
Vishnu Nairc519ff72021-01-21 08:23:08 -08004156 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(displayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07004157 return getWindowHandleLocked(focusedToken, displayId);
4158}
4159
Mady Mellor017bcd12020-06-23 19:12:00 +00004160bool InputDispatcher::hasWindowHandleLocked(const sp<InputWindowHandle>& windowHandle) const {
4161 for (auto& it : mWindowHandlesByDisplay) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004162 const std::vector<sp<InputWindowHandle>>& windowHandles = it.second;
Mady Mellor017bcd12020-06-23 19:12:00 +00004163 for (const sp<InputWindowHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08004164 if (handle->getId() == windowHandle->getId() &&
4165 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004166 if (windowHandle->getInfo()->displayId != it.first) {
4167 ALOGE("Found window %s in display %" PRId32
4168 ", but it should belong to display %" PRId32,
4169 windowHandle->getName().c_str(), it.first,
4170 windowHandle->getInfo()->displayId);
4171 }
4172 return true;
Arthur Hungb92218b2018-08-14 12:00:21 +08004173 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004174 }
4175 }
4176 return false;
4177}
4178
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004179bool InputDispatcher::hasResponsiveConnectionLocked(InputWindowHandle& windowHandle) const {
4180 sp<Connection> connection = getConnectionLocked(windowHandle.getToken());
4181 const bool noInputChannel =
4182 windowHandle.getInfo()->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
4183 if (connection != nullptr && noInputChannel) {
4184 ALOGW("%s has feature NO_INPUT_CHANNEL, but it matched to connection %s",
4185 windowHandle.getName().c_str(), connection->inputChannel->getName().c_str());
4186 return false;
4187 }
4188
4189 if (connection == nullptr) {
4190 if (!noInputChannel) {
4191 ALOGI("Could not find connection for %s", windowHandle.getName().c_str());
4192 }
4193 return false;
4194 }
4195 if (!connection->responsive) {
4196 ALOGW("Window %s is not responsive", windowHandle.getName().c_str());
4197 return false;
4198 }
4199 return true;
4200}
4201
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004202std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
4203 const sp<IBinder>& token) const {
Robert Carr5c8a0262018-10-03 16:30:44 -07004204 size_t count = mInputChannelsByToken.count(token);
4205 if (count == 0) {
4206 return nullptr;
4207 }
4208 return mInputChannelsByToken.at(token);
4209}
4210
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004211void InputDispatcher::updateWindowHandlesForDisplayLocked(
4212 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
4213 if (inputWindowHandles.empty()) {
4214 // Remove all handles on a display if there are no windows left.
4215 mWindowHandlesByDisplay.erase(displayId);
4216 return;
4217 }
4218
4219 // Since we compare the pointer of input window handles across window updates, we need
4220 // to make sure the handle object for the same window stays unchanged across updates.
4221 const std::vector<sp<InputWindowHandle>>& oldHandles = getWindowHandlesLocked(displayId);
chaviwaf87b3e2019-10-01 16:59:28 -07004222 std::unordered_map<int32_t /*id*/, sp<InputWindowHandle>> oldHandlesById;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004223 for (const sp<InputWindowHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07004224 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004225 }
4226
4227 std::vector<sp<InputWindowHandle>> newHandles;
4228 for (const sp<InputWindowHandle>& handle : inputWindowHandles) {
4229 if (!handle->updateInfo()) {
4230 // handle no longer valid
4231 continue;
4232 }
4233
4234 const InputWindowInfo* info = handle->getInfo();
4235 if ((getInputChannelLocked(handle->getToken()) == nullptr &&
4236 info->portalToDisplayId == ADISPLAY_ID_NONE)) {
4237 const bool noInputChannel =
Michael Wright44753b12020-07-08 13:48:11 +01004238 info->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
4239 const bool canReceiveInput = !info->flags.test(InputWindowInfo::Flag::NOT_TOUCHABLE) ||
4240 !info->flags.test(InputWindowInfo::Flag::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004241 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07004242 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004243 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07004244 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004245 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004246 }
4247
4248 if (info->displayId != displayId) {
4249 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
4250 handle->getName().c_str(), displayId, info->displayId);
4251 continue;
4252 }
4253
Robert Carredd13602020-04-13 17:24:34 -07004254 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
4255 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviwaf87b3e2019-10-01 16:59:28 -07004256 const sp<InputWindowHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004257 oldHandle->updateFrom(handle);
4258 newHandles.push_back(oldHandle);
4259 } else {
4260 newHandles.push_back(handle);
4261 }
4262 }
4263
4264 // Insert or replace
4265 mWindowHandlesByDisplay[displayId] = newHandles;
4266}
4267
Arthur Hung72d8dc32020-03-28 00:48:39 +00004268void InputDispatcher::setInputWindows(
4269 const std::unordered_map<int32_t, std::vector<sp<InputWindowHandle>>>& handlesPerDisplay) {
4270 { // acquire lock
4271 std::scoped_lock _l(mLock);
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004272 for (const auto& [displayId, handles] : handlesPerDisplay) {
4273 setInputWindowsLocked(handles, displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004274 }
4275 }
4276 // Wake up poll loop since it may need to make new input dispatching choices.
4277 mLooper->wake();
4278}
4279
Arthur Hungb92218b2018-08-14 12:00:21 +08004280/**
4281 * Called from InputManagerService, update window handle list by displayId that can receive input.
4282 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
4283 * If set an empty list, remove all handles from the specific display.
4284 * For focused handle, check if need to change and send a cancel event to previous one.
4285 * For removed handle, check if need to send a cancel event if already in touch.
4286 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00004287void InputDispatcher::setInputWindowsLocked(
4288 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004289 if (DEBUG_FOCUS) {
4290 std::string windowList;
4291 for (const sp<InputWindowHandle>& iwh : inputWindowHandles) {
4292 windowList += iwh->getName() + " ";
4293 }
4294 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
4295 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004296
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004297 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
4298 for (const sp<InputWindowHandle>& window : inputWindowHandles) {
4299 const bool noInputWindow =
4300 window->getInfo()->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
4301 if (noInputWindow && window->getToken() != nullptr) {
4302 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
4303 window->getName().c_str());
4304 window->releaseChannel();
4305 }
4306 }
4307
Arthur Hung72d8dc32020-03-28 00:48:39 +00004308 // Copy old handles for release if they are no longer present.
4309 const std::vector<sp<InputWindowHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004310
Arthur Hung72d8dc32020-03-28 00:48:39 +00004311 updateWindowHandlesForDisplayLocked(inputWindowHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004312
Vishnu Nair958da932020-08-21 17:12:37 -07004313 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
4314 if (mLastHoverWindowHandle &&
4315 std::find(windowHandles.begin(), windowHandles.end(), mLastHoverWindowHandle) ==
4316 windowHandles.end()) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004317 mLastHoverWindowHandle = nullptr;
4318 }
4319
Vishnu Nairc519ff72021-01-21 08:23:08 -08004320 std::optional<FocusResolver::FocusChanges> changes =
4321 mFocusResolver.setInputWindows(displayId, windowHandles);
4322 if (changes) {
4323 onFocusChangedLocked(*changes);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004324 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004325
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004326 std::unordered_map<int32_t, TouchState>::iterator stateIt =
4327 mTouchStatesByDisplay.find(displayId);
4328 if (stateIt != mTouchStatesByDisplay.end()) {
4329 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00004330 for (size_t i = 0; i < state.windows.size();) {
4331 TouchedWindow& touchedWindow = state.windows[i];
Mady Mellor017bcd12020-06-23 19:12:00 +00004332 if (!hasWindowHandleLocked(touchedWindow.windowHandle)) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004333 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004334 ALOGD("Touched window was removed: %s in display %" PRId32,
4335 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004336 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004337 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00004338 getInputChannelLocked(touchedWindow.windowHandle->getToken());
4339 if (touchedInputChannel != nullptr) {
4340 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4341 "touched window was removed");
4342 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004343 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004344 state.windows.erase(state.windows.begin() + i);
4345 } else {
4346 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004347 }
4348 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004349 }
Arthur Hung25e2af12020-03-26 12:58:37 +00004350
Arthur Hung72d8dc32020-03-28 00:48:39 +00004351 // Release information for windows that are no longer present.
4352 // This ensures that unused input channels are released promptly.
4353 // Otherwise, they might stick around until the window handle is destroyed
4354 // which might not happen until the next GC.
4355 for (const sp<InputWindowHandle>& oldWindowHandle : oldWindowHandles) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004356 if (!hasWindowHandleLocked(oldWindowHandle)) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004357 if (DEBUG_FOCUS) {
4358 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00004359 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004360 oldWindowHandle->releaseChannel();
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004361 // To avoid making too many calls into the compat framework, only
4362 // check for window flags when windows are going away.
4363 // TODO(b/157929241) : delete this. This is only needed temporarily
4364 // in order to gather some data about the flag usage
4365 if (oldWindowHandle->getInfo()->flags.test(InputWindowInfo::Flag::SLIPPERY)) {
4366 ALOGW("%s has FLAG_SLIPPERY. Please report this in b/157929241",
4367 oldWindowHandle->getName().c_str());
4368 if (mCompatService != nullptr) {
4369 mCompatService->reportChangeByUid(IInputConstants::BLOCK_FLAG_SLIPPERY,
4370 oldWindowHandle->getInfo()->ownerUid);
4371 }
4372 }
Arthur Hung25e2af12020-03-26 12:58:37 +00004373 }
chaviw291d88a2019-02-14 10:33:58 -08004374 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004375}
4376
4377void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07004378 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004379 if (DEBUG_FOCUS) {
4380 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
4381 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
4382 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004383 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004384 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004385
Chris Yea209fde2020-07-22 13:54:51 -07004386 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08004387 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004388
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004389 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
4390 return; // This application is already focused. No need to wake up or change anything.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004391 }
4392
Chris Yea209fde2020-07-22 13:54:51 -07004393 // Set the new application handle.
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004394 if (inputApplicationHandle != nullptr) {
4395 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
4396 } else {
4397 mFocusedApplicationHandlesByDisplay.erase(displayId);
4398 }
4399
4400 // No matter what the old focused application was, stop waiting on it because it is
4401 // no longer focused.
4402 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004403 } // release lock
4404
4405 // Wake up poll loop since it may need to make new input dispatching choices.
4406 mLooper->wake();
4407}
4408
Tiger Huang721e26f2018-07-24 22:26:19 +08004409/**
4410 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
4411 * the display not specified.
4412 *
4413 * We track any unreleased events for each window. If a window loses the ability to receive the
4414 * released event, we will send a cancel event to it. So when the focused display is changed, we
4415 * cancel all the unreleased display-unspecified events for the focused window on the old focused
4416 * display. The display-specified events won't be affected.
4417 */
4418void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004419 if (DEBUG_FOCUS) {
4420 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
4421 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004422 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004423 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08004424
4425 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004426 sp<IBinder> oldFocusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08004427 mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07004428 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004429 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07004430 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08004431 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004432 CancelationOptions
4433 options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
4434 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004435 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08004436 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
4437 }
4438 }
4439 mFocusedDisplayId = displayId;
4440
Chris Ye3c2d6f52020-08-09 10:39:48 -07004441 // Find new focused window and validate
Vishnu Nairc519ff72021-01-21 08:23:08 -08004442 sp<IBinder> newFocusedWindowToken = mFocusResolver.getFocusedWindowToken(displayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07004443 notifyFocusChangedLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08004444
Vishnu Nairad321cd2020-08-20 16:40:21 -07004445 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08004446 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairc519ff72021-01-21 08:23:08 -08004447 if (mFocusResolver.hasFocusedWindowTokens()) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004448 ALOGE("But another display has a focused window\n%s",
Vishnu Nairc519ff72021-01-21 08:23:08 -08004449 mFocusResolver.dumpFocusedWindows().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08004450 }
4451 }
4452 }
4453
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004454 if (DEBUG_FOCUS) {
4455 logDispatchStateLocked();
4456 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004457 } // release lock
4458
4459 // Wake up poll loop since it may need to make new input dispatching choices.
4460 mLooper->wake();
4461}
4462
Michael Wrightd02c5b62014-02-10 15:10:22 -08004463void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004464 if (DEBUG_FOCUS) {
4465 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
4466 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004467
4468 bool changed;
4469 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004470 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004471
4472 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
4473 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004474 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004475 }
4476
4477 if (mDispatchEnabled && !enabled) {
4478 resetAndDropEverythingLocked("dispatcher is being disabled");
4479 }
4480
4481 mDispatchEnabled = enabled;
4482 mDispatchFrozen = frozen;
4483 changed = true;
4484 } else {
4485 changed = false;
4486 }
4487
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004488 if (DEBUG_FOCUS) {
4489 logDispatchStateLocked();
4490 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004491 } // release lock
4492
4493 if (changed) {
4494 // Wake up poll loop since it may need to make new input dispatching choices.
4495 mLooper->wake();
4496 }
4497}
4498
4499void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004500 if (DEBUG_FOCUS) {
4501 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
4502 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004503
4504 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004505 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004506
4507 if (mInputFilterEnabled == enabled) {
4508 return;
4509 }
4510
4511 mInputFilterEnabled = enabled;
4512 resetAndDropEverythingLocked("input filter is being enabled or disabled");
4513 } // release lock
4514
4515 // Wake up poll loop since there might be work to do to drop everything.
4516 mLooper->wake();
4517}
4518
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08004519void InputDispatcher::setInTouchMode(bool inTouchMode) {
4520 std::scoped_lock lock(mLock);
4521 mInTouchMode = inTouchMode;
4522}
4523
Bernardo Rufinoea97d182020-08-19 14:43:14 +01004524void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
4525 if (opacity < 0 || opacity > 1) {
4526 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
4527 return;
4528 }
4529
4530 std::scoped_lock lock(mLock);
4531 mMaximumObscuringOpacityForTouch = opacity;
4532}
4533
4534void InputDispatcher::setBlockUntrustedTouchesMode(BlockUntrustedTouchesMode mode) {
4535 std::scoped_lock lock(mLock);
4536 mBlockUntrustedTouchesMode = mode;
4537}
4538
chaviwfbe5d9c2018-12-26 12:23:37 -08004539bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken) {
4540 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004541 if (DEBUG_FOCUS) {
4542 ALOGD("Trivial transfer to same window.");
4543 }
chaviwfbe5d9c2018-12-26 12:23:37 -08004544 return true;
4545 }
4546
Michael Wrightd02c5b62014-02-10 15:10:22 -08004547 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004548 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004549
chaviwfbe5d9c2018-12-26 12:23:37 -08004550 sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromToken);
4551 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toToken);
Yi Kong9b14ac62018-07-17 13:48:38 -07004552 if (fromWindowHandle == nullptr || toWindowHandle == nullptr) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004553 ALOGW("Cannot transfer focus because from or to window not found.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004554 return false;
4555 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004556 if (DEBUG_FOCUS) {
4557 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
4558 fromWindowHandle->getName().c_str(), toWindowHandle->getName().c_str());
4559 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004560 if (fromWindowHandle->getInfo()->displayId != toWindowHandle->getInfo()->displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004561 if (DEBUG_FOCUS) {
4562 ALOGD("Cannot transfer focus because windows are on different displays.");
4563 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004564 return false;
4565 }
4566
4567 bool found = false;
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004568 for (std::pair<const int32_t, TouchState>& pair : mTouchStatesByDisplay) {
4569 TouchState& state = pair.second;
Jeff Brownf086ddb2014-02-11 14:28:48 -08004570 for (size_t i = 0; i < state.windows.size(); i++) {
4571 const TouchedWindow& touchedWindow = state.windows[i];
4572 if (touchedWindow.windowHandle == fromWindowHandle) {
4573 int32_t oldTargetFlags = touchedWindow.targetFlags;
4574 BitSet32 pointerIds = touchedWindow.pointerIds;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004575
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004576 state.windows.erase(state.windows.begin() + i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004577
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004578 int32_t newTargetFlags = oldTargetFlags &
4579 (InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_SPLIT |
4580 InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004581 state.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004582
Jeff Brownf086ddb2014-02-11 14:28:48 -08004583 found = true;
4584 goto Found;
4585 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004586 }
4587 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004588 Found:
Michael Wrightd02c5b62014-02-10 15:10:22 -08004589
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004590 if (!found) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004591 if (DEBUG_FOCUS) {
4592 ALOGD("Focus transfer failed because from window did not have focus.");
4593 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004594 return false;
4595 }
4596
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004597 sp<Connection> fromConnection = getConnectionLocked(fromToken);
4598 sp<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004599 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004600 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004601 CancelationOptions
4602 options(CancelationOptions::CANCEL_POINTER_EVENTS,
4603 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004604 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004605 synthesizePointerDownEventsForConnectionLocked(toConnection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004606 }
4607
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004608 if (DEBUG_FOCUS) {
4609 logDispatchStateLocked();
4610 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004611 } // release lock
4612
4613 // Wake up poll loop since it may need to make new input dispatching choices.
4614 mLooper->wake();
4615 return true;
4616}
4617
4618void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004619 if (DEBUG_FOCUS) {
4620 ALOGD("Resetting and dropping all events (%s).", reason);
4621 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004622
4623 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
4624 synthesizeCancelationEventsForAllConnectionsLocked(options);
4625
4626 resetKeyRepeatLocked();
4627 releasePendingEventLocked();
4628 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004629 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004630
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004631 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08004632 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004633 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07004634 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004635}
4636
4637void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004638 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004639 dumpDispatchStateLocked(dump);
4640
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004641 std::istringstream stream(dump);
4642 std::string line;
4643
4644 while (std::getline(stream, line, '\n')) {
4645 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004646 }
4647}
4648
Prabir Pradhan99987712020-11-10 18:43:05 -08004649std::string InputDispatcher::dumpPointerCaptureStateLocked() {
4650 std::string dump;
4651
4652 dump += StringPrintf(INDENT "FocusedWindowRequestedPointerCapture: %s\n",
4653 toString(mFocusedWindowRequestedPointerCapture));
4654
4655 std::string windowName = "None";
4656 if (mWindowTokenWithPointerCapture) {
4657 const sp<InputWindowHandle> captureWindowHandle =
4658 getWindowHandleLocked(mWindowTokenWithPointerCapture);
4659 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
4660 : "token has capture without window";
4661 }
4662 dump += StringPrintf(INDENT "CurrentWindowWithPointerCapture: %s\n", windowName.c_str());
4663
4664 return dump;
4665}
4666
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004667void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07004668 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
4669 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
4670 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08004671 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004672
Tiger Huang721e26f2018-07-24 22:26:19 +08004673 if (!mFocusedApplicationHandlesByDisplay.empty()) {
4674 dump += StringPrintf(INDENT "FocusedApplications:\n");
4675 for (auto& it : mFocusedApplicationHandlesByDisplay) {
4676 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07004677 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05004678 const std::chrono::duration timeout =
4679 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004680 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004681 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05004682 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08004683 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004684 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08004685 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004686 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004687
Vishnu Nairc519ff72021-01-21 08:23:08 -08004688 dump += mFocusResolver.dump();
Prabir Pradhan99987712020-11-10 18:43:05 -08004689 dump += dumpPointerCaptureStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004690
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004691 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004692 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004693 for (const std::pair<int32_t, TouchState>& pair : mTouchStatesByDisplay) {
4694 const TouchState& state = pair.second;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004695 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004696 state.displayId, toString(state.down), toString(state.split),
4697 state.deviceId, state.source);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004698 if (!state.windows.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004699 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004700 for (size_t i = 0; i < state.windows.size(); i++) {
4701 const TouchedWindow& touchedWindow = state.windows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004702 dump += StringPrintf(INDENT4
4703 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
4704 i, touchedWindow.windowHandle->getName().c_str(),
4705 touchedWindow.pointerIds.value, touchedWindow.targetFlags);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004706 }
4707 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004708 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004709 }
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004710 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004711 dump += INDENT3 "Portal windows:\n";
4712 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004713 const sp<InputWindowHandle> portalWindowHandle = state.portalWindows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004714 dump += StringPrintf(INDENT4 "%zu: name='%s'\n", i,
4715 portalWindowHandle->getName().c_str());
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004716 }
4717 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004718 }
4719 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004720 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004721 }
4722
Arthur Hungb92218b2018-08-14 12:00:21 +08004723 if (!mWindowHandlesByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004724 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004725 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
Arthur Hung3b413f22018-10-26 18:05:34 +08004726 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", it.first);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004727 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004728 dump += INDENT2 "Windows:\n";
4729 for (size_t i = 0; i < windowHandles.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004730 const sp<InputWindowHandle>& windowHandle = windowHandles[i];
Arthur Hungb92218b2018-08-14 12:00:21 +08004731 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004732
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00004733 dump += StringPrintf(INDENT3 "%zu: name='%s', id=%" PRId32 ", displayId=%d, "
Vishnu Nair47074b82020-08-14 11:54:47 -07004734 "portalToDisplayId=%d, paused=%s, focusable=%s, "
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00004735 "hasWallpaper=%s, visible=%s, alpha=%.2f, "
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00004736 "flags=%s, type=%s, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004737 "frame=[%d,%d][%d,%d], globalScale=%f, "
Bernardo Rufino49d99e42021-01-18 15:16:59 +00004738 "applicationInfo.name=%s, "
4739 "applicationInfo.token=%s, "
chaviw1ff3d1e2020-07-01 15:53:47 -07004740 "touchableRegion=",
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00004741 i, windowInfo->name.c_str(), windowInfo->id,
4742 windowInfo->displayId, windowInfo->portalToDisplayId,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004743 toString(windowInfo->paused),
Vishnu Nair47074b82020-08-14 11:54:47 -07004744 toString(windowInfo->focusable),
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004745 toString(windowInfo->hasWallpaper),
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00004746 toString(windowInfo->visible), windowInfo->alpha,
Michael Wright8759d672020-07-21 00:46:45 +01004747 windowInfo->flags.string().c_str(),
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00004748 NamedEnum::string(windowInfo->type).c_str(),
Michael Wright44753b12020-07-08 13:48:11 +01004749 windowInfo->frameLeft, windowInfo->frameTop,
4750 windowInfo->frameRight, windowInfo->frameBottom,
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004751 windowInfo->globalScaleFactor,
Bernardo Rufino49d99e42021-01-18 15:16:59 +00004752 windowInfo->applicationInfo.name.c_str(),
4753 toString(windowInfo->applicationInfo.token).c_str());
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00004754 dump += dumpRegion(windowInfo->touchableRegion);
Michael Wright44753b12020-07-08 13:48:11 +01004755 dump += StringPrintf(", inputFeatures=%s",
4756 windowInfo->inputFeatures.string().c_str());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004757 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%" PRId64
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00004758 "ms, trustedOverlay=%s, hasToken=%s, "
4759 "touchOcclusionMode=%s\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004760 windowInfo->ownerPid, windowInfo->ownerUid,
Bernardo Rufinoc2f1fad2020-11-04 17:30:57 +00004761 millis(windowInfo->dispatchingTimeout),
4762 toString(windowInfo->trustedOverlay),
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00004763 toString(windowInfo->token != nullptr),
4764 toString(windowInfo->touchOcclusionMode).c_str());
chaviw85b44202020-07-24 11:46:21 -07004765 windowInfo->transform.dump(dump, "transform", INDENT4);
Arthur Hungb92218b2018-08-14 12:00:21 +08004766 }
4767 } else {
4768 dump += INDENT2 "Windows: <none>\n";
4769 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004770 }
4771 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08004772 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004773 }
4774
Michael Wright3dd60e22019-03-27 22:06:44 +00004775 if (!mGlobalMonitorsByDisplay.empty() || !mGestureMonitorsByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004776 for (auto& it : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004777 const std::vector<Monitor>& monitors = it.second;
4778 dump += StringPrintf(INDENT "Global monitors in display %" PRId32 ":\n", it.first);
4779 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004780 }
4781 for (auto& it : mGestureMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004782 const std::vector<Monitor>& monitors = it.second;
4783 dump += StringPrintf(INDENT "Gesture monitors in display %" PRId32 ":\n", it.first);
4784 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004785 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004786 } else {
Michael Wright3dd60e22019-03-27 22:06:44 +00004787 dump += INDENT "Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004788 }
4789
4790 nsecs_t currentTime = now();
4791
4792 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004793 if (!mRecentQueue.empty()) {
4794 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004795 for (std::shared_ptr<EventEntry>& entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004796 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05004797 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004798 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004799 }
4800 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004801 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004802 }
4803
4804 // Dump event currently being dispatched.
4805 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004806 dump += INDENT "PendingEvent:\n";
4807 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05004808 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004809 dump += StringPrintf(", age=%" PRId64 "ms\n",
4810 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004811 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004812 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004813 }
4814
4815 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004816 if (!mInboundQueue.empty()) {
4817 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004818 for (std::shared_ptr<EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004819 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05004820 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004821 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004822 }
4823 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004824 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004825 }
4826
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004827 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004828 dump += INDENT "ReplacedKeys:\n";
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004829 for (const std::pair<KeyReplacement, int32_t>& pair : mReplacedKeys) {
4830 const KeyReplacement& replacement = pair.first;
4831 int32_t newKeyCode = pair.second;
4832 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004833 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07004834 }
4835 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004836 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07004837 }
4838
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004839 if (!mConnectionsByFd.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004840 dump += INDENT "Connections:\n";
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004841 for (const auto& pair : mConnectionsByFd) {
4842 const sp<Connection>& connection = pair.second;
4843 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004844 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004845 pair.first, connection->getInputChannelName().c_str(),
4846 connection->getWindowName().c_str(), connection->getStatusLabel(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004847 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004848
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004849 if (!connection->outboundQueue.empty()) {
4850 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
4851 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05004852 dump += dumpQueue(connection->outboundQueue, currentTime);
4853
Michael Wrightd02c5b62014-02-10 15:10:22 -08004854 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004855 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004856 }
4857
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004858 if (!connection->waitQueue.empty()) {
4859 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
4860 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05004861 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004862 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004863 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004864 }
4865 }
4866 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004867 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004868 }
4869
4870 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004871 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
4872 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004873 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004874 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004875 }
4876
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004877 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004878 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
4879 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
4880 ns2ms(mConfig.keyRepeatTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004881}
4882
Michael Wright3dd60e22019-03-27 22:06:44 +00004883void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
4884 const size_t numMonitors = monitors.size();
4885 for (size_t i = 0; i < numMonitors; i++) {
4886 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004887 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00004888 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
4889 dump += "\n";
4890 }
4891}
4892
Garfield Tan15601662020-09-22 15:32:38 -07004893base::Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(
4894 const std::string& name) {
4895#if DEBUG_CHANNEL_CREATION
4896 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004897#endif
4898
Garfield Tan15601662020-09-22 15:32:38 -07004899 std::shared_ptr<InputChannel> serverChannel;
4900 std::unique_ptr<InputChannel> clientChannel;
4901 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
4902
4903 if (result) {
4904 return base::Error(result) << "Failed to open input channel pair with name " << name;
4905 }
4906
Michael Wrightd02c5b62014-02-10 15:10:22 -08004907 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004908 std::scoped_lock _l(mLock);
Garfield Tan15601662020-09-22 15:32:38 -07004909 sp<Connection> connection = new Connection(serverChannel, false /*monitor*/, mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004910
Garfield Tan15601662020-09-22 15:32:38 -07004911 int fd = serverChannel->getFd();
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004912 mConnectionsByFd[fd] = connection;
Garfield Tan15601662020-09-22 15:32:38 -07004913 mInputChannelsByToken[serverChannel->getConnectionToken()] = serverChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004914
Michael Wrightd02c5b62014-02-10 15:10:22 -08004915 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
4916 } // release lock
4917
4918 // Wake the looper because some connections have changed.
4919 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07004920 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004921}
4922
Garfield Tan15601662020-09-22 15:32:38 -07004923base::Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(
Siarhei Vishniakou58cfc602020-12-14 23:21:30 +00004924 int32_t displayId, bool isGestureMonitor, const std::string& name, int32_t pid) {
Garfield Tan15601662020-09-22 15:32:38 -07004925 std::shared_ptr<InputChannel> serverChannel;
4926 std::unique_ptr<InputChannel> clientChannel;
4927 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
4928 if (result) {
4929 return base::Error(result) << "Failed to open input channel pair with name " << name;
4930 }
4931
Michael Wright3dd60e22019-03-27 22:06:44 +00004932 { // acquire lock
4933 std::scoped_lock _l(mLock);
4934
4935 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07004936 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
4937 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00004938 }
4939
Garfield Tan15601662020-09-22 15:32:38 -07004940 sp<Connection> connection = new Connection(serverChannel, true /*monitor*/, mIdGenerator);
Michael Wright3dd60e22019-03-27 22:06:44 +00004941
Garfield Tan15601662020-09-22 15:32:38 -07004942 const int fd = serverChannel->getFd();
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004943 mConnectionsByFd[fd] = connection;
Garfield Tan15601662020-09-22 15:32:38 -07004944 mInputChannelsByToken[serverChannel->getConnectionToken()] = serverChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00004945
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004946 auto& monitorsByDisplay =
4947 isGestureMonitor ? mGestureMonitorsByDisplay : mGlobalMonitorsByDisplay;
Siarhei Vishniakou58cfc602020-12-14 23:21:30 +00004948 monitorsByDisplay[displayId].emplace_back(serverChannel, pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00004949
4950 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
Michael Wright3dd60e22019-03-27 22:06:44 +00004951 }
Garfield Tan15601662020-09-22 15:32:38 -07004952
Michael Wright3dd60e22019-03-27 22:06:44 +00004953 // Wake the looper because some connections have changed.
4954 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07004955 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00004956}
4957
Garfield Tan15601662020-09-22 15:32:38 -07004958status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004959 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004960 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004961
Garfield Tan15601662020-09-22 15:32:38 -07004962 status_t status = removeInputChannelLocked(connectionToken, false /*notify*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004963 if (status) {
4964 return status;
4965 }
4966 } // release lock
4967
4968 // Wake the poll loop because removing the connection may have changed the current
4969 // synchronization state.
4970 mLooper->wake();
4971 return OK;
4972}
4973
Garfield Tan15601662020-09-22 15:32:38 -07004974status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
4975 bool notify) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004976 sp<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004977 if (connection == nullptr) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00004978 // Connection can be removed via socket hang up or an explicit call to 'removeInputChannel'
Michael Wrightd02c5b62014-02-10 15:10:22 -08004979 return BAD_VALUE;
4980 }
4981
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004982 removeConnectionLocked(connection);
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004983 mInputChannelsByToken.erase(connectionToken);
Robert Carr5c8a0262018-10-03 16:30:44 -07004984
Michael Wrightd02c5b62014-02-10 15:10:22 -08004985 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004986 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004987 }
4988
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004989 mLooper->removeFd(connection->inputChannel->getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004990
4991 nsecs_t currentTime = now();
4992 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
4993
4994 connection->status = Connection::STATUS_ZOMBIE;
4995 return OK;
4996}
4997
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004998void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
4999 removeMonitorChannelLocked(connectionToken, mGlobalMonitorsByDisplay);
5000 removeMonitorChannelLocked(connectionToken, mGestureMonitorsByDisplay);
Michael Wright3dd60e22019-03-27 22:06:44 +00005001}
5002
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005003void InputDispatcher::removeMonitorChannelLocked(
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005004 const sp<IBinder>& connectionToken,
Michael Wright3dd60e22019-03-27 22:06:44 +00005005 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005006 for (auto it = monitorsByDisplay.begin(); it != monitorsByDisplay.end();) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005007 std::vector<Monitor>& monitors = it->second;
5008 const size_t numMonitors = monitors.size();
5009 for (size_t i = 0; i < numMonitors; i++) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005010 if (monitors[i].inputChannel->getConnectionToken() == connectionToken) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005011 monitors.erase(monitors.begin() + i);
5012 break;
5013 }
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005014 }
Michael Wright3dd60e22019-03-27 22:06:44 +00005015 if (monitors.empty()) {
5016 it = monitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005017 } else {
5018 ++it;
5019 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005020 }
5021}
5022
Michael Wright3dd60e22019-03-27 22:06:44 +00005023status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
5024 { // acquire lock
5025 std::scoped_lock _l(mLock);
5026 std::optional<int32_t> foundDisplayId = findGestureMonitorDisplayByTokenLocked(token);
5027
5028 if (!foundDisplayId) {
5029 ALOGW("Attempted to pilfer pointers from an un-registered monitor or invalid token");
5030 return BAD_VALUE;
5031 }
5032 int32_t displayId = foundDisplayId.value();
5033
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005034 std::unordered_map<int32_t, TouchState>::iterator stateIt =
5035 mTouchStatesByDisplay.find(displayId);
5036 if (stateIt == mTouchStatesByDisplay.end()) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005037 ALOGW("Failed to pilfer pointers: no pointers on display %" PRId32 ".", displayId);
5038 return BAD_VALUE;
5039 }
5040
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005041 TouchState& state = stateIt->second;
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005042 std::shared_ptr<InputChannel> requestingChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005043 std::optional<int32_t> foundDeviceId;
5044 for (const TouchedMonitor& touchedMonitor : state.gestureMonitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005045 if (touchedMonitor.monitor.inputChannel->getConnectionToken() == token) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005046 requestingChannel = touchedMonitor.monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005047 foundDeviceId = state.deviceId;
5048 }
5049 }
5050 if (!foundDeviceId || !state.down) {
5051 ALOGW("Attempted to pilfer points from a monitor without any on-going pointer streams."
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005052 " Ignoring.");
Michael Wright3dd60e22019-03-27 22:06:44 +00005053 return BAD_VALUE;
5054 }
5055 int32_t deviceId = foundDeviceId.value();
5056
5057 // Send cancel events to all the input channels we're stealing from.
5058 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005059 "gesture monitor stole pointer stream");
Michael Wright3dd60e22019-03-27 22:06:44 +00005060 options.deviceId = deviceId;
5061 options.displayId = displayId;
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005062 std::string canceledWindows = "[";
Michael Wright3dd60e22019-03-27 22:06:44 +00005063 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005064 std::shared_ptr<InputChannel> channel =
5065 getInputChannelLocked(window.windowHandle->getToken());
Michael Wright3a240c42019-12-10 20:53:41 +00005066 if (channel != nullptr) {
5067 synthesizeCancelationEventsForInputChannelLocked(channel, options);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005068 canceledWindows += channel->getName() + ", ";
Michael Wright3a240c42019-12-10 20:53:41 +00005069 }
Michael Wright3dd60e22019-03-27 22:06:44 +00005070 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005071 canceledWindows += "]";
5072 ALOGI("Monitor %s is stealing touch from %s", requestingChannel->getName().c_str(),
5073 canceledWindows.c_str());
5074
Michael Wright3dd60e22019-03-27 22:06:44 +00005075 // Then clear the current touch state so we stop dispatching to them as well.
5076 state.filterNonMonitors();
5077 }
5078 return OK;
5079}
5080
Prabir Pradhan99987712020-11-10 18:43:05 -08005081void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
5082 { // acquire lock
5083 std::scoped_lock _l(mLock);
5084 if (DEBUG_FOCUS) {
5085 const sp<InputWindowHandle> windowHandle = getWindowHandleLocked(windowToken);
5086 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
5087 windowHandle != nullptr ? windowHandle->getName().c_str()
5088 : "token without window");
5089 }
5090
Vishnu Nairc519ff72021-01-21 08:23:08 -08005091 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08005092 if (focusedToken != windowToken) {
5093 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
5094 enabled ? "enable" : "disable");
5095 return;
5096 }
5097
5098 if (enabled == mFocusedWindowRequestedPointerCapture) {
5099 ALOGW("Ignoring request to %s Pointer Capture: "
5100 "window has %s requested pointer capture.",
5101 enabled ? "enable" : "disable", enabled ? "already" : "not");
5102 return;
5103 }
5104
5105 mFocusedWindowRequestedPointerCapture = enabled;
5106 setPointerCaptureLocked(enabled);
5107 } // release lock
5108
5109 // Wake the thread to process command entries.
5110 mLooper->wake();
5111}
5112
Michael Wright3dd60e22019-03-27 22:06:44 +00005113std::optional<int32_t> InputDispatcher::findGestureMonitorDisplayByTokenLocked(
5114 const sp<IBinder>& token) {
5115 for (const auto& it : mGestureMonitorsByDisplay) {
5116 const std::vector<Monitor>& monitors = it.second;
5117 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005118 if (monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005119 return it.first;
5120 }
5121 }
5122 }
5123 return std::nullopt;
5124}
5125
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005126std::optional<int32_t> InputDispatcher::findMonitorPidByTokenLocked(const sp<IBinder>& token) {
5127 std::optional<int32_t> gesturePid = findMonitorPidByToken(mGestureMonitorsByDisplay, token);
5128 if (gesturePid.has_value()) {
5129 return gesturePid;
5130 }
5131 return findMonitorPidByToken(mGlobalMonitorsByDisplay, token);
5132}
5133
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005134sp<Connection> InputDispatcher::getConnectionLocked(const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005135 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005136 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08005137 }
5138
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005139 for (const auto& pair : mConnectionsByFd) {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005140 const sp<Connection>& connection = pair.second;
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005141 if (connection->inputChannel->getConnectionToken() == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005142 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005143 }
5144 }
Robert Carr4e670e52018-08-15 13:26:12 -07005145
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005146 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005147}
5148
Siarhei Vishniakouad991402020-10-28 11:40:09 -05005149std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
5150 sp<Connection> connection = getConnectionLocked(connectionToken);
5151 if (connection == nullptr) {
5152 return "<nullptr>";
5153 }
5154 return connection->getInputChannelName();
5155}
5156
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005157void InputDispatcher::removeConnectionLocked(const sp<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005158 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005159 removeByValue(mConnectionsByFd, connection);
5160}
5161
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005162void InputDispatcher::onDispatchCycleFinishedLocked(nsecs_t currentTime,
5163 const sp<Connection>& connection, uint32_t seq,
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10005164 bool handled, nsecs_t consumeTime) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005165 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5166 &InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005167 commandEntry->connection = connection;
5168 commandEntry->eventTime = currentTime;
5169 commandEntry->seq = seq;
5170 commandEntry->handled = handled;
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10005171 commandEntry->consumeTime = consumeTime;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005172 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005173}
5174
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005175void InputDispatcher::onDispatchCycleBrokenLocked(nsecs_t currentTime,
5176 const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005177 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005178 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005179
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005180 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5181 &InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005182 commandEntry->connection = connection;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005183 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005184}
5185
Vishnu Nairad321cd2020-08-20 16:40:21 -07005186void InputDispatcher::notifyFocusChangedLocked(const sp<IBinder>& oldToken,
5187 const sp<IBinder>& newToken) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005188 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5189 &InputDispatcher::doNotifyFocusChangedLockedInterruptible);
chaviw0c06c6e2019-01-09 13:27:07 -08005190 commandEntry->oldToken = oldToken;
5191 commandEntry->newToken = newToken;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07005192 postCommandLocked(std::move(commandEntry));
Robert Carrf759f162018-11-13 12:57:11 -08005193}
5194
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005195void InputDispatcher::onAnrLocked(const sp<Connection>& connection) {
5196 if (connection == nullptr) {
5197 LOG_ALWAYS_FATAL("Caller must check for nullness");
5198 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005199 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
5200 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005201 if (connection->waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005202 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005203 connection->inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005204 return;
5205 }
5206 /**
5207 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
5208 * may not be the one that caused the timeout to occur. One possibility is that window timeout
5209 * has changed. This could cause newer entries to time out before the already dispatched
5210 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
5211 * processes the events linearly. So providing information about the oldest entry seems to be
5212 * most useful.
5213 */
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005214 DispatchEntry* oldestEntry = *connection->waitQueue.begin();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005215 const nsecs_t currentWait = now() - oldestEntry->deliveryTime;
5216 std::string reason =
5217 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005218 connection->inputChannel->getName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005219 ns2ms(currentWait),
5220 oldestEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005221 sp<IBinder> connectionToken = connection->inputChannel->getConnectionToken();
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06005222 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005223
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005224 processConnectionUnresponsiveLocked(*connection, std::move(reason));
5225
5226 // Stop waking up for events on this connection, it is already unresponsive
5227 cancelEventsForAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005228}
5229
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005230void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
5231 std::string reason =
5232 StringPrintf("%s does not have a focused window", application->getName().c_str());
5233 updateLastAnrStateLocked(*application, reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005234
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005235 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5236 &InputDispatcher::doNotifyNoFocusedWindowAnrLockedInterruptible);
5237 commandEntry->inputApplicationHandle = std::move(application);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005238 postCommandLocked(std::move(commandEntry));
5239}
5240
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00005241void InputDispatcher::onUntrustedTouchLocked(const std::string& obscuringPackage) {
5242 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5243 &InputDispatcher::doNotifyUntrustedTouchLockedInterruptible);
5244 commandEntry->obscuringPackage = obscuringPackage;
5245 postCommandLocked(std::move(commandEntry));
5246}
5247
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005248void InputDispatcher::updateLastAnrStateLocked(const sp<InputWindowHandle>& window,
5249 const std::string& reason) {
5250 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
5251 updateLastAnrStateLocked(windowLabel, reason);
5252}
5253
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005254void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
5255 const std::string& reason) {
5256 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005257 updateLastAnrStateLocked(windowLabel, reason);
5258}
5259
5260void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
5261 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005262 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07005263 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005264 struct tm tm;
5265 localtime_r(&t, &tm);
5266 char timestr[64];
5267 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005268 mLastAnrState.clear();
5269 mLastAnrState += INDENT "ANR:\n";
5270 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005271 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
5272 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005273 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005274}
5275
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005276void InputDispatcher::doNotifyConfigurationChangedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005277 mLock.unlock();
5278
5279 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
5280
5281 mLock.lock();
5282}
5283
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005284void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005285 sp<Connection> connection = commandEntry->connection;
5286
5287 if (connection->status != Connection::STATUS_ZOMBIE) {
5288 mLock.unlock();
5289
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005290 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005291
5292 mLock.lock();
5293 }
5294}
5295
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005296void InputDispatcher::doNotifyFocusChangedLockedInterruptible(CommandEntry* commandEntry) {
chaviw0c06c6e2019-01-09 13:27:07 -08005297 sp<IBinder> oldToken = commandEntry->oldToken;
5298 sp<IBinder> newToken = commandEntry->newToken;
Robert Carrf759f162018-11-13 12:57:11 -08005299 mLock.unlock();
chaviw0c06c6e2019-01-09 13:27:07 -08005300 mPolicy->notifyFocusChanged(oldToken, newToken);
Robert Carrf759f162018-11-13 12:57:11 -08005301 mLock.lock();
5302}
5303
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005304void InputDispatcher::doNotifyNoFocusedWindowAnrLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005305 mLock.unlock();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005306
5307 mPolicy->notifyNoFocusedWindowAnr(commandEntry->inputApplicationHandle);
5308
5309 mLock.lock();
5310}
5311
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005312void InputDispatcher::doNotifyWindowUnresponsiveLockedInterruptible(CommandEntry* commandEntry) {
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005313 mLock.unlock();
5314
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005315 mPolicy->notifyWindowUnresponsive(commandEntry->connectionToken, commandEntry->reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005316
5317 mLock.lock();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005318}
5319
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005320void InputDispatcher::doNotifyMonitorUnresponsiveLockedInterruptible(CommandEntry* commandEntry) {
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005321 mLock.unlock();
5322
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005323 mPolicy->notifyMonitorUnresponsive(commandEntry->pid, commandEntry->reason);
5324
5325 mLock.lock();
5326}
5327
5328void InputDispatcher::doNotifyWindowResponsiveLockedInterruptible(CommandEntry* commandEntry) {
5329 mLock.unlock();
5330
5331 mPolicy->notifyWindowResponsive(commandEntry->connectionToken);
5332
5333 mLock.lock();
5334}
5335
5336void InputDispatcher::doNotifyMonitorResponsiveLockedInterruptible(CommandEntry* commandEntry) {
5337 mLock.unlock();
5338
5339 mPolicy->notifyMonitorResponsive(commandEntry->pid);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005340
5341 mLock.lock();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005342}
5343
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00005344void InputDispatcher::doNotifyUntrustedTouchLockedInterruptible(CommandEntry* commandEntry) {
5345 mLock.unlock();
5346
5347 mPolicy->notifyUntrustedTouch(commandEntry->obscuringPackage);
5348
5349 mLock.lock();
5350}
5351
Michael Wrightd02c5b62014-02-10 15:10:22 -08005352void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
5353 CommandEntry* commandEntry) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005354 KeyEntry& entry = *(commandEntry->keyEntry);
5355 KeyEvent event = createKeyEvent(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005356
5357 mLock.unlock();
5358
Michael Wright2b3c3302018-03-02 17:19:13 +00005359 android::base::Timer t;
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06005360 const sp<IBinder>& token = commandEntry->connectionToken;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005361 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(token, &event, entry.policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00005362 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
5363 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005364 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00005365 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005366
5367 mLock.lock();
5368
5369 if (delay < 0) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005370 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005371 } else if (!delay) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005372 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005373 } else {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005374 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
5375 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005376 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005377}
5378
chaviwfd6d3512019-03-25 13:23:49 -07005379void InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible(CommandEntry* commandEntry) {
5380 mLock.unlock();
5381 mPolicy->onPointerDownOutsideFocus(commandEntry->newToken);
5382 mLock.lock();
5383}
5384
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005385/**
5386 * Connection is responsive if it has no events in the waitQueue that are older than the
5387 * current time.
5388 */
5389static bool isConnectionResponsive(const Connection& connection) {
5390 const nsecs_t currentTime = now();
5391 for (const DispatchEntry* entry : connection.waitQueue) {
5392 if (entry->timeoutTime < currentTime) {
5393 return false;
5394 }
5395 }
5396 return true;
5397}
5398
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005399void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005400 sp<Connection> connection = commandEntry->connection;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005401 const nsecs_t finishTime = commandEntry->eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005402 uint32_t seq = commandEntry->seq;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005403 const bool handled = commandEntry->handled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005404
5405 // Handle post-event policy actions.
Garfield Tane84e6f92019-08-29 17:28:41 -07005406 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005407 if (dispatchEntryIt == connection->waitQueue.end()) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005408 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005409 }
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005410 DispatchEntry* dispatchEntry = *dispatchEntryIt;
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07005411 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005412 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005413 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
5414 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005415 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07005416 reportDispatchStatistics(std::chrono::nanoseconds(eventDuration), *connection, handled);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005417
5418 bool restartEvent;
Siarhei Vishniakou49483272019-10-22 13:13:47 -07005419 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005420 KeyEntry& keyEntry = static_cast<KeyEntry&>(*(dispatchEntry->eventEntry));
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005421 restartEvent =
5422 afterKeyEventLockedInterruptible(connection, dispatchEntry, keyEntry, handled);
Siarhei Vishniakou49483272019-10-22 13:13:47 -07005423 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005424 MotionEntry& motionEntry = static_cast<MotionEntry&>(*(dispatchEntry->eventEntry));
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005425 restartEvent = afterMotionEventLockedInterruptible(connection, dispatchEntry, motionEntry,
5426 handled);
5427 } else {
5428 restartEvent = false;
5429 }
5430
5431 // Dequeue the event and start the next cycle.
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07005432 // Because the lock might have been released, it is possible that the
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005433 // contents of the wait queue to have been drained, so we need to double-check
5434 // a few things.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005435 dispatchEntryIt = connection->findWaitQueueEntry(seq);
5436 if (dispatchEntryIt != connection->waitQueue.end()) {
5437 dispatchEntry = *dispatchEntryIt;
5438 connection->waitQueue.erase(dispatchEntryIt);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005439 const sp<IBinder>& connectionToken = connection->inputChannel->getConnectionToken();
5440 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005441 if (!connection->responsive) {
5442 connection->responsive = isConnectionResponsive(*connection);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005443 if (connection->responsive) {
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005444 // The connection was unresponsive, and now it's responsive.
5445 processConnectionResponsiveLocked(*connection);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005446 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005447 }
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005448 traceWaitQueueLength(connection);
5449 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005450 connection->outboundQueue.push_front(dispatchEntry);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07005451 traceOutboundQueueLength(connection);
5452 } else {
5453 releaseDispatchEntry(dispatchEntry);
5454 }
5455 }
5456
5457 // Start the next dispatch cycle for this connection.
5458 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005459}
5460
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005461void InputDispatcher::sendMonitorUnresponsiveCommandLocked(int32_t pid, std::string reason) {
5462 std::unique_ptr<CommandEntry> monitorUnresponsiveCommand = std::make_unique<CommandEntry>(
5463 &InputDispatcher::doNotifyMonitorUnresponsiveLockedInterruptible);
5464 monitorUnresponsiveCommand->pid = pid;
5465 monitorUnresponsiveCommand->reason = std::move(reason);
5466 postCommandLocked(std::move(monitorUnresponsiveCommand));
5467}
5468
5469void InputDispatcher::sendWindowUnresponsiveCommandLocked(sp<IBinder> connectionToken,
5470 std::string reason) {
5471 std::unique_ptr<CommandEntry> windowUnresponsiveCommand = std::make_unique<CommandEntry>(
5472 &InputDispatcher::doNotifyWindowUnresponsiveLockedInterruptible);
5473 windowUnresponsiveCommand->connectionToken = std::move(connectionToken);
5474 windowUnresponsiveCommand->reason = std::move(reason);
5475 postCommandLocked(std::move(windowUnresponsiveCommand));
5476}
5477
5478void InputDispatcher::sendMonitorResponsiveCommandLocked(int32_t pid) {
5479 std::unique_ptr<CommandEntry> monitorResponsiveCommand = std::make_unique<CommandEntry>(
5480 &InputDispatcher::doNotifyMonitorResponsiveLockedInterruptible);
5481 monitorResponsiveCommand->pid = pid;
5482 postCommandLocked(std::move(monitorResponsiveCommand));
5483}
5484
5485void InputDispatcher::sendWindowResponsiveCommandLocked(sp<IBinder> connectionToken) {
5486 std::unique_ptr<CommandEntry> windowResponsiveCommand = std::make_unique<CommandEntry>(
5487 &InputDispatcher::doNotifyWindowResponsiveLockedInterruptible);
5488 windowResponsiveCommand->connectionToken = std::move(connectionToken);
5489 postCommandLocked(std::move(windowResponsiveCommand));
5490}
5491
5492/**
5493 * Tell the policy that a connection has become unresponsive so that it can start ANR.
5494 * Check whether the connection of interest is a monitor or a window, and add the corresponding
5495 * command entry to the command queue.
5496 */
5497void InputDispatcher::processConnectionUnresponsiveLocked(const Connection& connection,
5498 std::string reason) {
5499 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
5500 if (connection.monitor) {
5501 ALOGW("Monitor %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
5502 reason.c_str());
5503 std::optional<int32_t> pid = findMonitorPidByTokenLocked(connectionToken);
5504 if (!pid.has_value()) {
5505 ALOGE("Could not find unresponsive monitor for connection %s",
5506 connection.inputChannel->getName().c_str());
5507 return;
5508 }
5509 sendMonitorUnresponsiveCommandLocked(pid.value(), std::move(reason));
5510 return;
5511 }
5512 // If not a monitor, must be a window
5513 ALOGW("Window %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
5514 reason.c_str());
5515 sendWindowUnresponsiveCommandLocked(connectionToken, std::move(reason));
5516}
5517
5518/**
5519 * Tell the policy that a connection has become responsive so that it can stop ANR.
5520 */
5521void InputDispatcher::processConnectionResponsiveLocked(const Connection& connection) {
5522 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
5523 if (connection.monitor) {
5524 std::optional<int32_t> pid = findMonitorPidByTokenLocked(connectionToken);
5525 if (!pid.has_value()) {
5526 ALOGE("Could not find responsive monitor for connection %s",
5527 connection.inputChannel->getName().c_str());
5528 return;
5529 }
5530 sendMonitorResponsiveCommandLocked(pid.value());
5531 return;
5532 }
5533 // If not a monitor, must be a window
5534 sendWindowResponsiveCommandLocked(connectionToken);
5535}
5536
Michael Wrightd02c5b62014-02-10 15:10:22 -08005537bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005538 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005539 KeyEntry& keyEntry, bool handled) {
5540 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005541 if (!handled) {
5542 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005543 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005544 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005545 return false;
5546 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005547
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005548 // Get the fallback key state.
5549 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005550 int32_t originalKeyCode = keyEntry.keyCode;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005551 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005552 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005553 connection->inputState.removeFallbackKey(originalKeyCode);
5554 }
5555
5556 if (handled || !dispatchEntry->hasForegroundTarget()) {
5557 // If the application handles the original key for which we previously
5558 // generated a fallback or if the window is not a foreground window,
5559 // then cancel the associated fallback key, if any.
5560 if (fallbackKeyCode != -1) {
5561 // Dispatch the unhandled key to the policy with the cancel flag.
Michael Wrightd02c5b62014-02-10 15:10:22 -08005562#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005563 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005564 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005565 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005566#endif
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005567 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005568 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005569
5570 mLock.unlock();
5571
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005572 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005573 keyEntry.policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005574
5575 mLock.lock();
5576
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005577 // Cancel the fallback key.
5578 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005579 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005580 "application handled the original non-fallback key "
5581 "or is no longer a foreground target, "
5582 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005583 options.keyCode = fallbackKeyCode;
5584 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005585 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005586 connection->inputState.removeFallbackKey(originalKeyCode);
5587 }
5588 } else {
5589 // If the application did not handle a non-fallback key, first check
5590 // that we are in a good state to perform unhandled key event processing
5591 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005592 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005593 if (fallbackKeyCode == -1 && !initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005594#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005595 ALOGD("Unhandled key event: Skipping unhandled key event processing "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005596 "since this is not an initial down. "
5597 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005598 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005599#endif
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005600 return false;
5601 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005602
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005603 // Dispatch the unhandled key to the policy.
5604#if DEBUG_OUTBOUND_EVENT_DETAILS
5605 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005606 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005607 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005608#endif
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005609 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005610
5611 mLock.unlock();
5612
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005613 bool fallback =
5614 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005615 &event, keyEntry.policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005616
5617 mLock.lock();
5618
5619 if (connection->status != Connection::STATUS_NORMAL) {
5620 connection->inputState.removeFallbackKey(originalKeyCode);
5621 return false;
5622 }
5623
5624 // Latch the fallback keycode for this key on an initial down.
5625 // The fallback keycode cannot change at any other point in the lifecycle.
5626 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005627 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005628 fallbackKeyCode = event.getKeyCode();
5629 } else {
5630 fallbackKeyCode = AKEYCODE_UNKNOWN;
5631 }
5632 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
5633 }
5634
5635 ALOG_ASSERT(fallbackKeyCode != -1);
5636
5637 // Cancel the fallback key if the policy decides not to send it anymore.
5638 // We will continue to dispatch the key to the policy but we will no
5639 // longer dispatch a fallback key to the application.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005640 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
5641 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005642#if DEBUG_OUTBOUND_EVENT_DETAILS
5643 if (fallback) {
5644 ALOGD("Unhandled key event: Policy requested to send key %d"
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005645 "as a fallback for %d, but on the DOWN it had requested "
5646 "to send %d instead. Fallback canceled.",
5647 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005648 } else {
5649 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005650 "but on the DOWN it had requested to send %d. "
5651 "Fallback canceled.",
5652 originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005653 }
5654#endif
5655
5656 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
5657 "canceling fallback, policy no longer desires it");
5658 options.keyCode = fallbackKeyCode;
5659 synthesizeCancelationEventsForConnectionLocked(connection, options);
5660
5661 fallback = false;
5662 fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005663 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005664 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005665 }
5666 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005667
5668#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005669 {
5670 std::string msg;
5671 const KeyedVector<int32_t, int32_t>& fallbackKeys =
5672 connection->inputState.getFallbackKeys();
5673 for (size_t i = 0; i < fallbackKeys.size(); i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005674 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005675 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005676 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005677 fallbackKeys.size(), msg.c_str());
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005678 }
5679#endif
5680
5681 if (fallback) {
5682 // Restart the dispatch cycle using the fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005683 keyEntry.eventTime = event.getEventTime();
5684 keyEntry.deviceId = event.getDeviceId();
5685 keyEntry.source = event.getSource();
5686 keyEntry.displayId = event.getDisplayId();
5687 keyEntry.flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
5688 keyEntry.keyCode = fallbackKeyCode;
5689 keyEntry.scanCode = event.getScanCode();
5690 keyEntry.metaState = event.getMetaState();
5691 keyEntry.repeatCount = event.getRepeatCount();
5692 keyEntry.downTime = event.getDownTime();
5693 keyEntry.syntheticRepeat = false;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005694
5695#if DEBUG_OUTBOUND_EVENT_DETAILS
5696 ALOGD("Unhandled key event: Dispatching fallback key. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005697 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005698 originalKeyCode, fallbackKeyCode, keyEntry.metaState);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005699#endif
5700 return true; // restart the event
5701 } else {
5702#if DEBUG_OUTBOUND_EVENT_DETAILS
5703 ALOGD("Unhandled key event: No fallback key.");
5704#endif
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005705
5706 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005707 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005708 }
5709 }
5710 return false;
5711}
5712
5713bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005714 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005715 MotionEntry& motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005716 return false;
5717}
5718
5719void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
5720 mLock.unlock();
5721
Sean Stoutb4e0a592021-02-23 07:34:53 -08005722 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType,
5723 commandEntry->displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005724
5725 mLock.lock();
5726}
5727
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07005728void InputDispatcher::reportDispatchStatistics(std::chrono::nanoseconds eventDuration,
5729 const Connection& connection, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005730 // TODO Write some statistics about how long we spend waiting.
5731}
5732
Siarhei Vishniakoude4bf152019-08-16 11:12:52 -05005733/**
5734 * Report the touch event latency to the statsd server.
5735 * Input events are reported for statistics if:
5736 * - This is a touchscreen event
5737 * - InputFilter is not enabled
5738 * - Event is not injected or synthesized
5739 *
5740 * Statistics should be reported before calling addValue, to prevent a fresh new sample
5741 * from getting aggregated with the "old" data.
5742 */
5743void InputDispatcher::reportTouchEventForStatistics(const MotionEntry& motionEntry)
5744 REQUIRES(mLock) {
5745 const bool reportForStatistics = (motionEntry.source == AINPUT_SOURCE_TOUCHSCREEN) &&
5746 !(motionEntry.isSynthesized()) && !mInputFilterEnabled;
5747 if (!reportForStatistics) {
5748 return;
5749 }
5750
5751 if (mTouchStatistics.shouldReport()) {
5752 android::util::stats_write(android::util::TOUCH_EVENT_REPORTED, mTouchStatistics.getMin(),
5753 mTouchStatistics.getMax(), mTouchStatistics.getMean(),
5754 mTouchStatistics.getStDev(), mTouchStatistics.getCount());
5755 mTouchStatistics.reset();
5756 }
5757 const float latencyMicros = nanoseconds_to_microseconds(now() - motionEntry.eventTime);
5758 mTouchStatistics.addValue(latencyMicros);
5759}
5760
Michael Wrightd02c5b62014-02-10 15:10:22 -08005761void InputDispatcher::traceInboundQueueLengthLocked() {
5762 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005763 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005764 }
5765}
5766
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08005767void InputDispatcher::traceOutboundQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005768 if (ATRACE_ENABLED()) {
5769 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08005770 snprintf(counterName, sizeof(counterName), "oq:%s", connection->getWindowName().c_str());
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005771 ATRACE_INT(counterName, connection->outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005772 }
5773}
5774
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08005775void InputDispatcher::traceWaitQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005776 if (ATRACE_ENABLED()) {
5777 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08005778 snprintf(counterName, sizeof(counterName), "wq:%s", connection->getWindowName().c_str());
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005779 ATRACE_INT(counterName, connection->waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005780 }
5781}
5782
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005783void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005784 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005785
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005786 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005787 dumpDispatchStateLocked(dump);
5788
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005789 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005790 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005791 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005792 }
5793}
5794
5795void InputDispatcher::monitor() {
5796 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005797 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005798 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005799 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005800}
5801
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08005802/**
5803 * Wake up the dispatcher and wait until it processes all events and commands.
5804 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
5805 * this method can be safely called from any thread, as long as you've ensured that
5806 * the work you are interested in completing has already been queued.
5807 */
5808bool InputDispatcher::waitForIdle() {
5809 /**
5810 * Timeout should represent the longest possible time that a device might spend processing
5811 * events and commands.
5812 */
5813 constexpr std::chrono::duration TIMEOUT = 100ms;
5814 std::unique_lock lock(mLock);
5815 mLooper->wake();
5816 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
5817 return result == std::cv_status::no_timeout;
5818}
5819
Vishnu Naire798b472020-07-23 13:52:21 -07005820/**
5821 * Sets focus to the window identified by the token. This must be called
5822 * after updating any input window handles.
5823 *
5824 * Params:
5825 * request.token - input channel token used to identify the window that should gain focus.
5826 * request.focusedToken - the token that the caller expects currently to be focused. If the
5827 * specified token does not match the currently focused window, this request will be dropped.
5828 * If the specified focused token matches the currently focused window, the call will succeed.
5829 * Set this to "null" if this call should succeed no matter what the currently focused token is.
5830 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
5831 * when requesting the focus change. This determines which request gets
5832 * precedence if there is a focus change request from another source such as pointer down.
5833 */
Vishnu Nair958da932020-08-21 17:12:37 -07005834void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
5835 { // acquire lock
5836 std::scoped_lock _l(mLock);
Vishnu Nairc519ff72021-01-21 08:23:08 -08005837 std::optional<FocusResolver::FocusChanges> changes =
5838 mFocusResolver.setFocusedWindow(request, getWindowHandlesLocked(request.displayId));
5839 if (changes) {
5840 onFocusChangedLocked(*changes);
Vishnu Nair958da932020-08-21 17:12:37 -07005841 }
5842 } // release lock
5843 // Wake up poll loop since it may need to make new input dispatching choices.
5844 mLooper->wake();
5845}
5846
Vishnu Nairc519ff72021-01-21 08:23:08 -08005847void InputDispatcher::onFocusChangedLocked(const FocusResolver::FocusChanges& changes) {
5848 if (changes.oldFocus) {
5849 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(changes.oldFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005850 if (focusedInputChannel) {
5851 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
5852 "focus left window");
5853 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Vishnu Nairc519ff72021-01-21 08:23:08 -08005854 enqueueFocusEventLocked(changes.oldFocus, false /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005855 }
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005856 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08005857 if (changes.newFocus) {
5858 enqueueFocusEventLocked(changes.newFocus, true /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005859 }
5860
Prabir Pradhan99987712020-11-10 18:43:05 -08005861 // If a window has pointer capture, then it must have focus. We need to ensure that this
5862 // contract is upheld when pointer capture is being disabled due to a loss of window focus.
5863 // If the window loses focus before it loses pointer capture, then the window can be in a state
5864 // where it has pointer capture but not focus, violating the contract. Therefore we must
5865 // dispatch the pointer capture event before the focus event. Since focus events are added to
5866 // the front of the queue (above), we add the pointer capture event to the front of the queue
5867 // after the focus events are added. This ensures the pointer capture event ends up at the
5868 // front.
5869 disablePointerCaptureForcedLocked();
5870
Vishnu Nairc519ff72021-01-21 08:23:08 -08005871 if (mFocusedDisplayId == changes.displayId) {
5872 notifyFocusChangedLocked(changes.oldFocus, changes.newFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005873 }
5874}
Vishnu Nair958da932020-08-21 17:12:37 -07005875
Prabir Pradhan99987712020-11-10 18:43:05 -08005876void InputDispatcher::disablePointerCaptureForcedLocked() {
5877 if (!mFocusedWindowRequestedPointerCapture && !mWindowTokenWithPointerCapture) {
5878 return;
5879 }
5880
5881 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
5882
5883 if (mFocusedWindowRequestedPointerCapture) {
5884 mFocusedWindowRequestedPointerCapture = false;
5885 setPointerCaptureLocked(false);
5886 }
5887
5888 if (!mWindowTokenWithPointerCapture) {
5889 // No need to send capture changes because no window has capture.
5890 return;
5891 }
5892
5893 if (mPendingEvent != nullptr) {
5894 // Move the pending event to the front of the queue. This will give the chance
5895 // for the pending event to be dropped if it is a captured event.
5896 mInboundQueue.push_front(mPendingEvent);
5897 mPendingEvent = nullptr;
5898 }
5899
5900 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
5901 false /* hasCapture */);
5902 mInboundQueue.push_front(std::move(entry));
5903}
5904
Prabir Pradhan99987712020-11-10 18:43:05 -08005905void InputDispatcher::setPointerCaptureLocked(bool enabled) {
5906 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5907 &InputDispatcher::doSetPointerCaptureLockedInterruptible);
5908 commandEntry->enabled = enabled;
5909 postCommandLocked(std::move(commandEntry));
5910}
5911
5912void InputDispatcher::doSetPointerCaptureLockedInterruptible(
5913 android::inputdispatcher::CommandEntry* commandEntry) {
5914 mLock.unlock();
5915
5916 mPolicy->setPointerCapture(commandEntry->enabled);
5917
5918 mLock.lock();
5919}
5920
Garfield Tane84e6f92019-08-29 17:28:41 -07005921} // namespace android::inputdispatcher