blob: 001c50f533161a28d7f10b5c7d0cfe352f866d53 [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
Michael Wright2b3c3302018-03-02 17:19:13 +000022#include <android-base/chrono_utils.h>
Peter Collingbourneb04b9b82021-02-08 12:09:47 -080023#include <android-base/properties.h>
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080024#include <android-base/stringprintf.h>
Siarhei Vishniakou70622952020-07-30 11:17:23 -050025#include <android/os/IInputConstants.h>
Robert Carr4e670e52018-08-15 13:26:12 -070026#include <binder/Binder.h>
Dominik Laskowski75788452021-02-09 18:51:25 -080027#include <ftl/enum.h>
chaviw15fab6f2021-06-07 14:15:52 -050028#include <gui/SurfaceComposerClient.h>
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -080029#include <input/InputDevice.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070030#include <log/log.h>
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +000031#include <log/log_event_list.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070032#include <powermanager/PowerManager.h>
Michael Wright44753b12020-07-08 13:48:11 +010033#include <unistd.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070034#include <utils/Trace.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080035
Michael Wright44753b12020-07-08 13:48:11 +010036#include <cerrno>
37#include <cinttypes>
38#include <climits>
39#include <cstddef>
40#include <ctime>
41#include <queue>
42#include <sstream>
43
44#include "Connection.h"
Chris Yef59a2f42020-10-16 12:55:26 -070045#include "InputDispatcher.h"
Michael Wright44753b12020-07-08 13:48:11 +010046
Michael Wrightd02c5b62014-02-10 15:10:22 -080047#define INDENT " "
48#define INDENT2 " "
49#define INDENT3 " "
50#define INDENT4 " "
51
Peter Collingbourneb04b9b82021-02-08 12:09:47 -080052using android::base::HwTimeoutMultiplier;
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +000053using android::base::Result;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080054using android::base::StringPrintf;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -070055using android::gui::DisplayInfo;
chaviw98318de2021-05-19 16:45:23 -050056using android::gui::FocusRequest;
57using android::gui::TouchOcclusionMode;
58using android::gui::WindowInfo;
59using android::gui::WindowInfoHandle;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -080060using android::os::BlockUntrustedTouchesMode;
Siarhei Vishniakou2508b872020-12-03 16:33:53 -100061using android::os::IInputConstants;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -080062using android::os::InputEventInjectionResult;
63using android::os::InputEventInjectionSync;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080064
Garfield Tane84e6f92019-08-29 17:28:41 -070065namespace android::inputdispatcher {
Michael Wrightd02c5b62014-02-10 15:10:22 -080066
Prabir Pradhancef936d2021-07-21 16:17:52 +000067namespace {
68
Prabir Pradhan61a5d242021-07-26 16:41:09 +000069// Log detailed debug messages about each inbound event notification to the dispatcher.
70constexpr bool DEBUG_INBOUND_EVENT_DETAILS = false;
71
72// Log detailed debug messages about each outbound event processed by the dispatcher.
73constexpr bool DEBUG_OUTBOUND_EVENT_DETAILS = false;
74
75// Log debug messages about the dispatch cycle.
76constexpr bool DEBUG_DISPATCH_CYCLE = false;
77
78// Log debug messages about channel creation
79constexpr bool DEBUG_CHANNEL_CREATION = false;
80
81// Log debug messages about input event injection.
82constexpr bool DEBUG_INJECTION = false;
83
84// Log debug messages about input focus tracking.
85constexpr bool DEBUG_FOCUS = false;
86
Antonio Kantekf16f2832021-09-28 04:39:20 +000087// Log debug messages about touch mode event
88constexpr bool DEBUG_TOUCH_MODE = false;
89
Prabir Pradhan61a5d242021-07-26 16:41:09 +000090// Log debug messages about touch occlusion
Prabir Pradhan61a5d242021-07-26 16:41:09 +000091constexpr bool DEBUG_TOUCH_OCCLUSION = true;
92
93// Log debug messages about the app switch latency optimization.
94constexpr bool DEBUG_APP_SWITCH = false;
95
96// Log debug messages about hover events.
97constexpr bool DEBUG_HOVER = false;
98
Prabir Pradhancef936d2021-07-21 16:17:52 +000099// Temporarily releases a held mutex for the lifetime of the instance.
100// Named to match std::scoped_lock
101class scoped_unlock {
102public:
103 explicit scoped_unlock(std::mutex& mutex) : mMutex(mutex) { mMutex.unlock(); }
104 ~scoped_unlock() { mMutex.lock(); }
105
106private:
107 std::mutex& mMutex;
108};
109
Michael Wrightd02c5b62014-02-10 15:10:22 -0800110// Default input dispatching timeout if there is no focused application or paused window
111// from which to determine an appropriate dispatching timeout.
Peter Collingbourneb04b9b82021-02-08 12:09:47 -0800112const std::chrono::duration DEFAULT_INPUT_DISPATCHING_TIMEOUT = std::chrono::milliseconds(
113 android::os::IInputConstants::UNMULTIPLIED_DEFAULT_DISPATCHING_TIMEOUT_MILLIS *
114 HwTimeoutMultiplier());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800115
116// Amount of time to allow for all pending events to be processed when an app switch
117// key is on the way. This is used to preempt input dispatch and drop input events
118// when an application takes too long to respond and the user has pressed an app switch key.
Michael Wright2b3c3302018-03-02 17:19:13 +0000119constexpr nsecs_t APP_SWITCH_TIMEOUT = 500 * 1000000LL; // 0.5sec
Michael Wrightd02c5b62014-02-10 15:10:22 -0800120
121// Amount of time to allow for an event to be dispatched (measured since its eventTime)
122// before considering it stale and dropping it.
Vadim Tryshev78548252022-01-27 19:32:46 +0000123const nsecs_t STALE_EVENT_TIMEOUT = 10000 * 1000000LL // 10sec
124 * HwTimeoutMultiplier();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800125
Michael Wrightd02c5b62014-02-10 15:10:22 -0800126// 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 +0000127constexpr nsecs_t SLOW_EVENT_PROCESSING_WARNING_TIMEOUT = 2000 * 1000000LL; // 2sec
128
129// Log a warning when an interception call takes longer than this to process.
130constexpr std::chrono::milliseconds SLOW_INTERCEPTION_THRESHOLD = 50ms;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800131
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700132// Additional key latency in case a connection is still processing some motion events.
133// This will help with the case when a user touched a button that opens a new window,
134// and gives us the chance to dispatch the key to this new window.
135constexpr std::chrono::nanoseconds KEY_WAITING_FOR_EVENTS_TIMEOUT = 500ms;
136
Michael Wrightd02c5b62014-02-10 15:10:22 -0800137// Number of recent events to keep for debugging purposes.
Michael Wright2b3c3302018-03-02 17:19:13 +0000138constexpr size_t RECENT_QUEUE_MAX_SIZE = 10;
139
Antonio Kantekea47acb2021-12-23 12:41:25 -0800140// Event log tags. See EventLogTags.logtags for reference.
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +0000141constexpr int LOGTAG_INPUT_INTERACTION = 62000;
142constexpr int LOGTAG_INPUT_FOCUS = 62001;
Arthur Hungb3307ee2021-10-14 10:57:37 +0000143constexpr int LOGTAG_INPUT_CANCEL = 62003;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +0000144
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000145inline nsecs_t now() {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800146 return systemTime(SYSTEM_TIME_MONOTONIC);
147}
148
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000149inline const char* toString(bool value) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800150 return value ? "true" : "false";
151}
152
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000153inline const std::string toString(const sp<IBinder>& binder) {
Bernardo Rufino49d99e42021-01-18 15:16:59 +0000154 if (binder == nullptr) {
155 return "<null>";
156 }
157 return StringPrintf("%p", binder.get());
158}
159
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000160inline int32_t getMotionEventActionPointerIndex(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700161 return (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) >>
162 AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800163}
164
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000165bool isValidKeyAction(int32_t action) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800166 switch (action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700167 case AKEY_EVENT_ACTION_DOWN:
168 case AKEY_EVENT_ACTION_UP:
169 return true;
170 default:
171 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800172 }
173}
174
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000175bool validateKeyEvent(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700176 if (!isValidKeyAction(action)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800177 ALOGE("Key event has invalid action code 0x%x", action);
178 return false;
179 }
180 return true;
181}
182
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000183bool isValidMotionAction(int32_t action, int32_t actionButton, int32_t pointerCount) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800184 switch (action & AMOTION_EVENT_ACTION_MASK) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700185 case AMOTION_EVENT_ACTION_DOWN:
186 case AMOTION_EVENT_ACTION_UP:
187 case AMOTION_EVENT_ACTION_CANCEL:
188 case AMOTION_EVENT_ACTION_MOVE:
189 case AMOTION_EVENT_ACTION_OUTSIDE:
190 case AMOTION_EVENT_ACTION_HOVER_ENTER:
191 case AMOTION_EVENT_ACTION_HOVER_MOVE:
192 case AMOTION_EVENT_ACTION_HOVER_EXIT:
193 case AMOTION_EVENT_ACTION_SCROLL:
194 return true;
195 case AMOTION_EVENT_ACTION_POINTER_DOWN:
196 case AMOTION_EVENT_ACTION_POINTER_UP: {
197 int32_t index = getMotionEventActionPointerIndex(action);
198 return index >= 0 && index < pointerCount;
199 }
200 case AMOTION_EVENT_ACTION_BUTTON_PRESS:
201 case AMOTION_EVENT_ACTION_BUTTON_RELEASE:
202 return actionButton != 0;
203 default:
204 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800205 }
206}
207
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000208int64_t millis(std::chrono::nanoseconds t) {
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -0500209 return std::chrono::duration_cast<std::chrono::milliseconds>(t).count();
210}
211
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000212bool validateMotionEvent(int32_t action, int32_t actionButton, size_t pointerCount,
213 const PointerProperties* pointerProperties) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700214 if (!isValidMotionAction(action, actionButton, pointerCount)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800215 ALOGE("Motion event has invalid action code 0x%x", action);
216 return false;
217 }
218 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
Siarhei Vishniakou01747382022-01-20 13:23:27 -0800219 ALOGE("Motion event has invalid pointer count %zu; value must be between 1 and %zu.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700220 pointerCount, MAX_POINTERS);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800221 return false;
222 }
223 BitSet32 pointerIdBits;
224 for (size_t i = 0; i < pointerCount; i++) {
225 int32_t id = pointerProperties[i].id;
226 if (id < 0 || id > MAX_POINTER_ID) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700227 ALOGE("Motion event has invalid pointer id %d; value must be between 0 and %d", id,
228 MAX_POINTER_ID);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800229 return false;
230 }
231 if (pointerIdBits.hasBit(id)) {
232 ALOGE("Motion event has duplicate pointer id %d", id);
233 return false;
234 }
235 pointerIdBits.markBit(id);
236 }
237 return true;
238}
239
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000240std::string dumpRegion(const Region& region) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800241 if (region.isEmpty()) {
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000242 return "<empty>";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800243 }
244
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000245 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800246 bool first = true;
247 Region::const_iterator cur = region.begin();
248 Region::const_iterator const tail = region.end();
249 while (cur != tail) {
250 if (first) {
251 first = false;
252 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800253 dump += "|";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800254 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800255 dump += StringPrintf("[%d,%d][%d,%d]", cur->left, cur->top, cur->right, cur->bottom);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800256 cur++;
257 }
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000258 return dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800259}
260
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000261std::string dumpQueue(const std::deque<DispatchEntry*>& queue, nsecs_t currentTime) {
Siarhei Vishniakou14411c92020-09-18 21:15:05 -0500262 constexpr size_t maxEntries = 50; // max events to print
263 constexpr size_t skipBegin = maxEntries / 2;
264 const size_t skipEnd = queue.size() - maxEntries / 2;
265 // skip from maxEntries / 2 ... size() - maxEntries/2
266 // only print from 0 .. skipBegin and then from skipEnd .. size()
267
268 std::string dump;
269 for (size_t i = 0; i < queue.size(); i++) {
270 const DispatchEntry& entry = *queue[i];
271 if (i >= skipBegin && i < skipEnd) {
272 dump += StringPrintf(INDENT4 "<skipped %zu entries>\n", skipEnd - skipBegin);
273 i = skipEnd - 1; // it will be incremented to "skipEnd" by 'continue'
274 continue;
275 }
276 dump.append(INDENT4);
277 dump += entry.eventEntry->getDescription();
278 dump += StringPrintf(", seq=%" PRIu32
279 ", targetFlags=0x%08x, resolvedAction=%d, age=%" PRId64 "ms",
280 entry.seq, entry.targetFlags, entry.resolvedAction,
281 ns2ms(currentTime - entry.eventEntry->eventTime));
282 if (entry.deliveryTime != 0) {
283 // This entry was delivered, so add information on how long we've been waiting
284 dump += StringPrintf(", wait=%" PRId64 "ms", ns2ms(currentTime - entry.deliveryTime));
285 }
286 dump.append("\n");
287 }
288 return dump;
289}
290
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700291/**
292 * Find the entry in std::unordered_map by key, and return it.
293 * If the entry is not found, return a default constructed entry.
294 *
295 * Useful when the entries are vectors, since an empty vector will be returned
296 * if the entry is not found.
297 * Also useful when the entries are sp<>. If an entry is not found, nullptr is returned.
298 */
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700299template <typename K, typename V>
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000300V getValueByKey(const std::unordered_map<K, V>& map, K key) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700301 auto it = map.find(key);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700302 return it != map.end() ? it->second : V{};
Tiger Huang721e26f2018-07-24 22:26:19 +0800303}
304
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000305bool haveSameToken(const sp<WindowInfoHandle>& first, const sp<WindowInfoHandle>& second) {
chaviwaf87b3e2019-10-01 16:59:28 -0700306 if (first == second) {
307 return true;
308 }
309
310 if (first == nullptr || second == nullptr) {
311 return false;
312 }
313
314 return first->getToken() == second->getToken();
315}
316
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000317bool haveSameApplicationToken(const WindowInfo* first, const WindowInfo* second) {
Bernardo Rufino1ff9d592021-01-18 16:58:57 +0000318 if (first == nullptr || second == nullptr) {
319 return false;
320 }
321 return first->applicationInfo.token != nullptr &&
322 first->applicationInfo.token == second->applicationInfo.token;
323}
324
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000325bool isStaleEvent(nsecs_t currentTime, const EventEntry& entry) {
Siarhei Vishniakouadfd4fa2019-12-20 11:02:58 -0800326 return currentTime - entry.eventTime >= STALE_EVENT_TIMEOUT;
327}
328
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000329std::unique_ptr<DispatchEntry> createDispatchEntry(const InputTarget& inputTarget,
330 std::shared_ptr<EventEntry> eventEntry,
331 int32_t inputTargetFlags) {
chaviw1ff3d1e2020-07-01 15:53:47 -0700332 if (inputTarget.useDefaultPointerTransform()) {
333 const ui::Transform& transform = inputTarget.getDefaultPointerTransform();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700334 return std::make_unique<DispatchEntry>(eventEntry, inputTargetFlags, transform,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700335 inputTarget.displayTransform,
336 inputTarget.globalScaleFactor);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000337 }
338
339 ALOG_ASSERT(eventEntry->type == EventEntry::Type::MOTION);
340 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
341
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700342 std::vector<PointerCoords> pointerCoords;
343 pointerCoords.resize(motionEntry.pointerCount);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000344
345 // Use the first pointer information to normalize all other pointers. This could be any pointer
346 // as long as all other pointers are normalized to the same value and the final DispatchEntry
chaviw1ff3d1e2020-07-01 15:53:47 -0700347 // uses the transform for the normalized pointer.
348 const ui::Transform& firstPointerTransform =
349 inputTarget.pointerTransforms[inputTarget.pointerIds.firstMarkedBit()];
350 ui::Transform inverseFirstTransform = firstPointerTransform.inverse();
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000351
352 // Iterate through all pointers in the event to normalize against the first.
353 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.pointerCount; pointerIndex++) {
354 const PointerProperties& pointerProperties = motionEntry.pointerProperties[pointerIndex];
355 uint32_t pointerId = uint32_t(pointerProperties.id);
chaviw1ff3d1e2020-07-01 15:53:47 -0700356 const ui::Transform& currTransform = inputTarget.pointerTransforms[pointerId];
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000357
358 pointerCoords[pointerIndex].copyFrom(motionEntry.pointerCoords[pointerIndex]);
chaviw1ff3d1e2020-07-01 15:53:47 -0700359 // First, apply the current pointer's transform to update the coordinates into
360 // window space.
361 pointerCoords[pointerIndex].transform(currTransform);
362 // Next, apply the inverse transform of the normalized coordinates so the
363 // current coordinates are transformed into the normalized coordinate space.
364 pointerCoords[pointerIndex].transform(inverseFirstTransform);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000365 }
366
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700367 std::unique_ptr<MotionEntry> combinedMotionEntry =
368 std::make_unique<MotionEntry>(motionEntry.id, motionEntry.eventTime,
369 motionEntry.deviceId, motionEntry.source,
370 motionEntry.displayId, motionEntry.policyFlags,
371 motionEntry.action, motionEntry.actionButton,
372 motionEntry.flags, motionEntry.metaState,
373 motionEntry.buttonState, motionEntry.classification,
374 motionEntry.edgeFlags, motionEntry.xPrecision,
375 motionEntry.yPrecision, motionEntry.xCursorPosition,
376 motionEntry.yCursorPosition, motionEntry.downTime,
377 motionEntry.pointerCount, motionEntry.pointerProperties,
Prabir Pradhan5beda762021-12-10 09:30:08 +0000378 pointerCoords.data());
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000379
380 if (motionEntry.injectionState) {
381 combinedMotionEntry->injectionState = motionEntry.injectionState;
382 combinedMotionEntry->injectionState->refCount += 1;
383 }
384
385 std::unique_ptr<DispatchEntry> dispatchEntry =
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700386 std::make_unique<DispatchEntry>(std::move(combinedMotionEntry), inputTargetFlags,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700387 firstPointerTransform, inputTarget.displayTransform,
388 inputTarget.globalScaleFactor);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000389 return dispatchEntry;
390}
391
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000392status_t openInputChannelPair(const std::string& name, std::shared_ptr<InputChannel>& serverChannel,
393 std::unique_ptr<InputChannel>& clientChannel) {
Garfield Tan15601662020-09-22 15:32:38 -0700394 std::unique_ptr<InputChannel> uniqueServerChannel;
395 status_t result = InputChannel::openInputChannelPair(name, uniqueServerChannel, clientChannel);
396
397 serverChannel = std::move(uniqueServerChannel);
398 return result;
399}
400
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500401template <typename T>
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000402bool sharedPointersEqual(const std::shared_ptr<T>& lhs, const std::shared_ptr<T>& rhs) {
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500403 if (lhs == nullptr && rhs == nullptr) {
404 return true;
405 }
406 if (lhs == nullptr || rhs == nullptr) {
407 return false;
408 }
409 return *lhs == *rhs;
410}
411
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000412KeyEvent createKeyEvent(const KeyEntry& entry) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +0000413 KeyEvent event;
414 event.initialize(entry.id, entry.deviceId, entry.source, entry.displayId, INVALID_HMAC,
415 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
416 entry.repeatCount, entry.downTime, entry.eventTime);
417 return event;
418}
419
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000420bool shouldReportMetricsForConnection(const Connection& connection) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000421 // Do not keep track of gesture monitors. They receive every event and would disproportionately
422 // affect the statistics.
423 if (connection.monitor) {
424 return false;
425 }
426 // If the connection is experiencing ANR, let's skip it. We have separate ANR metrics
427 if (!connection.responsive) {
428 return false;
429 }
430 return true;
431}
432
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000433bool shouldReportFinishedEvent(const DispatchEntry& dispatchEntry, const Connection& connection) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000434 const EventEntry& eventEntry = *dispatchEntry.eventEntry;
435 const int32_t& inputEventId = eventEntry.id;
436 if (inputEventId != dispatchEntry.resolvedEventId) {
437 // Event was transmuted
438 return false;
439 }
440 if (inputEventId == android::os::IInputConstants::INVALID_INPUT_EVENT_ID) {
441 return false;
442 }
443 // Only track latency for events that originated from hardware
444 if (eventEntry.isSynthesized()) {
445 return false;
446 }
447 const EventEntry::Type& inputEventEntryType = eventEntry.type;
448 if (inputEventEntryType == EventEntry::Type::KEY) {
449 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
450 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
451 return false;
452 }
453 } else if (inputEventEntryType == EventEntry::Type::MOTION) {
454 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
455 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL ||
456 motionEntry.action == AMOTION_EVENT_ACTION_HOVER_EXIT) {
457 return false;
458 }
459 } else {
460 // Not a key or a motion
461 return false;
462 }
463 if (!shouldReportMetricsForConnection(connection)) {
464 return false;
465 }
466 return true;
467}
468
Prabir Pradhancef936d2021-07-21 16:17:52 +0000469/**
470 * Connection is responsive if it has no events in the waitQueue that are older than the
471 * current time.
472 */
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000473bool isConnectionResponsive(const Connection& connection) {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000474 const nsecs_t currentTime = now();
475 for (const DispatchEntry* entry : connection.waitQueue) {
476 if (entry->timeoutTime < currentTime) {
477 return false;
478 }
479 }
480 return true;
481}
482
Antonio Kantekf16f2832021-09-28 04:39:20 +0000483// Returns true if the event type passed as argument represents a user activity.
484bool isUserActivityEvent(const EventEntry& eventEntry) {
485 switch (eventEntry.type) {
486 case EventEntry::Type::FOCUS:
487 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
488 case EventEntry::Type::DRAG:
489 case EventEntry::Type::TOUCH_MODE_CHANGED:
490 case EventEntry::Type::SENSOR:
491 case EventEntry::Type::CONFIGURATION_CHANGED:
492 return false;
493 case EventEntry::Type::DEVICE_RESET:
494 case EventEntry::Type::KEY:
495 case EventEntry::Type::MOTION:
496 return true;
497 }
498}
499
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800500// Returns true if the given window can accept pointer events at the given display location.
Prabir Pradhand65552b2021-10-07 11:23:50 -0700501bool windowAcceptsTouchAt(const WindowInfo& windowInfo, int32_t displayId, int32_t x, int32_t y,
502 bool isStylus) {
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -0800503 const auto inputConfig = windowInfo.inputConfig;
504 if (windowInfo.displayId != displayId ||
505 inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800506 return false;
507 }
Prabir Pradhand65552b2021-10-07 11:23:50 -0700508 const bool windowCanInterceptTouch = isStylus && windowInfo.interceptsStylus();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -0800509 if (inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) && !windowCanInterceptTouch) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800510 return false;
511 }
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -0800512 const bool isModalWindow = !inputConfig.test(WindowInfo::InputConfig::NOT_FOCUSABLE) &&
513 !inputConfig.test(WindowInfo::InputConfig::NOT_TOUCH_MODAL);
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800514 if (!isModalWindow && !windowInfo.touchableRegionContainsPoint(x, y)) {
515 return false;
516 }
517 return true;
518}
519
Prabir Pradhand65552b2021-10-07 11:23:50 -0700520bool isPointerFromStylus(const MotionEntry& entry, int32_t pointerIndex) {
521 return isFromSource(entry.source, AINPUT_SOURCE_STYLUS) &&
522 (entry.pointerProperties[pointerIndex].toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS ||
523 entry.pointerProperties[pointerIndex].toolType == AMOTION_EVENT_TOOL_TYPE_ERASER);
524}
525
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000526} // namespace
527
Michael Wrightd02c5b62014-02-10 15:10:22 -0800528// --- InputDispatcher ---
529
Garfield Tan00f511d2019-06-12 16:55:40 -0700530InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy)
531 : mPolicy(policy),
532 mPendingEvent(nullptr),
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700533 mLastDropReason(DropReason::NOT_DROPPED),
Garfield Tanff1f1bb2020-01-28 13:24:04 -0800534 mIdGenerator(IdGenerator::Source::INPUT_DISPATCHER),
Garfield Tan00f511d2019-06-12 16:55:40 -0700535 mAppSwitchSawKeyDown(false),
536 mAppSwitchDueTime(LONG_LONG_MAX),
537 mNextUnblockedEvent(nullptr),
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800538 mMonitorDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT),
Garfield Tan00f511d2019-06-12 16:55:40 -0700539 mDispatchEnabled(false),
540 mDispatchFrozen(false),
541 mInputFilterEnabled(false),
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -0800542 // mInTouchMode will be initialized by the WindowManager to the default device config.
543 // To avoid leaking stack in case that call never comes, and for tests,
544 // initialize it here anyways.
Antonio Kantekf16f2832021-09-28 04:39:20 +0000545 mInTouchMode(kDefaultInTouchMode),
Bernardo Rufinoea97d182020-08-19 14:43:14 +0100546 mMaximumObscuringOpacityForTouch(1.0f),
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000547 mFocusedDisplayId(ADISPLAY_ID_DEFAULT),
Prabir Pradhan99987712020-11-10 18:43:05 -0800548 mWindowTokenWithPointerCapture(nullptr),
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +0000549 mLatencyAggregator(),
Siarhei Vishniakoubd252722022-01-06 03:49:35 -0800550 mLatencyTracker(&mLatencyAggregator) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800551 mLooper = new Looper(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800552 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800553
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700554 mWindowInfoListener = new DispatcherWindowListener(*this);
555 SurfaceComposerClient::getDefault()->addWindowInfosListener(mWindowInfoListener);
556
Yi Kong9b14ac62018-07-17 13:48:38 -0700557 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800558
559 policy->getDispatcherConfiguration(&mConfig);
560}
561
562InputDispatcher::~InputDispatcher() {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000563 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800564
Prabir Pradhancef936d2021-07-21 16:17:52 +0000565 resetKeyRepeatLocked();
566 releasePendingEventLocked();
567 drainInboundQueueLocked();
568 mCommandQueue.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800569
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +0000570 while (!mConnectionsByToken.empty()) {
571 sp<Connection> connection = mConnectionsByToken.begin()->second;
Prabir Pradhancef936d2021-07-21 16:17:52 +0000572 removeInputChannelLocked(connection->inputChannel->getConnectionToken(),
573 false /* notify */);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800574 }
575}
576
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700577status_t InputDispatcher::start() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700578 if (mThread) {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700579 return ALREADY_EXISTS;
580 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700581 mThread = std::make_unique<InputThread>(
582 "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
583 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700584}
585
586status_t InputDispatcher::stop() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700587 if (mThread && mThread->isCallingThread()) {
588 ALOGE("InputDispatcher cannot be stopped from its own thread!");
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700589 return INVALID_OPERATION;
590 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700591 mThread.reset();
592 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700593}
594
Michael Wrightd02c5b62014-02-10 15:10:22 -0800595void InputDispatcher::dispatchOnce() {
596 nsecs_t nextWakeupTime = LONG_LONG_MAX;
597 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800598 std::scoped_lock _l(mLock);
599 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800600
601 // Run a dispatch loop if there are no pending commands.
602 // The dispatch loop might enqueue commands to run afterwards.
603 if (!haveCommandsLocked()) {
604 dispatchOnceInnerLocked(&nextWakeupTime);
605 }
606
607 // Run all pending commands if there are any.
608 // If any commands were run then force the next poll to wake up immediately.
Prabir Pradhancef936d2021-07-21 16:17:52 +0000609 if (runCommandsLockedInterruptable()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800610 nextWakeupTime = LONG_LONG_MIN;
611 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800612
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700613 // If we are still waiting for ack on some events,
614 // we might have to wake up earlier to check if an app is anr'ing.
615 const nsecs_t nextAnrCheck = processAnrsLocked();
616 nextWakeupTime = std::min(nextWakeupTime, nextAnrCheck);
617
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800618 // We are about to enter an infinitely long sleep, because we have no commands or
619 // pending or queued events
620 if (nextWakeupTime == LONG_LONG_MAX) {
621 mDispatcherEnteredIdle.notify_all();
622 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800623 } // release lock
624
625 // Wait for callback or timeout or wake. (make sure we round up, not down)
626 nsecs_t currentTime = now();
627 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
628 mLooper->pollOnce(timeoutMillis);
629}
630
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700631/**
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500632 * Raise ANR if there is no focused window.
633 * Before the ANR is raised, do a final state check:
634 * 1. The currently focused application must be the same one we are waiting for.
635 * 2. Ensure we still don't have a focused window.
636 */
637void InputDispatcher::processNoFocusedWindowAnrLocked() {
638 // Check if the application that we are waiting for is still focused.
639 std::shared_ptr<InputApplicationHandle> focusedApplication =
640 getValueByKey(mFocusedApplicationHandlesByDisplay, mAwaitedApplicationDisplayId);
641 if (focusedApplication == nullptr ||
642 focusedApplication->getApplicationToken() !=
643 mAwaitedFocusedApplication->getApplicationToken()) {
644 // Unexpected because we should have reset the ANR timer when focused application changed
645 ALOGE("Waited for a focused window, but focused application has already changed to %s",
646 focusedApplication->getName().c_str());
647 return; // The focused application has changed.
648 }
649
chaviw98318de2021-05-19 16:45:23 -0500650 const sp<WindowInfoHandle>& focusedWindowHandle =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500651 getFocusedWindowHandleLocked(mAwaitedApplicationDisplayId);
652 if (focusedWindowHandle != nullptr) {
653 return; // We now have a focused window. No need for ANR.
654 }
655 onAnrLocked(mAwaitedFocusedApplication);
656}
657
658/**
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700659 * Check if any of the connections' wait queues have events that are too old.
660 * If we waited for events to be ack'ed for more than the window timeout, raise an ANR.
661 * Return the time at which we should wake up next.
662 */
663nsecs_t InputDispatcher::processAnrsLocked() {
664 const nsecs_t currentTime = now();
665 nsecs_t nextAnrCheck = LONG_LONG_MAX;
666 // Check if we are waiting for a focused window to appear. Raise ANR if waited too long
667 if (mNoFocusedWindowTimeoutTime.has_value() && mAwaitedFocusedApplication != nullptr) {
668 if (currentTime >= *mNoFocusedWindowTimeoutTime) {
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500669 processNoFocusedWindowAnrLocked();
Chris Yea209fde2020-07-22 13:54:51 -0700670 mAwaitedFocusedApplication.reset();
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500671 mNoFocusedWindowTimeoutTime = std::nullopt;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700672 return LONG_LONG_MIN;
673 } else {
Siarhei Vishniakou38a6d272020-10-20 20:29:33 -0500674 // Keep waiting. We will drop the event when mNoFocusedWindowTimeoutTime comes.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700675 nextAnrCheck = *mNoFocusedWindowTimeoutTime;
676 }
677 }
678
679 // Check if any connection ANRs are due
680 nextAnrCheck = std::min(nextAnrCheck, mAnrTracker.firstTimeout());
681 if (currentTime < nextAnrCheck) { // most likely scenario
682 return nextAnrCheck; // everything is normal. Let's check again at nextAnrCheck
683 }
684
685 // If we reached here, we have an unresponsive connection.
686 sp<Connection> connection = getConnectionLocked(mAnrTracker.firstToken());
687 if (connection == nullptr) {
688 ALOGE("Could not find connection for entry %" PRId64, mAnrTracker.firstTimeout());
689 return nextAnrCheck;
690 }
691 connection->responsive = false;
692 // Stop waking up for this unresponsive connection
693 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000694 onAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700695 return LONG_LONG_MIN;
696}
697
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800698std::chrono::nanoseconds InputDispatcher::getDispatchingTimeoutLocked(
699 const sp<Connection>& connection) {
700 if (connection->monitor) {
701 return mMonitorDispatchingTimeout;
702 }
703 const sp<WindowInfoHandle> window =
704 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700705 if (window != nullptr) {
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500706 return window->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700707 }
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500708 return DEFAULT_INPUT_DISPATCHING_TIMEOUT;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700709}
710
Michael Wrightd02c5b62014-02-10 15:10:22 -0800711void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
712 nsecs_t currentTime = now();
713
Jeff Browndc5992e2014-04-11 01:27:26 -0700714 // Reset the key repeat timer whenever normal dispatch is suspended while the
715 // device is in a non-interactive state. This is to ensure that we abort a key
716 // repeat if the device is just coming out of sleep.
717 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800718 resetKeyRepeatLocked();
719 }
720
721 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
722 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +0100723 if (DEBUG_FOCUS) {
724 ALOGD("Dispatch frozen. Waiting some more.");
725 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800726 return;
727 }
728
729 // Optimize latency of app switches.
730 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
731 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
732 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
733 if (mAppSwitchDueTime < *nextWakeupTime) {
734 *nextWakeupTime = mAppSwitchDueTime;
735 }
736
737 // Ready to start a new event.
738 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700739 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700740 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800741 if (isAppSwitchDue) {
742 // The inbound queue is empty so the app switch key we were waiting
743 // for will never arrive. Stop waiting for it.
744 resetPendingAppSwitchLocked(false);
745 isAppSwitchDue = false;
746 }
747
748 // Synthesize a key repeat if appropriate.
749 if (mKeyRepeatState.lastKeyEntry) {
750 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
751 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
752 } else {
753 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
754 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
755 }
756 }
757 }
758
759 // Nothing to do if there is no pending event.
760 if (!mPendingEvent) {
761 return;
762 }
763 } else {
764 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700765 mPendingEvent = mInboundQueue.front();
766 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800767 traceInboundQueueLengthLocked();
768 }
769
770 // Poke user activity for this event.
771 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700772 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800773 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800774 }
775
776 // Now we have an event to dispatch.
777 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700778 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800779 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700780 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800781 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700782 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800783 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700784 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800785 }
786
787 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700788 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800789 }
790
791 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700792 case EventEntry::Type::CONFIGURATION_CHANGED: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700793 const ConfigurationChangedEntry& typedEntry =
794 static_cast<const ConfigurationChangedEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700795 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700796 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700797 break;
798 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800799
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700800 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700801 const DeviceResetEntry& typedEntry =
802 static_cast<const DeviceResetEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700803 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700804 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700805 break;
806 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800807
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100808 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700809 std::shared_ptr<FocusEntry> typedEntry =
810 std::static_pointer_cast<FocusEntry>(mPendingEvent);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100811 dispatchFocusLocked(currentTime, typedEntry);
812 done = true;
813 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
814 break;
815 }
816
Antonio Kantek7242d8b2021-08-05 16:07:20 -0700817 case EventEntry::Type::TOUCH_MODE_CHANGED: {
818 const auto typedEntry = std::static_pointer_cast<TouchModeEntry>(mPendingEvent);
819 dispatchTouchModeChangeLocked(currentTime, typedEntry);
820 done = true;
821 dropReason = DropReason::NOT_DROPPED; // touch mode events are never dropped
822 break;
823 }
824
Prabir Pradhan99987712020-11-10 18:43:05 -0800825 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
826 const auto typedEntry =
827 std::static_pointer_cast<PointerCaptureChangedEntry>(mPendingEvent);
828 dispatchPointerCaptureChangedLocked(currentTime, typedEntry, dropReason);
829 done = true;
830 break;
831 }
832
arthurhungb89ccb02020-12-30 16:19:01 +0800833 case EventEntry::Type::DRAG: {
834 std::shared_ptr<DragEntry> typedEntry =
835 std::static_pointer_cast<DragEntry>(mPendingEvent);
836 dispatchDragLocked(currentTime, typedEntry);
837 done = true;
838 break;
839 }
840
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700841 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700842 std::shared_ptr<KeyEntry> keyEntry = std::static_pointer_cast<KeyEntry>(mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700843 if (isAppSwitchDue) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700844 if (isAppSwitchKeyEvent(*keyEntry)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700845 resetPendingAppSwitchLocked(true);
846 isAppSwitchDue = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700847 } else if (dropReason == DropReason::NOT_DROPPED) {
848 dropReason = DropReason::APP_SWITCH;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700849 }
850 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700851 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *keyEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700852 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700853 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700854 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
855 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700856 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700857 done = dispatchKeyLocked(currentTime, keyEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700858 break;
859 }
860
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700861 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700862 std::shared_ptr<MotionEntry> motionEntry =
863 std::static_pointer_cast<MotionEntry>(mPendingEvent);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700864 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
865 dropReason = DropReason::APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800866 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700867 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *motionEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700868 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700869 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700870 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
871 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700872 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700873 done = dispatchMotionLocked(currentTime, motionEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700874 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800875 }
Chris Yef59a2f42020-10-16 12:55:26 -0700876
877 case EventEntry::Type::SENSOR: {
878 std::shared_ptr<SensorEntry> sensorEntry =
879 std::static_pointer_cast<SensorEntry>(mPendingEvent);
880 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
881 dropReason = DropReason::APP_SWITCH;
882 }
883 // Sensor timestamps use SYSTEM_TIME_BOOTTIME time base, so we can't use
884 // 'currentTime' here, get SYSTEM_TIME_BOOTTIME instead.
885 nsecs_t bootTime = systemTime(SYSTEM_TIME_BOOTTIME);
886 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(bootTime, *sensorEntry)) {
887 dropReason = DropReason::STALE;
888 }
889 dispatchSensorLocked(currentTime, sensorEntry, &dropReason, nextWakeupTime);
890 done = true;
891 break;
892 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800893 }
894
895 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700896 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700897 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800898 }
Michael Wright3a981722015-06-10 15:26:13 +0100899 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800900
901 releasePendingEventLocked();
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700902 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -0800903 }
904}
905
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700906/**
907 * Return true if the events preceding this incoming motion event should be dropped
908 * Return false otherwise (the default behaviour)
909 */
910bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700911 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
Prabir Pradhanaa561d12021-09-24 06:57:33 -0700912 isFromSource(motionEntry.source, AINPUT_SOURCE_CLASS_POINTER);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700913
914 // Optimize case where the current application is unresponsive and the user
915 // decides to touch a window in a different application.
916 // If the application takes too long to catch up then we drop all events preceding
917 // the touch into the other window.
918 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700919 int32_t displayId = motionEntry.displayId;
920 int32_t x = static_cast<int32_t>(
921 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
922 int32_t y = static_cast<int32_t>(
923 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Prabir Pradhand65552b2021-10-07 11:23:50 -0700924
925 const bool isStylus = isPointerFromStylus(motionEntry, 0 /*pointerIndex*/);
chaviw98318de2021-05-19 16:45:23 -0500926 sp<WindowInfoHandle> touchedWindowHandle =
Prabir Pradhand65552b2021-10-07 11:23:50 -0700927 findTouchedWindowAtLocked(displayId, x, y, nullptr, isStylus);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700928 if (touchedWindowHandle != nullptr &&
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700929 touchedWindowHandle->getApplicationToken() !=
930 mAwaitedFocusedApplication->getApplicationToken()) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700931 // User touched a different application than the one we are waiting on.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700932 ALOGI("Pruning input queue because user touched a different application while waiting "
933 "for %s",
934 mAwaitedFocusedApplication->getName().c_str());
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700935 return true;
936 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700937
Prabir Pradhandfabf8a2022-01-21 08:19:30 -0800938 // Alternatively, maybe there's a spy window that could handle this event.
939 const std::vector<sp<WindowInfoHandle>> touchedSpies =
940 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
941 for (const auto& windowHandle : touchedSpies) {
942 const sp<Connection> connection = getConnectionLocked(windowHandle->getToken());
Siarhei Vishniakou34ed4d42020-06-18 00:43:02 +0000943 if (connection != nullptr && connection->responsive) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -0800944 // This spy window could take more input. Drop all events preceding this
945 // event, so that the spy window can get a chance to receive the stream.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700946 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
Prabir Pradhandfabf8a2022-01-21 08:19:30 -0800947 "responsive spy window that may handle the event.",
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700948 mAwaitedFocusedApplication->getName().c_str());
949 return true;
950 }
951 }
952 }
953
954 // Prevent getting stuck: if we have a pending key event, and some motion events that have not
955 // yet been processed by some connections, the dispatcher will wait for these motion
956 // events to be processed before dispatching the key event. This is because these motion events
957 // may cause a new window to be launched, which the user might expect to receive focus.
958 // To prevent waiting forever for such events, just send the key to the currently focused window
959 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
960 ALOGD("Received a new pointer down event, stop waiting for events to process and "
961 "just send the pending key event to the focused window.");
962 mKeyIsWaitingForEventsTimeout = now();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700963 }
964 return false;
965}
966
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700967bool InputDispatcher::enqueueInboundEventLocked(std::unique_ptr<EventEntry> newEntry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700968 bool needWake = mInboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700969 mInboundQueue.push_back(std::move(newEntry));
970 EventEntry& entry = *(mInboundQueue.back());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800971 traceInboundQueueLengthLocked();
972
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700973 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700974 case EventEntry::Type::KEY: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700975 // Optimize app switch latency.
976 // If the application takes too long to catch up then we drop all events preceding
977 // the app switch key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700978 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700979 if (isAppSwitchKeyEvent(keyEntry)) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700980 if (keyEntry.action == AKEY_EVENT_ACTION_DOWN) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700981 mAppSwitchSawKeyDown = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700982 } else if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700983 if (mAppSwitchSawKeyDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000984 if (DEBUG_APP_SWITCH) {
985 ALOGD("App switch is pending!");
986 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700987 mAppSwitchDueTime = keyEntry.eventTime + APP_SWITCH_TIMEOUT;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700988 mAppSwitchSawKeyDown = false;
989 needWake = true;
990 }
991 }
992 }
993 break;
994 }
995
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700996 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700997 if (shouldPruneInboundQueueLocked(static_cast<MotionEntry&>(entry))) {
998 mNextUnblockedEvent = mInboundQueue.back();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700999 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001000 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001001 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001002 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001003 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001004 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
1005 break;
1006 }
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001007 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001008 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08001009 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07001010 case EventEntry::Type::SENSOR:
arthurhungb89ccb02020-12-30 16:19:01 +08001011 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1012 case EventEntry::Type::DRAG: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001013 // nothing to do
1014 break;
1015 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001016 }
1017
1018 return needWake;
1019}
1020
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001021void InputDispatcher::addRecentEventLocked(std::shared_ptr<EventEntry> entry) {
Chris Yef59a2f42020-10-16 12:55:26 -07001022 // Do not store sensor event in recent queue to avoid flooding the queue.
1023 if (entry->type != EventEntry::Type::SENSOR) {
1024 mRecentQueue.push_back(entry);
1025 }
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001026 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001027 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001028 }
1029}
1030
chaviw98318de2021-05-19 16:45:23 -05001031sp<WindowInfoHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, int32_t x,
1032 int32_t y, TouchState* touchState,
Prabir Pradhand65552b2021-10-07 11:23:50 -07001033 bool isStylus,
chaviw98318de2021-05-19 16:45:23 -05001034 bool addOutsideTargets,
1035 bool ignoreDragWindow) {
Siarhei Vishniakou64452932020-11-06 17:51:32 -06001036 if (addOutsideTargets && touchState == nullptr) {
1037 LOG_ALWAYS_FATAL("Must provide a valid touch state if adding outside targets");
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001038 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001039 // Traverse windows from front to back to find touched window.
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001040 const auto& windowHandles = getWindowHandlesLocked(displayId);
chaviw98318de2021-05-19 16:45:23 -05001041 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
arthurhung6d4bed92021-03-17 11:59:33 +08001042 if (ignoreDragWindow && haveSameToken(windowHandle, mDragState->dragWindow)) {
arthurhungb89ccb02020-12-30 16:19:01 +08001043 continue;
1044 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001045
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001046 const WindowInfo& info = *windowHandle->getInfo();
Prabir Pradhand65552b2021-10-07 11:23:50 -07001047 if (!info.isSpy() && windowAcceptsTouchAt(info, displayId, x, y, isStylus)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001048 return windowHandle;
1049 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001050
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001051 if (addOutsideTargets &&
1052 info.inputConfig.test(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001053 touchState->addOrUpdateWindow(windowHandle, InputTarget::FLAG_DISPATCH_AS_OUTSIDE,
1054 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001055 }
1056 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001057 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001058}
1059
Prabir Pradhand65552b2021-10-07 11:23:50 -07001060std::vector<sp<WindowInfoHandle>> InputDispatcher::findTouchedSpyWindowsAtLocked(
1061 int32_t displayId, int32_t x, int32_t y, bool isStylus) const {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001062 // Traverse windows from front to back and gather the touched spy windows.
1063 std::vector<sp<WindowInfoHandle>> spyWindows;
1064 const auto& windowHandles = getWindowHandlesLocked(displayId);
1065 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
1066 const WindowInfo& info = *windowHandle->getInfo();
1067
Prabir Pradhand65552b2021-10-07 11:23:50 -07001068 if (!windowAcceptsTouchAt(info, displayId, x, y, isStylus)) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001069 continue;
1070 }
1071 if (!info.isSpy()) {
1072 // The first touched non-spy window was found, so return the spy windows touched so far.
1073 return spyWindows;
1074 }
1075 spyWindows.push_back(windowHandle);
1076 }
1077 return spyWindows;
1078}
1079
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001080void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001081 const char* reason;
1082 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001083 case DropReason::POLICY:
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001084 if (DEBUG_INBOUND_EVENT_DETAILS) {
1085 ALOGD("Dropped event because policy consumed it.");
1086 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001087 reason = "inbound event was dropped because the policy consumed it";
1088 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001089 case DropReason::DISABLED:
1090 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001091 ALOGI("Dropped event because input dispatch is disabled.");
1092 }
1093 reason = "inbound event was dropped because input dispatch is disabled";
1094 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001095 case DropReason::APP_SWITCH:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001096 ALOGI("Dropped event because of pending overdue app switch.");
1097 reason = "inbound event was dropped because of pending overdue app switch";
1098 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001099 case DropReason::BLOCKED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001100 ALOGI("Dropped event because the current application is not responding and the user "
1101 "has started interacting with a different application.");
1102 reason = "inbound event was dropped because the current application is not responding "
1103 "and the user has started interacting with a different application";
1104 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001105 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001106 ALOGI("Dropped event because it is stale.");
1107 reason = "inbound event was dropped because it is stale";
1108 break;
Prabir Pradhan99987712020-11-10 18:43:05 -08001109 case DropReason::NO_POINTER_CAPTURE:
1110 ALOGI("Dropped event because there is no window with Pointer Capture.");
1111 reason = "inbound event was dropped because there is no window with Pointer Capture";
1112 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001113 case DropReason::NOT_DROPPED: {
1114 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001115 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001116 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001117 }
1118
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001119 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001120 case EventEntry::Type::KEY: {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001121 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
1122 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001123 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001124 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001125 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001126 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1127 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001128 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
1129 synthesizeCancelationEventsForAllConnectionsLocked(options);
1130 } else {
1131 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
1132 synthesizeCancelationEventsForAllConnectionsLocked(options);
1133 }
1134 break;
1135 }
Chris Yef59a2f42020-10-16 12:55:26 -07001136 case EventEntry::Type::SENSOR: {
1137 break;
1138 }
arthurhungb89ccb02020-12-30 16:19:01 +08001139 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1140 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08001141 break;
1142 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001143 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001144 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001145 case EventEntry::Type::CONFIGURATION_CHANGED:
1146 case EventEntry::Type::DEVICE_RESET: {
Dominik Laskowski75788452021-02-09 18:51:25 -08001147 LOG_ALWAYS_FATAL("Should not drop %s events", ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001148 break;
1149 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001150 }
1151}
1152
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001153static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001154 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
1155 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001156}
1157
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001158bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
1159 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
1160 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
1161 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001162}
1163
1164bool InputDispatcher::isAppSwitchPendingLocked() {
1165 return mAppSwitchDueTime != LONG_LONG_MAX;
1166}
1167
1168void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
1169 mAppSwitchDueTime = LONG_LONG_MAX;
1170
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001171 if (DEBUG_APP_SWITCH) {
1172 if (handled) {
1173 ALOGD("App switch has arrived.");
1174 } else {
1175 ALOGD("App switch was abandoned.");
1176 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001177 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001178}
1179
Michael Wrightd02c5b62014-02-10 15:10:22 -08001180bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001181 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001182}
1183
Prabir Pradhancef936d2021-07-21 16:17:52 +00001184bool InputDispatcher::runCommandsLockedInterruptable() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001185 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001186 return false;
1187 }
1188
1189 do {
Prabir Pradhancef936d2021-07-21 16:17:52 +00001190 auto command = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001191 mCommandQueue.pop_front();
Prabir Pradhancef936d2021-07-21 16:17:52 +00001192 // Commands are run with the lock held, but may release and re-acquire the lock from within.
1193 command();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001194 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001195 return true;
1196}
1197
Prabir Pradhancef936d2021-07-21 16:17:52 +00001198void InputDispatcher::postCommandLocked(Command&& command) {
1199 mCommandQueue.push_back(command);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001200}
1201
1202void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001203 while (!mInboundQueue.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001204 std::shared_ptr<EventEntry> entry = mInboundQueue.front();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001205 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001206 releaseInboundEventLocked(entry);
1207 }
1208 traceInboundQueueLengthLocked();
1209}
1210
1211void InputDispatcher::releasePendingEventLocked() {
1212 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001213 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -07001214 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001215 }
1216}
1217
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001218void InputDispatcher::releaseInboundEventLocked(std::shared_ptr<EventEntry> entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001219 InjectionState* injectionState = entry->injectionState;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001220 if (injectionState && injectionState->injectionResult == InputEventInjectionResult::PENDING) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001221 if (DEBUG_DISPATCH_CYCLE) {
1222 ALOGD("Injected inbound event was dropped.");
1223 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001224 setInjectionResult(*entry, InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001225 }
1226 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001227 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001228 }
1229 addRecentEventLocked(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001230}
1231
1232void InputDispatcher::resetKeyRepeatLocked() {
1233 if (mKeyRepeatState.lastKeyEntry) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001234 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001235 }
1236}
1237
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001238std::shared_ptr<KeyEntry> InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
1239 std::shared_ptr<KeyEntry> entry = mKeyRepeatState.lastKeyEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001240
Michael Wright2e732952014-09-24 13:26:59 -07001241 uint32_t policyFlags = entry->policyFlags &
1242 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001243
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001244 std::shared_ptr<KeyEntry> newEntry =
1245 std::make_unique<KeyEntry>(mIdGenerator.nextId(), currentTime, entry->deviceId,
1246 entry->source, entry->displayId, policyFlags, entry->action,
1247 entry->flags, entry->keyCode, entry->scanCode,
1248 entry->metaState, entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001249
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001250 newEntry->syntheticRepeat = true;
1251 mKeyRepeatState.lastKeyEntry = newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001252 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001253 return newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001254}
1255
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001256bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001257 const ConfigurationChangedEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001258 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1259 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry.eventTime);
1260 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001261
1262 // Reset key repeating in case a keyboard device was added or removed or something.
1263 resetKeyRepeatLocked();
1264
1265 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Prabir Pradhancef936d2021-07-21 16:17:52 +00001266 auto command = [this, eventTime = entry.eventTime]() REQUIRES(mLock) {
1267 scoped_unlock unlock(mLock);
1268 mPolicy->notifyConfigurationChanged(eventTime);
1269 };
1270 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001271 return true;
1272}
1273
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001274bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime,
1275 const DeviceResetEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001276 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1277 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry.eventTime,
1278 entry.deviceId);
1279 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001280
liushenxiang42232912021-05-21 20:24:09 +08001281 // Reset key repeating in case a keyboard device was disabled or enabled.
1282 if (mKeyRepeatState.lastKeyEntry && mKeyRepeatState.lastKeyEntry->deviceId == entry.deviceId) {
1283 resetKeyRepeatLocked();
1284 }
1285
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001286 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, "device was reset");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001287 options.deviceId = entry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001288 synthesizeCancelationEventsForAllConnectionsLocked(options);
1289 return true;
1290}
1291
Vishnu Nairad321cd2020-08-20 16:40:21 -07001292void InputDispatcher::enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus,
Vishnu Nairc519ff72021-01-21 08:23:08 -08001293 const std::string& reason) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001294 if (mPendingEvent != nullptr) {
1295 // Move the pending event to the front of the queue. This will give the chance
1296 // for the pending event to get dispatched to the newly focused window
1297 mInboundQueue.push_front(mPendingEvent);
1298 mPendingEvent = nullptr;
1299 }
1300
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001301 std::unique_ptr<FocusEntry> focusEntry =
1302 std::make_unique<FocusEntry>(mIdGenerator.nextId(), now(), windowToken, hasFocus,
1303 reason);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001304
1305 // This event should go to the front of the queue, but behind all other focus events
1306 // Find the last focus event, and insert right after it
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001307 std::deque<std::shared_ptr<EventEntry>>::reverse_iterator it =
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001308 std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001309 [](const std::shared_ptr<EventEntry>& event) {
1310 return event->type == EventEntry::Type::FOCUS;
1311 });
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001312
1313 // Maintain the order of focus events. Insert the entry after all other focus events.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001314 mInboundQueue.insert(it.base(), std::move(focusEntry));
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001315}
1316
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001317void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime, std::shared_ptr<FocusEntry> entry) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05001318 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001319 if (channel == nullptr) {
1320 return; // Window has gone away
1321 }
1322 InputTarget target;
1323 target.inputChannel = channel;
1324 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1325 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001326 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
1327 channel->getName();
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001328 std::string reason = std::string("reason=").append(entry->reason);
1329 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001330 dispatchEventLocked(currentTime, entry, {target});
1331}
1332
Prabir Pradhan99987712020-11-10 18:43:05 -08001333void InputDispatcher::dispatchPointerCaptureChangedLocked(
1334 nsecs_t currentTime, const std::shared_ptr<PointerCaptureChangedEntry>& entry,
1335 DropReason& dropReason) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001336 dropReason = DropReason::NOT_DROPPED;
1337
Prabir Pradhan99987712020-11-10 18:43:05 -08001338 const bool haveWindowWithPointerCapture = mWindowTokenWithPointerCapture != nullptr;
Prabir Pradhan99987712020-11-10 18:43:05 -08001339 sp<IBinder> token;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001340
1341 if (entry->pointerCaptureRequest.enable) {
1342 // Enable Pointer Capture.
1343 if (haveWindowWithPointerCapture &&
1344 (entry->pointerCaptureRequest == mCurrentPointerCaptureRequest)) {
1345 LOG_ALWAYS_FATAL("This request to enable Pointer Capture has already been dispatched "
1346 "to the window.");
1347 }
1348 if (!mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08001349 // This can happen if a window requests capture and immediately releases capture.
1350 ALOGW("No window requested Pointer Capture.");
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001351 dropReason = DropReason::NO_POINTER_CAPTURE;
Prabir Pradhan99987712020-11-10 18:43:05 -08001352 return;
1353 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001354 if (entry->pointerCaptureRequest.seq != mCurrentPointerCaptureRequest.seq) {
1355 ALOGI("Skipping dispatch of Pointer Capture being enabled: sequence number mismatch.");
1356 return;
1357 }
1358
Vishnu Nairc519ff72021-01-21 08:23:08 -08001359 token = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08001360 LOG_ALWAYS_FATAL_IF(!token, "Cannot find focused window for Pointer Capture.");
1361 mWindowTokenWithPointerCapture = token;
1362 } else {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001363 // Disable Pointer Capture.
1364 // We do not check if the sequence number matches for requests to disable Pointer Capture
1365 // for two reasons:
1366 // 1. Pointer Capture can be disabled by a focus change, which means we can get two entries
1367 // to disable capture with the same sequence number: one generated by
1368 // disablePointerCaptureForcedLocked() and another as an acknowledgement of Pointer
1369 // Capture being disabled in InputReader.
1370 // 2. We respect any request to disable Pointer Capture generated by InputReader, since the
1371 // actual Pointer Capture state that affects events being generated by input devices is
1372 // in InputReader.
1373 if (!haveWindowWithPointerCapture) {
1374 // Pointer capture was already forcefully disabled because of focus change.
1375 dropReason = DropReason::NOT_DROPPED;
1376 return;
1377 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001378 token = mWindowTokenWithPointerCapture;
1379 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001380 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001381 setPointerCaptureLocked(false);
1382 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001383 }
1384
1385 auto channel = getInputChannelLocked(token);
1386 if (channel == nullptr) {
1387 // Window has gone away, clean up Pointer Capture state.
1388 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001389 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001390 setPointerCaptureLocked(false);
1391 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001392 return;
1393 }
1394 InputTarget target;
1395 target.inputChannel = channel;
1396 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1397 entry->dispatchInProgress = true;
1398 dispatchEventLocked(currentTime, entry, {target});
1399
1400 dropReason = DropReason::NOT_DROPPED;
1401}
1402
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001403void InputDispatcher::dispatchTouchModeChangeLocked(nsecs_t currentTime,
1404 const std::shared_ptr<TouchModeEntry>& entry) {
1405 const std::vector<sp<WindowInfoHandle>>& windowHandles =
1406 getWindowHandlesLocked(mFocusedDisplayId);
1407 if (windowHandles.empty()) {
1408 return;
1409 }
1410 const std::vector<InputTarget> inputTargets =
1411 getInputTargetsFromWindowHandlesLocked(windowHandles);
1412 if (inputTargets.empty()) {
1413 return;
1414 }
1415 entry->dispatchInProgress = true;
1416 dispatchEventLocked(currentTime, entry, inputTargets);
1417}
1418
1419std::vector<InputTarget> InputDispatcher::getInputTargetsFromWindowHandlesLocked(
1420 const std::vector<sp<WindowInfoHandle>>& windowHandles) const {
1421 std::vector<InputTarget> inputTargets;
1422 for (const sp<WindowInfoHandle>& handle : windowHandles) {
1423 // TODO(b/193718270): Due to performance concerns, consider notifying visible windows only.
1424 const sp<IBinder>& token = handle->getToken();
1425 if (token == nullptr) {
1426 continue;
1427 }
1428 std::shared_ptr<InputChannel> channel = getInputChannelLocked(token);
1429 if (channel == nullptr) {
1430 continue; // Window has gone away
1431 }
1432 InputTarget target;
1433 target.inputChannel = channel;
1434 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1435 inputTargets.push_back(target);
1436 }
1437 return inputTargets;
1438}
1439
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001440bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, std::shared_ptr<KeyEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001441 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001442 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001443 if (!entry->dispatchInProgress) {
1444 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1445 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1446 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1447 if (mKeyRepeatState.lastKeyEntry &&
Chris Ye2ad95392020-09-01 13:44:44 -07001448 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode &&
Michael Wrightd02c5b62014-02-10 15:10:22 -08001449 // We have seen two identical key downs in a row which indicates that the device
1450 // driver is automatically generating key repeats itself. We take note of the
1451 // repeat here, but we disable our own next key repeat timer since it is clear that
1452 // we will not need to synthesize key repeats ourselves.
Chris Ye2ad95392020-09-01 13:44:44 -07001453 mKeyRepeatState.lastKeyEntry->deviceId == entry->deviceId) {
1454 // Make sure we don't get key down from a different device. If a different
1455 // device Id has same key pressed down, the new device Id will replace the
1456 // current one to hold the key repeat with repeat count reset.
1457 // In the future when got a KEY_UP on the device id, drop it and do not
1458 // stop the key repeat on current device.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001459 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1460 resetKeyRepeatLocked();
1461 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
1462 } else {
1463 // Not a repeat. Save key down state in case we do see a repeat later.
1464 resetKeyRepeatLocked();
1465 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1466 }
1467 mKeyRepeatState.lastKeyEntry = entry;
Chris Ye2ad95392020-09-01 13:44:44 -07001468 } else if (entry->action == AKEY_EVENT_ACTION_UP && mKeyRepeatState.lastKeyEntry &&
1469 mKeyRepeatState.lastKeyEntry->deviceId != entry->deviceId) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001470 // The key on device 'deviceId' is still down, do not stop key repeat
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001471 if (DEBUG_INBOUND_EVENT_DETAILS) {
1472 ALOGD("deviceId=%d got KEY_UP as stale", entry->deviceId);
1473 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001474 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001475 resetKeyRepeatLocked();
1476 }
1477
1478 if (entry->repeatCount == 1) {
1479 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1480 } else {
1481 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1482 }
1483
1484 entry->dispatchInProgress = true;
1485
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001486 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001487 }
1488
1489 // Handle case where the policy asked us to try again later last time.
1490 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
1491 if (currentTime < entry->interceptKeyWakeupTime) {
1492 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1493 *nextWakeupTime = entry->interceptKeyWakeupTime;
1494 }
1495 return false; // wait until next wakeup
1496 }
1497 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
1498 entry->interceptKeyWakeupTime = 0;
1499 }
1500
1501 // Give the policy a chance to intercept the key.
1502 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
1503 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07001504 sp<IBinder> focusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08001505 mFocusResolver.getFocusedWindowToken(getTargetDisplayId(*entry));
Prabir Pradhancef936d2021-07-21 16:17:52 +00001506
1507 auto command = [this, focusedWindowToken, entry]() REQUIRES(mLock) {
1508 doInterceptKeyBeforeDispatchingCommand(focusedWindowToken, *entry);
1509 };
1510 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001511 return false; // wait for the command to run
1512 } else {
1513 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
1514 }
1515 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001516 if (*dropReason == DropReason::NOT_DROPPED) {
1517 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001518 }
1519 }
1520
1521 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001522 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001523 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001524 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1525 : InputEventInjectionResult::FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001526 mReporter->reportDroppedKey(entry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001527 return true;
1528 }
1529
1530 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001531 std::vector<InputTarget> inputTargets;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001532 InputEventInjectionResult injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001533 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001534 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001535 return false;
1536 }
1537
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001538 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001539 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001540 return true;
1541 }
1542
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001543 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001544 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001545
1546 // Dispatch the key.
1547 dispatchEventLocked(currentTime, entry, inputTargets);
1548 return true;
1549}
1550
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001551void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001552 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1553 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
1554 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1555 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
1556 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId,
1557 entry.policyFlags, entry.action, entry.flags, entry.keyCode, entry.scanCode,
1558 entry.metaState, entry.repeatCount, entry.downTime);
1559 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001560}
1561
Prabir Pradhancef936d2021-07-21 16:17:52 +00001562void InputDispatcher::dispatchSensorLocked(nsecs_t currentTime,
1563 const std::shared_ptr<SensorEntry>& entry,
Chris Yef59a2f42020-10-16 12:55:26 -07001564 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001565 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1566 ALOGD("notifySensorEvent eventTime=%" PRId64 ", hwTimestamp=%" PRId64 ", deviceId=%d, "
1567 "source=0x%x, sensorType=%s",
1568 entry->eventTime, entry->hwTimestamp, entry->deviceId, entry->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08001569 ftl::enum_string(entry->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001570 }
Prabir Pradhancef936d2021-07-21 16:17:52 +00001571 auto command = [this, entry]() REQUIRES(mLock) {
1572 scoped_unlock unlock(mLock);
1573
1574 if (entry->accuracyChanged) {
1575 mPolicy->notifySensorAccuracy(entry->deviceId, entry->sensorType, entry->accuracy);
1576 }
1577 mPolicy->notifySensorEvent(entry->deviceId, entry->sensorType, entry->accuracy,
1578 entry->hwTimestamp, entry->values);
1579 };
1580 postCommandLocked(std::move(command));
Chris Yef59a2f42020-10-16 12:55:26 -07001581}
1582
1583bool InputDispatcher::flushSensor(int deviceId, InputDeviceSensorType sensorType) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001584 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1585 ALOGD("flushSensor deviceId=%d, sensorType=%s", deviceId,
Dominik Laskowski75788452021-02-09 18:51:25 -08001586 ftl::enum_string(sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001587 }
Chris Yef59a2f42020-10-16 12:55:26 -07001588 { // acquire lock
1589 std::scoped_lock _l(mLock);
1590
1591 for (auto it = mInboundQueue.begin(); it != mInboundQueue.end(); it++) {
1592 std::shared_ptr<EventEntry> entry = *it;
1593 if (entry->type == EventEntry::Type::SENSOR) {
1594 it = mInboundQueue.erase(it);
1595 releaseInboundEventLocked(entry);
1596 }
1597 }
1598 }
1599 return true;
1600}
1601
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001602bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, std::shared_ptr<MotionEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001603 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001604 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001605 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001606 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001607 entry->dispatchInProgress = true;
1608
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001609 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001610 }
1611
1612 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001613 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001614 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001615 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1616 : InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001617 return true;
1618 }
1619
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001620 const bool isPointerEvent = isFromSource(entry->source, AINPUT_SOURCE_CLASS_POINTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001621
1622 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001623 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001624
1625 bool conflictingPointerActions = false;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001626 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001627 if (isPointerEvent) {
1628 // Pointer event. (eg. touchscreen)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001629 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001630 findTouchedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001631 &conflictingPointerActions);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001632 } else {
1633 // Non touch event. (eg. trackball)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001634 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001635 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001636 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001637 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001638 return false;
1639 }
1640
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001641 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001642 if (injectionResult == InputEventInjectionResult::PERMISSION_DENIED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001643 ALOGW("Permission denied, dropping the motion (isPointer=%s)", toString(isPointerEvent));
1644 return true;
1645 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001646 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001647 CancelationOptions::Mode mode(isPointerEvent
1648 ? CancelationOptions::CANCEL_POINTER_EVENTS
1649 : CancelationOptions::CANCEL_NON_POINTER_EVENTS);
1650 CancelationOptions options(mode, "input event injection failed");
1651 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001652 return true;
1653 }
1654
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001655 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001656 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001657
1658 // Dispatch the motion.
1659 if (conflictingPointerActions) {
1660 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001661 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001662 synthesizeCancelationEventsForAllConnectionsLocked(options);
1663 }
1664 dispatchEventLocked(currentTime, entry, inputTargets);
1665 return true;
1666}
1667
chaviw98318de2021-05-19 16:45:23 -05001668void InputDispatcher::enqueueDragEventLocked(const sp<WindowInfoHandle>& windowHandle,
arthurhungb89ccb02020-12-30 16:19:01 +08001669 bool isExiting, const MotionEntry& motionEntry) {
1670 // If the window needs enqueue a drag event, the pointerCount should be 1 and the action should
1671 // be AMOTION_EVENT_ACTION_MOVE, that could guarantee the first pointer is always valid.
1672 LOG_ALWAYS_FATAL_IF(motionEntry.pointerCount != 1);
1673 PointerCoords pointerCoords;
1674 pointerCoords.copyFrom(motionEntry.pointerCoords[0]);
1675 pointerCoords.transform(windowHandle->getInfo()->transform);
1676
1677 std::unique_ptr<DragEntry> dragEntry =
1678 std::make_unique<DragEntry>(mIdGenerator.nextId(), motionEntry.eventTime,
1679 windowHandle->getToken(), isExiting, pointerCoords.getX(),
1680 pointerCoords.getY());
1681
1682 enqueueInboundEventLocked(std::move(dragEntry));
1683}
1684
1685void InputDispatcher::dispatchDragLocked(nsecs_t currentTime, std::shared_ptr<DragEntry> entry) {
1686 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
1687 if (channel == nullptr) {
1688 return; // Window has gone away
1689 }
1690 InputTarget target;
1691 target.inputChannel = channel;
1692 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1693 entry->dispatchInProgress = true;
1694 dispatchEventLocked(currentTime, entry, {target});
1695}
1696
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001697void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001698 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1699 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
1700 ", policyFlags=0x%x, "
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001701 "action=%s, actionButton=0x%x, flags=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001702 "metaState=0x%x, buttonState=0x%x,"
1703 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
1704 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId,
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001705 entry.policyFlags, MotionEvent::actionToString(entry.action).c_str(),
1706 entry.actionButton, entry.flags, entry.metaState, entry.buttonState, entry.edgeFlags,
1707 entry.xPrecision, entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001708
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001709 for (uint32_t i = 0; i < entry.pointerCount; i++) {
1710 ALOGD(" Pointer %d: id=%d, toolType=%d, "
1711 "x=%f, y=%f, pressure=%f, size=%f, "
1712 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1713 "orientation=%f",
1714 i, entry.pointerProperties[i].id, entry.pointerProperties[i].toolType,
1715 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1716 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1717 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1718 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1719 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1720 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1721 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1722 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1723 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
1724 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001725 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001726}
1727
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001728void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
1729 std::shared_ptr<EventEntry> eventEntry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001730 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001731 ATRACE_CALL();
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001732 if (DEBUG_DISPATCH_CYCLE) {
1733 ALOGD("dispatchEventToCurrentInputTargets");
1734 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001735
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001736 updateInteractionTokensLocked(*eventEntry, inputTargets);
1737
Michael Wrightd02c5b62014-02-10 15:10:22 -08001738 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1739
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001740 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001741
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001742 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001743 sp<Connection> connection =
1744 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001745 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08001746 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001747 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001748 if (DEBUG_FOCUS) {
1749 ALOGD("Dropping event delivery to target with channel '%s' because it "
1750 "is no longer registered with the input dispatcher.",
1751 inputTarget.inputChannel->getName().c_str());
1752 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001753 }
1754 }
1755}
1756
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001757void InputDispatcher::cancelEventsForAnrLocked(const sp<Connection>& connection) {
1758 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
1759 // If the policy decides to close the app, we will get a channel removal event via
1760 // unregisterInputChannel, and will clean up the connection that way. We are already not
1761 // sending new pointers to the connection when it blocked, but focused events will continue to
1762 // pile up.
1763 ALOGW("Canceling events for %s because it is unresponsive",
1764 connection->inputChannel->getName().c_str());
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08001765 if (connection->status == Connection::Status::NORMAL) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001766 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1767 "application not responding");
1768 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001769 }
1770}
1771
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001772void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001773 if (DEBUG_FOCUS) {
1774 ALOGD("Resetting ANR timeouts.");
1775 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001776
1777 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001778 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07001779 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001780}
1781
Tiger Huang721e26f2018-07-24 22:26:19 +08001782/**
1783 * Get the display id that the given event should go to. If this event specifies a valid display id,
1784 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1785 * Focused display is the display that the user most recently interacted with.
1786 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001787int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001788 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001789 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001790 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001791 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1792 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001793 break;
1794 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001795 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001796 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1797 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001798 break;
1799 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00001800 case EventEntry::Type::TOUCH_MODE_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08001801 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001802 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001803 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07001804 case EventEntry::Type::DEVICE_RESET:
arthurhungb89ccb02020-12-30 16:19:01 +08001805 case EventEntry::Type::SENSOR:
1806 case EventEntry::Type::DRAG: {
Dominik Laskowski75788452021-02-09 18:51:25 -08001807 ALOGE("%s events do not have a target display", ftl::enum_string(entry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001808 return ADISPLAY_ID_NONE;
1809 }
Tiger Huang721e26f2018-07-24 22:26:19 +08001810 }
1811 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1812}
1813
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001814bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
1815 const char* focusedWindowName) {
1816 if (mAnrTracker.empty()) {
1817 // already processed all events that we waited for
1818 mKeyIsWaitingForEventsTimeout = std::nullopt;
1819 return false;
1820 }
1821
1822 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
1823 // Start the timer
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00001824 // Wait to send key because there are unprocessed events that may cause focus to change
Siarhei Vishniakou70622952020-07-30 11:17:23 -05001825 mKeyIsWaitingForEventsTimeout = currentTime +
1826 std::chrono::duration_cast<std::chrono::nanoseconds>(KEY_WAITING_FOR_EVENTS_TIMEOUT)
1827 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001828 return true;
1829 }
1830
1831 // We still have pending events, and already started the timer
1832 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
1833 return true; // Still waiting
1834 }
1835
1836 // Waited too long, and some connection still hasn't processed all motions
1837 // Just send the key to the focused window
1838 ALOGW("Dispatching key to %s even though there are other unprocessed events",
1839 focusedWindowName);
1840 mKeyIsWaitingForEventsTimeout = std::nullopt;
1841 return false;
1842}
1843
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001844InputEventInjectionResult InputDispatcher::findFocusedWindowTargetsLocked(
1845 nsecs_t currentTime, const EventEntry& entry, std::vector<InputTarget>& inputTargets,
1846 nsecs_t* nextWakeupTime) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001847 std::string reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001848
Tiger Huang721e26f2018-07-24 22:26:19 +08001849 int32_t displayId = getTargetDisplayId(entry);
chaviw98318de2021-05-19 16:45:23 -05001850 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07001851 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08001852 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1853
Michael Wrightd02c5b62014-02-10 15:10:22 -08001854 // If there is no currently focused window and no focused application
1855 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001856 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
1857 ALOGI("Dropping %s event because there is no focused window or focused application in "
1858 "display %" PRId32 ".",
Dominik Laskowski75788452021-02-09 18:51:25 -08001859 ftl::enum_string(entry.type).c_str(), displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001860 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001861 }
1862
Vishnu Nair062a8672021-09-03 16:07:44 -07001863 // Drop key events if requested by input feature
1864 if (focusedWindowHandle != nullptr && shouldDropInput(entry, focusedWindowHandle)) {
1865 return InputEventInjectionResult::FAILED;
1866 }
1867
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001868 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
1869 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
1870 // start interacting with another application via touch (app switch). This code can be removed
1871 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
1872 // an app is expected to have a focused window.
1873 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
1874 if (!mNoFocusedWindowTimeoutTime.has_value()) {
1875 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001876 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
1877 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
1878 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001879 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05001880 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001881 ALOGW("Waiting because no window has focus but %s may eventually add a "
1882 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001883 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001884 *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001885 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001886 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
1887 // Already raised ANR. Drop the event
1888 ALOGE("Dropping %s event because there is no focused window",
Dominik Laskowski75788452021-02-09 18:51:25 -08001889 ftl::enum_string(entry.type).c_str());
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001890 return InputEventInjectionResult::FAILED;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001891 } else {
1892 // Still waiting for the focused window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001893 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001894 }
1895 }
1896
1897 // we have a valid, non-null focused window
1898 resetNoFocusedWindowTimeoutLocked();
1899
Michael Wrightd02c5b62014-02-10 15:10:22 -08001900 // Check permissions.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001901 if (!checkInjectionPermission(focusedWindowHandle, entry.injectionState)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001902 return InputEventInjectionResult::PERMISSION_DENIED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001903 }
1904
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001905 if (focusedWindowHandle->getInfo()->inputConfig.test(
1906 WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001907 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001908 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001909 }
1910
1911 // If the event is a key event, then we must wait for all previous events to
1912 // complete before delivering it because previous events may have the
1913 // side-effect of transferring focus to a different window and we want to
1914 // ensure that the following keys are sent to the new window.
1915 //
1916 // Suppose the user touches a button in a window then immediately presses "A".
1917 // If the button causes a pop-up window to appear then we want to ensure that
1918 // the "A" key is delivered to the new pop-up window. This is because users
1919 // often anticipate pending UI changes when typing on a keyboard.
1920 // To obtain this behavior, we must serialize key events with respect to all
1921 // prior input events.
1922 if (entry.type == EventEntry::Type::KEY) {
1923 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
1924 *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001925 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001926 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001927 }
1928
1929 // Success! Output targets.
Tiger Huang721e26f2018-07-24 22:26:19 +08001930 addWindowTargetLocked(focusedWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001931 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS,
1932 BitSet32(0), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001933
1934 // Done.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001935 return InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001936}
1937
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001938/**
1939 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
1940 * that are currently unresponsive.
1941 */
Prabir Pradhan0a99c922021-09-03 08:27:53 -07001942std::vector<Monitor> InputDispatcher::selectResponsiveMonitorsLocked(
1943 const std::vector<Monitor>& monitors) const {
1944 std::vector<Monitor> responsiveMonitors;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001945 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
Prabir Pradhan0a99c922021-09-03 08:27:53 -07001946 [this](const Monitor& monitor) REQUIRES(mLock) {
1947 sp<Connection> connection =
1948 getConnectionLocked(monitor.inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001949 if (connection == nullptr) {
1950 ALOGE("Could not find connection for monitor %s",
Prabir Pradhan0a99c922021-09-03 08:27:53 -07001951 monitor.inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001952 return false;
1953 }
1954 if (!connection->responsive) {
1955 ALOGW("Unresponsive monitor %s will not get the new gesture",
1956 connection->inputChannel->getName().c_str());
1957 return false;
1958 }
1959 return true;
1960 });
1961 return responsiveMonitors;
1962}
1963
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001964InputEventInjectionResult InputDispatcher::findTouchedWindowTargetsLocked(
1965 nsecs_t currentTime, const MotionEntry& entry, std::vector<InputTarget>& inputTargets,
1966 nsecs_t* nextWakeupTime, bool* outConflictingPointerActions) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001967 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001968 enum InjectionPermission {
1969 INJECTION_PERMISSION_UNKNOWN,
1970 INJECTION_PERMISSION_GRANTED,
1971 INJECTION_PERMISSION_DENIED
1972 };
1973
Michael Wrightd02c5b62014-02-10 15:10:22 -08001974 // For security reasons, we defer updating the touch state until we are sure that
1975 // event injection will be allowed.
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001976 const int32_t displayId = entry.displayId;
1977 const int32_t action = entry.action;
1978 const int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001979
1980 // Update the touch state as needed based on the properties of the touch event.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001981 InputEventInjectionResult injectionResult = InputEventInjectionResult::PENDING;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001982 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
chaviw98318de2021-05-19 16:45:23 -05001983 sp<WindowInfoHandle> newHoverWindowHandle(mLastHoverWindowHandle);
1984 sp<WindowInfoHandle> newTouchedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001985
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001986 // Copy current touch state into tempTouchState.
1987 // This state will be used to update mTouchStatesByDisplay at the end of this function.
1988 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07001989 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001990 TouchState tempTouchState;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001991 if (const auto it = mTouchStatesByDisplay.find(displayId); it != mTouchStatesByDisplay.end()) {
1992 oldState = &(it->second);
Prabir Pradhane680f9b2022-02-04 04:24:00 -08001993 tempTouchState = *oldState;
Jeff Brownf086ddb2014-02-11 14:28:48 -08001994 }
1995
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001996 bool isSplit = tempTouchState.split;
1997 bool switchedDevice = tempTouchState.deviceId >= 0 && tempTouchState.displayId >= 0 &&
1998 (tempTouchState.deviceId != entry.deviceId || tempTouchState.source != entry.source ||
1999 tempTouchState.displayId != displayId);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002000
2001 const bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
2002 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2003 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
2004 const bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN ||
2005 maskedAction == AMOTION_EVENT_ACTION_SCROLL || isHoverAction);
Prabir Pradhanaa561d12021-09-24 06:57:33 -07002006 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002007 bool wrongDevice = false;
2008 if (newGesture) {
2009 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002010 if (switchedDevice && tempTouchState.down && !down && !isHoverAction) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002011 ALOGI("Dropping event because a pointer for a different device is already down "
2012 "in display %" PRId32,
2013 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002014 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002015 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002016 switchedDevice = false;
2017 wrongDevice = true;
2018 goto Failed;
2019 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002020 tempTouchState.reset();
2021 tempTouchState.down = down;
2022 tempTouchState.deviceId = entry.deviceId;
2023 tempTouchState.source = entry.source;
2024 tempTouchState.displayId = displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002025 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002026 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002027 ALOGI("Dropping move event because a pointer for a different device is already active "
2028 "in display %" PRId32,
2029 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002030 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002031 injectionResult = InputEventInjectionResult::PERMISSION_DENIED;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002032 switchedDevice = false;
2033 wrongDevice = true;
2034 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002035 }
2036
2037 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
2038 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
2039
Garfield Tan00f511d2019-06-12 16:55:40 -07002040 int32_t x;
2041 int32_t y;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002042 const int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Garfield Tan00f511d2019-06-12 16:55:40 -07002043 // Always dispatch mouse events to cursor position.
2044 if (isFromMouse) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002045 x = int32_t(entry.xCursorPosition);
2046 y = int32_t(entry.yCursorPosition);
Garfield Tan00f511d2019-06-12 16:55:40 -07002047 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002048 x = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X));
2049 y = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y));
Garfield Tan00f511d2019-06-12 16:55:40 -07002050 }
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002051 const bool isDown = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Prabir Pradhand65552b2021-10-07 11:23:50 -07002052 const bool isStylus = isPointerFromStylus(entry, pointerIndex);
Siarhei Vishniakou64452932020-11-06 17:51:32 -06002053 newTouchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y, &tempTouchState,
Prabir Pradhand65552b2021-10-07 11:23:50 -07002054 isStylus, isDown /*addOutsideTargets*/);
Michael Wright3dd60e22019-03-27 22:06:44 +00002055
Michael Wrightd02c5b62014-02-10 15:10:22 -08002056 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07002057 if (newTouchedWindowHandle == nullptr) {
Arthur Hungb3307ee2021-10-14 10:57:37 +00002058 ALOGD("No new touched window at (%" PRId32 ", %" PRId32 ") in display %" PRId32, x, y,
2059 displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002060 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002061 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002062 }
2063
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002064 // Figure out whether splitting will be allowed for this window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002065 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002066 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
2067 // New window supports splitting, but we should never split mouse events.
2068 isSplit = !isFromMouse;
2069 } else if (isSplit) {
2070 // New window does not support splitting but we have already split events.
2071 // Ignore the new window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002072 newTouchedWindowHandle = nullptr;
2073 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002074 } else {
2075 // No window is touched, so set split to true. This will allow the next pointer down to
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002076 // be delivered to a new window which supports split touch. Pointers from a mouse device
2077 // should never be split.
2078 tempTouchState.split = isSplit = !isFromMouse;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002079 }
2080
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002081 // Update hover state.
Michael Wright3dd60e22019-03-27 22:06:44 +00002082 if (newTouchedWindowHandle != nullptr) {
Garfield Tandf26e862020-07-01 20:18:19 -07002083 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
2084 newHoverWindowHandle = nullptr;
2085 } else if (isHoverAction) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002086 newHoverWindowHandle = newTouchedWindowHandle;
Michael Wright3dd60e22019-03-27 22:06:44 +00002087 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002088 }
2089
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002090 std::vector<sp<WindowInfoHandle>> newTouchedWindows =
Prabir Pradhand65552b2021-10-07 11:23:50 -07002091 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002092 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002093 // Process the foreground window first so that it is the first to receive the event.
2094 newTouchedWindows.insert(newTouchedWindows.begin(), newTouchedWindowHandle);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002095 }
2096
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002097 if (newTouchedWindows.empty()) {
2098 ALOGI("Dropping event because there is no touchable window at (%d, %d) on display %d.",
2099 x, y, displayId);
2100 injectionResult = InputEventInjectionResult::FAILED;
2101 goto Failed;
2102 }
2103
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002104 for (const sp<WindowInfoHandle>& windowHandle : newTouchedWindows) {
2105 const WindowInfo& info = *windowHandle->getInfo();
2106
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002107 if (info.inputConfig.test(WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002108 ALOGI("Not sending touch event to %s because it is paused",
2109 windowHandle->getName().c_str());
2110 continue;
2111 }
2112
2113 // Ensure the window has a connection and the connection is responsive
2114 const bool isResponsive = hasResponsiveConnectionLocked(*windowHandle);
2115 if (!isResponsive) {
2116 ALOGW("Not sending touch gesture to %s because it is not responsive",
2117 windowHandle->getName().c_str());
2118 continue;
2119 }
2120
2121 // Drop events that can't be trusted due to occlusion
2122 if (mBlockUntrustedTouchesMode != BlockUntrustedTouchesMode::DISABLED) {
2123 TouchOcclusionInfo occlusionInfo =
2124 computeTouchOcclusionInfoLocked(windowHandle, x, y);
2125 if (!isTouchTrustedLocked(occlusionInfo)) {
2126 if (DEBUG_TOUCH_OCCLUSION) {
2127 ALOGD("Stack of obscuring windows during untrusted touch (%d, %d):", x, y);
2128 for (const auto& log : occlusionInfo.debugInfo) {
2129 ALOGD("%s", log.c_str());
2130 }
2131 }
2132 sendUntrustedTouchCommandLocked(occlusionInfo.obscuringPackage);
2133 if (mBlockUntrustedTouchesMode == BlockUntrustedTouchesMode::BLOCK) {
2134 ALOGW("Dropping untrusted touch event due to %s/%d",
2135 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid);
2136 continue;
2137 }
2138 }
2139 }
2140
2141 // Drop touch events if requested by input feature
2142 if (shouldDropInput(entry, windowHandle)) {
2143 continue;
2144 }
2145
2146 // Set target flags.
2147 int32_t targetFlags = InputTarget::FLAG_DISPATCH_AS_IS;
2148
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002149 if (!info.isSpy()) {
2150 // There should only be one new foreground (non-spy) window at this location.
2151 targetFlags |= InputTarget::FLAG_FOREGROUND;
2152 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002153
2154 if (isSplit) {
2155 targetFlags |= InputTarget::FLAG_SPLIT;
2156 }
2157 if (isWindowObscuredAtPointLocked(windowHandle, x, y)) {
2158 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
2159 } else if (isWindowObscuredLocked(windowHandle)) {
2160 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2161 }
Michael Wright3dd60e22019-03-27 22:06:44 +00002162
2163 // Update the temporary touch state.
2164 BitSet32 pointerIds;
2165 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002166 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wright3dd60e22019-03-27 22:06:44 +00002167 pointerIds.markBit(pointerId);
2168 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002169
2170 tempTouchState.addOrUpdateWindow(windowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002171 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002172 } else {
2173 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
2174
2175 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002176 if (!tempTouchState.down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002177 if (DEBUG_FOCUS) {
2178 ALOGD("Dropping event because the pointer is not down or we previously "
2179 "dropped the pointer down event in display %" PRId32,
2180 displayId);
2181 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002182 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002183 goto Failed;
2184 }
2185
arthurhung6d4bed92021-03-17 11:59:33 +08002186 addDragEventLocked(entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002187
Michael Wrightd02c5b62014-02-10 15:10:22 -08002188 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002189 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002190 tempTouchState.isSlippery()) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002191 const int32_t x = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
2192 const int32_t y = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002193
Prabir Pradhand65552b2021-10-07 11:23:50 -07002194 const bool isStylus = isPointerFromStylus(entry, 0 /*pointerIndex*/);
chaviw98318de2021-05-19 16:45:23 -05002195 sp<WindowInfoHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002196 tempTouchState.getFirstForegroundWindowHandle();
Prabir Pradhand65552b2021-10-07 11:23:50 -07002197 newTouchedWindowHandle =
2198 findTouchedWindowAtLocked(displayId, x, y, &tempTouchState, isStylus);
Vishnu Nair062a8672021-09-03 16:07:44 -07002199
2200 // Drop touch events if requested by input feature
2201 if (newTouchedWindowHandle != nullptr &&
2202 shouldDropInput(entry, newTouchedWindowHandle)) {
2203 newTouchedWindowHandle = nullptr;
2204 }
2205
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002206 if (oldTouchedWindowHandle != newTouchedWindowHandle &&
2207 oldTouchedWindowHandle != nullptr && newTouchedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002208 if (DEBUG_FOCUS) {
2209 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
2210 oldTouchedWindowHandle->getName().c_str(),
2211 newTouchedWindowHandle->getName().c_str(), displayId);
2212 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002213 // Make a slippery exit from the old window.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002214 tempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
2215 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT,
2216 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002217
2218 // Make a slippery entrance into the new window.
2219 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002220 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002221 }
2222
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002223 int32_t targetFlags =
2224 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002225 if (isSplit) {
2226 targetFlags |= InputTarget::FLAG_SPLIT;
2227 }
2228 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
2229 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002230 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
2231 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002232 }
2233
2234 BitSet32 pointerIds;
2235 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002236 pointerIds.markBit(entry.pointerProperties[0].id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002237 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002238 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002239 }
2240 }
2241 }
2242
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002243 // Update dispatching for hover enter and exit.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002244 if (newHoverWindowHandle != mLastHoverWindowHandle) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002245 // Let the previous window know that the hover sequence is over, unless we already did
2246 // it when dispatching it as is to newTouchedWindowHandle.
Garfield Tandf26e862020-07-01 20:18:19 -07002247 if (mLastHoverWindowHandle != nullptr &&
2248 (maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT ||
2249 mLastHoverWindowHandle != newTouchedWindowHandle)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002250 if (DEBUG_HOVER) {
2251 ALOGD("Sending hover exit event to window %s.",
2252 mLastHoverWindowHandle->getName().c_str());
2253 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002254 tempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
2255 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002256 }
2257
Garfield Tandf26e862020-07-01 20:18:19 -07002258 // Let the new window know that the hover sequence is starting, unless we already did it
2259 // when dispatching it as is to newTouchedWindowHandle.
2260 if (newHoverWindowHandle != nullptr &&
2261 (maskedAction != AMOTION_EVENT_ACTION_HOVER_ENTER ||
2262 newHoverWindowHandle != newTouchedWindowHandle)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002263 if (DEBUG_HOVER) {
2264 ALOGD("Sending hover enter event to window %s.",
2265 newHoverWindowHandle->getName().c_str());
2266 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002267 tempTouchState.addOrUpdateWindow(newHoverWindowHandle,
2268 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER,
2269 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002270 }
2271 }
2272
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002273 // Ensure that we have at least one foreground or spy window. It's possible that we dropped some
2274 // of the touched windows we previously found if they became paused or unresponsive or were
2275 // removed.
2276 if (std::none_of(tempTouchState.windows.begin(), tempTouchState.windows.end(),
2277 [](const TouchedWindow& touchedWindow) {
2278 return (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) != 0 ||
2279 touchedWindow.windowHandle->getInfo()->isSpy();
2280 })) {
2281 ALOGI("Dropping event because there is no touched window on display %d to receive it.",
2282 displayId);
2283 injectionResult = InputEventInjectionResult::FAILED;
2284 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002285 }
2286
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002287 // Check permission to inject into all touched foreground windows.
2288 if (std::any_of(tempTouchState.windows.begin(), tempTouchState.windows.end(),
2289 [this, &entry](const TouchedWindow& touchedWindow) {
2290 return (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) != 0 &&
2291 !checkInjectionPermission(touchedWindow.windowHandle,
2292 entry.injectionState);
2293 })) {
2294 injectionResult = InputEventInjectionResult::PERMISSION_DENIED;
2295 injectionPermission = INJECTION_PERMISSION_DENIED;
2296 goto Failed;
2297 }
2298 // Permission granted to inject into all touched foreground windows.
2299 injectionPermission = INJECTION_PERMISSION_GRANTED;
2300
Michael Wrightd02c5b62014-02-10 15:10:22 -08002301 // Check whether windows listening for outside touches are owned by the same UID. If it is
2302 // set the policy flag that we will not reveal coordinate information to this window.
2303 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002304 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002305 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002306 if (foregroundWindowHandle) {
2307 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002308 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002309 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
chaviw98318de2021-05-19 16:45:23 -05002310 sp<WindowInfoHandle> windowInfoHandle = touchedWindow.windowHandle;
2311 if (windowInfoHandle->getInfo()->ownerUid != foregroundWindowUid) {
2312 tempTouchState.addOrUpdateWindow(windowInfoHandle,
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002313 InputTarget::FLAG_ZERO_COORDS,
2314 BitSet32(0));
Michael Wright3dd60e22019-03-27 22:06:44 +00002315 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002316 }
2317 }
2318 }
2319 }
2320
Michael Wrightd02c5b62014-02-10 15:10:22 -08002321 // If this is the first pointer going down and the touched window has a wallpaper
2322 // then also add the touched wallpaper windows so they are locked in for the duration
2323 // of the touch gesture.
2324 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
2325 // engine only supports touch events. We would need to add a mechanism similar
2326 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
2327 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002328 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002329 tempTouchState.getFirstForegroundWindowHandle();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002330 if (foregroundWindowHandle &&
2331 foregroundWindowHandle->getInfo()->inputConfig.test(
2332 WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
chaviw98318de2021-05-19 16:45:23 -05002333 const std::vector<sp<WindowInfoHandle>>& windowHandles =
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002334 getWindowHandlesLocked(displayId);
chaviw98318de2021-05-19 16:45:23 -05002335 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
2336 const WindowInfo* info = windowHandle->getInfo();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002337 if (info->displayId == displayId &&
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002338 windowHandle->getInfo()->inputConfig.test(
2339 WindowInfo::InputConfig::IS_WALLPAPER)) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002340 tempTouchState
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002341 .addOrUpdateWindow(windowHandle,
2342 InputTarget::FLAG_WINDOW_IS_OBSCURED |
2343 InputTarget::
2344 FLAG_WINDOW_IS_PARTIALLY_OBSCURED |
2345 InputTarget::FLAG_DISPATCH_AS_IS,
2346 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002347 }
2348 }
2349 }
2350 }
2351
2352 // Success! Output targets.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002353 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002354
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002355 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002356 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002357 touchedWindow.pointerIds, inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002358 }
2359
2360 // Drop the outside or hover touch windows since we will not care about them
2361 // in the next iteration.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002362 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002363
2364Failed:
2365 // Check injection permission once and for all.
2366 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002367 if (checkInjectionPermission(nullptr, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002368 injectionPermission = INJECTION_PERMISSION_GRANTED;
2369 } else {
2370 injectionPermission = INJECTION_PERMISSION_DENIED;
2371 }
2372 }
2373
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002374 if (injectionPermission != INJECTION_PERMISSION_GRANTED) {
2375 return injectionResult;
2376 }
2377
Michael Wrightd02c5b62014-02-10 15:10:22 -08002378 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002379 if (!wrongDevice) {
2380 if (switchedDevice) {
2381 if (DEBUG_FOCUS) {
2382 ALOGD("Conflicting pointer actions: Switched to a different device.");
2383 }
2384 *outConflictingPointerActions = true;
2385 }
2386
2387 if (isHoverAction) {
2388 // Started hovering, therefore no longer down.
2389 if (oldState && oldState->down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002390 if (DEBUG_FOCUS) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002391 ALOGD("Conflicting pointer actions: Hover received while pointer was "
2392 "down.");
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002393 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002394 *outConflictingPointerActions = true;
2395 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002396 tempTouchState.reset();
2397 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2398 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
2399 tempTouchState.deviceId = entry.deviceId;
2400 tempTouchState.source = entry.source;
2401 tempTouchState.displayId = displayId;
2402 }
2403 } else if (maskedAction == AMOTION_EVENT_ACTION_UP ||
2404 maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
2405 // All pointers up or canceled.
2406 tempTouchState.reset();
2407 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2408 // First pointer went down.
2409 if (oldState && oldState->down) {
2410 if (DEBUG_FOCUS) {
2411 ALOGD("Conflicting pointer actions: Down received while already down.");
2412 }
2413 *outConflictingPointerActions = true;
2414 }
2415 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2416 // One pointer went up.
2417 if (isSplit) {
2418 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2419 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002420
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002421 for (size_t i = 0; i < tempTouchState.windows.size();) {
2422 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2423 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
2424 touchedWindow.pointerIds.clearBit(pointerId);
2425 if (touchedWindow.pointerIds.isEmpty()) {
2426 tempTouchState.windows.erase(tempTouchState.windows.begin() + i);
2427 continue;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002428 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002429 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002430 i += 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002431 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002432 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002433 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002434
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002435 // Save changes unless the action was scroll in which case the temporary touch
2436 // state was only valid for this one action.
2437 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
2438 if (tempTouchState.displayId >= 0) {
2439 mTouchStatesByDisplay[displayId] = tempTouchState;
2440 } else {
2441 mTouchStatesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002442 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002443 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002444
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002445 // Update hover state.
2446 mLastHoverWindowHandle = newHoverWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002447 }
2448
Michael Wrightd02c5b62014-02-10 15:10:22 -08002449 return injectionResult;
2450}
2451
arthurhung6d4bed92021-03-17 11:59:33 +08002452void InputDispatcher::finishDragAndDrop(int32_t displayId, float x, float y) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07002453 // Prevent stylus interceptor windows from affecting drag and drop behavior for now, until we
2454 // have an explicit reason to support it.
2455 constexpr bool isStylus = false;
2456
chaviw98318de2021-05-19 16:45:23 -05002457 const sp<WindowInfoHandle> dropWindow =
Prabir Pradhand65552b2021-10-07 11:23:50 -07002458 findTouchedWindowAtLocked(displayId, x, y, nullptr /*touchState*/, isStylus,
Siarhei Vishniakou64452932020-11-06 17:51:32 -06002459 false /*addOutsideTargets*/, true /*ignoreDragWindow*/);
arthurhung6d4bed92021-03-17 11:59:33 +08002460 if (dropWindow) {
2461 vec2 local = dropWindow->getInfo()->transform.transform(x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002462 sendDropWindowCommandLocked(dropWindow->getToken(), local.x, local.y);
Arthur Hung6d0571e2021-04-09 20:18:16 +08002463 } else {
Prabir Pradhancef936d2021-07-21 16:17:52 +00002464 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002465 }
2466 mDragState.reset();
2467}
2468
2469void InputDispatcher::addDragEventLocked(const MotionEntry& entry) {
2470 if (entry.pointerCount != 1 || !mDragState) {
arthurhungb89ccb02020-12-30 16:19:01 +08002471 return;
2472 }
2473
arthurhung6d4bed92021-03-17 11:59:33 +08002474 if (!mDragState->isStartDrag) {
2475 mDragState->isStartDrag = true;
2476 mDragState->isStylusButtonDownAtStart =
2477 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2478 }
2479
arthurhungb89ccb02020-12-30 16:19:01 +08002480 int32_t maskedAction = entry.action & AMOTION_EVENT_ACTION_MASK;
2481 int32_t x = static_cast<int32_t>(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
2482 int32_t y = static_cast<int32_t>(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
2483 if (maskedAction == AMOTION_EVENT_ACTION_MOVE) {
arthurhung6d4bed92021-03-17 11:59:33 +08002484 // Handle the special case : stylus button no longer pressed.
2485 bool isStylusButtonDown = (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2486 if (mDragState->isStylusButtonDownAtStart && !isStylusButtonDown) {
2487 finishDragAndDrop(entry.displayId, x, y);
2488 return;
2489 }
2490
Prabir Pradhand65552b2021-10-07 11:23:50 -07002491 // Prevent stylus interceptor windows from affecting drag and drop behavior for now, until
2492 // we have an explicit reason to support it.
2493 constexpr bool isStylus = false;
2494
chaviw98318de2021-05-19 16:45:23 -05002495 const sp<WindowInfoHandle> hoverWindowHandle =
Prabir Pradhand65552b2021-10-07 11:23:50 -07002496 findTouchedWindowAtLocked(entry.displayId, x, y, nullptr /*touchState*/, isStylus,
Siarhei Vishniakou64452932020-11-06 17:51:32 -06002497 false /*addOutsideTargets*/, true /*ignoreDragWindow*/);
arthurhungb89ccb02020-12-30 16:19:01 +08002498 // enqueue drag exit if needed.
arthurhung6d4bed92021-03-17 11:59:33 +08002499 if (hoverWindowHandle != mDragState->dragHoverWindowHandle &&
2500 !haveSameToken(hoverWindowHandle, mDragState->dragHoverWindowHandle)) {
2501 if (mDragState->dragHoverWindowHandle != nullptr) {
2502 enqueueDragEventLocked(mDragState->dragHoverWindowHandle, true /*isExiting*/,
2503 entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002504 }
arthurhung6d4bed92021-03-17 11:59:33 +08002505 mDragState->dragHoverWindowHandle = hoverWindowHandle;
arthurhungb89ccb02020-12-30 16:19:01 +08002506 }
2507 // enqueue drag location if needed.
2508 if (hoverWindowHandle != nullptr) {
2509 enqueueDragEventLocked(hoverWindowHandle, false /*isExiting*/, entry);
2510 }
arthurhung6d4bed92021-03-17 11:59:33 +08002511 } else if (maskedAction == AMOTION_EVENT_ACTION_UP) {
2512 finishDragAndDrop(entry.displayId, x, y);
2513 } else if (maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00002514 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002515 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08002516 }
2517}
2518
chaviw98318de2021-05-19 16:45:23 -05002519void InputDispatcher::addWindowTargetLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002520 int32_t targetFlags, BitSet32 pointerIds,
2521 std::vector<InputTarget>& inputTargets) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002522 std::vector<InputTarget>::iterator it =
2523 std::find_if(inputTargets.begin(), inputTargets.end(),
2524 [&windowHandle](const InputTarget& inputTarget) {
2525 return inputTarget.inputChannel->getConnectionToken() ==
2526 windowHandle->getToken();
2527 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002528
chaviw98318de2021-05-19 16:45:23 -05002529 const WindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002530
2531 if (it == inputTargets.end()) {
2532 InputTarget inputTarget;
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05002533 std::shared_ptr<InputChannel> inputChannel =
2534 getInputChannelLocked(windowHandle->getToken());
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002535 if (inputChannel == nullptr) {
2536 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
2537 return;
2538 }
2539 inputTarget.inputChannel = inputChannel;
2540 inputTarget.flags = targetFlags;
2541 inputTarget.globalScaleFactor = windowInfo->globalScaleFactor;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002542 const auto& displayInfoIt = mDisplayInfos.find(windowInfo->displayId);
2543 if (displayInfoIt != mDisplayInfos.end()) {
Prabir Pradhanb9b18502021-08-26 12:30:32 -07002544 inputTarget.displayTransform = displayInfoIt->second.transform;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002545 } else {
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00002546 ALOGE("DisplayInfo not found for window on display: %d", windowInfo->displayId);
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002547 }
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002548 inputTargets.push_back(inputTarget);
2549 it = inputTargets.end() - 1;
2550 }
2551
2552 ALOG_ASSERT(it->flags == targetFlags);
2553 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
2554
chaviw1ff3d1e2020-07-01 15:53:47 -07002555 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002556}
2557
Michael Wright3dd60e22019-03-27 22:06:44 +00002558void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002559 int32_t displayId) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002560 auto monitorsIt = mGlobalMonitorsByDisplay.find(displayId);
2561 if (monitorsIt == mGlobalMonitorsByDisplay.end()) return;
Michael Wright3dd60e22019-03-27 22:06:44 +00002562
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002563 for (const Monitor& monitor : selectResponsiveMonitorsLocked(monitorsIt->second)) {
2564 InputTarget target;
2565 target.inputChannel = monitor.inputChannel;
2566 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
2567 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
2568 target.displayTransform = it->second.transform;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002569 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002570 target.setDefaultPointerTransform(target.displayTransform);
2571 inputTargets.push_back(target);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002572 }
2573}
2574
chaviw98318de2021-05-19 16:45:23 -05002575bool InputDispatcher::checkInjectionPermission(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002576 const InjectionState* injectionState) {
2577 if (injectionState &&
2578 (windowHandle == nullptr ||
2579 windowHandle->getInfo()->ownerUid != injectionState->injectorUid) &&
2580 !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002581 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002582 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002583 "owned by uid %d",
2584 injectionState->injectorPid, injectionState->injectorUid,
2585 windowHandle->getName().c_str(), windowHandle->getInfo()->ownerUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002586 } else {
2587 ALOGW("Permission denied: injecting event from pid %d uid %d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002588 injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002589 }
2590 return false;
2591 }
2592 return true;
2593}
2594
Robert Carrc9bf1d32020-04-13 17:21:08 -07002595/**
2596 * Indicate whether one window handle should be considered as obscuring
2597 * another window handle. We only check a few preconditions. Actually
2598 * checking the bounds is left to the caller.
2599 */
chaviw98318de2021-05-19 16:45:23 -05002600static bool canBeObscuredBy(const sp<WindowInfoHandle>& windowHandle,
2601 const sp<WindowInfoHandle>& otherHandle) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002602 // Compare by token so cloned layers aren't counted
2603 if (haveSameToken(windowHandle, otherHandle)) {
2604 return false;
2605 }
2606 auto info = windowHandle->getInfo();
2607 auto otherInfo = otherHandle->getInfo();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002608 if (otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002609 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002610 } else if (otherInfo->alpha == 0 &&
2611 otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE)) {
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002612 // Those act as if they were invisible, so we don't need to flag them.
2613 // We do want to potentially flag touchable windows even if they have 0
2614 // opacity, since they can consume touches and alter the effects of the
2615 // user interaction (eg. apps that rely on
2616 // FLAG_WINDOW_IS_PARTIALLY_OBSCURED should still be told about those
2617 // windows), hence we also check for FLAG_NOT_TOUCHABLE.
2618 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00002619 } else if (info->ownerUid == otherInfo->ownerUid) {
2620 // If ownerUid is the same we don't generate occlusion events as there
2621 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002622 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002623 } else if (otherInfo->inputConfig.test(gui::WindowInfo::InputConfig::TRUSTED_OVERLAY)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002624 return false;
2625 } else if (otherInfo->displayId != info->displayId) {
2626 return false;
2627 }
2628 return true;
2629}
2630
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002631/**
2632 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
2633 * untrusted, one should check:
2634 *
2635 * 1. If result.hasBlockingOcclusion is true.
2636 * If it's, it means the touch should be blocked due to a window with occlusion mode of
2637 * BLOCK_UNTRUSTED.
2638 *
2639 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
2640 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
2641 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
2642 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
2643 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
2644 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
2645 *
2646 * If neither of those is true, then it means the touch can be allowed.
2647 */
2648InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
chaviw98318de2021-05-19 16:45:23 -05002649 const sp<WindowInfoHandle>& windowHandle, int32_t x, int32_t y) const {
2650 const WindowInfo* windowInfo = windowHandle->getInfo();
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002651 int32_t displayId = windowInfo->displayId;
chaviw98318de2021-05-19 16:45:23 -05002652 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002653 TouchOcclusionInfo info;
2654 info.hasBlockingOcclusion = false;
2655 info.obscuringOpacity = 0;
2656 info.obscuringUid = -1;
2657 std::map<int32_t, float> opacityByUid;
chaviw98318de2021-05-19 16:45:23 -05002658 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002659 if (windowHandle == otherHandle) {
2660 break; // All future windows are below us. Exit early.
2661 }
chaviw98318de2021-05-19 16:45:23 -05002662 const WindowInfo* otherInfo = otherHandle->getInfo();
Bernardo Rufino1ff9d592021-01-18 16:58:57 +00002663 if (canBeObscuredBy(windowHandle, otherHandle) && otherInfo->frameContainsPoint(x, y) &&
2664 !haveSameApplicationToken(windowInfo, otherInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002665 if (DEBUG_TOUCH_OCCLUSION) {
2666 info.debugInfo.push_back(
2667 dumpWindowForTouchOcclusion(otherInfo, /* isTouchedWindow */ false));
2668 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002669 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
2670 // we perform the checks below to see if the touch can be propagated or not based on the
2671 // window's touch occlusion mode
2672 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
2673 info.hasBlockingOcclusion = true;
2674 info.obscuringUid = otherInfo->ownerUid;
2675 info.obscuringPackage = otherInfo->packageName;
2676 break;
2677 }
2678 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
2679 uint32_t uid = otherInfo->ownerUid;
2680 float opacity =
2681 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
2682 // Given windows A and B:
2683 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
2684 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
2685 opacityByUid[uid] = opacity;
2686 if (opacity > info.obscuringOpacity) {
2687 info.obscuringOpacity = opacity;
2688 info.obscuringUid = uid;
2689 info.obscuringPackage = otherInfo->packageName;
2690 }
2691 }
2692 }
2693 }
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002694 if (DEBUG_TOUCH_OCCLUSION) {
2695 info.debugInfo.push_back(
2696 dumpWindowForTouchOcclusion(windowInfo, /* isTouchedWindow */ true));
2697 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002698 return info;
2699}
2700
chaviw98318de2021-05-19 16:45:23 -05002701std::string InputDispatcher::dumpWindowForTouchOcclusion(const WindowInfo* info,
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002702 bool isTouchedWindow) const {
Bernardo Rufino49d99e42021-01-18 15:16:59 +00002703 return StringPrintf(INDENT2
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002704 "* %spackage=%s/%" PRId32 ", id=%" PRId32 ", mode=%s, alpha=%.2f, "
Bernardo Rufino49d99e42021-01-18 15:16:59 +00002705 "frame=[%" PRId32 ",%" PRId32 "][%" PRId32 ",%" PRId32
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002706 "], touchableRegion=%s, window={%s}, inputConfig={%s}, inputFeatures={%s}, "
Bernardo Rufino49d99e42021-01-18 15:16:59 +00002707 "hasToken=%s, applicationInfo.name=%s, applicationInfo.token=%s\n",
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002708 isTouchedWindow ? "[TOUCHED] " : "", info->packageName.c_str(),
2709 info->ownerUid, info->id, toString(info->touchOcclusionMode).c_str(),
2710 info->alpha, info->frameLeft, info->frameTop, info->frameRight,
2711 info->frameBottom, dumpRegion(info->touchableRegion).c_str(),
2712 info->name.c_str(), info->inputConfig.string().c_str(),
2713 info->inputFeatures.string().c_str(), toString(info->token != nullptr),
2714 info->applicationInfo.name.c_str(),
Bernardo Rufino49d99e42021-01-18 15:16:59 +00002715 toString(info->applicationInfo.token).c_str());
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002716}
2717
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002718bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
2719 if (occlusionInfo.hasBlockingOcclusion) {
2720 ALOGW("Untrusted touch due to occlusion by %s/%d", occlusionInfo.obscuringPackage.c_str(),
2721 occlusionInfo.obscuringUid);
2722 return false;
2723 }
2724 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
2725 ALOGW("Untrusted touch due to occlusion by %s/%d (obscuring opacity = "
2726 "%.2f, maximum allowed = %.2f)",
2727 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid,
2728 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
2729 return false;
2730 }
2731 return true;
2732}
2733
chaviw98318de2021-05-19 16:45:23 -05002734bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002735 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002736 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05002737 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2738 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002739 if (windowHandle == otherHandle) {
2740 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002741 }
chaviw98318de2021-05-19 16:45:23 -05002742 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002743 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002744 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002745 return true;
2746 }
2747 }
2748 return false;
2749}
2750
chaviw98318de2021-05-19 16:45:23 -05002751bool InputDispatcher::isWindowObscuredLocked(const sp<WindowInfoHandle>& windowHandle) const {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002752 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05002753 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2754 const WindowInfo* windowInfo = windowHandle->getInfo();
2755 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002756 if (windowHandle == otherHandle) {
2757 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002758 }
chaviw98318de2021-05-19 16:45:23 -05002759 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002760 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002761 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002762 return true;
2763 }
2764 }
2765 return false;
2766}
2767
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002768std::string InputDispatcher::getApplicationWindowLabel(
chaviw98318de2021-05-19 16:45:23 -05002769 const InputApplicationHandle* applicationHandle, const sp<WindowInfoHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002770 if (applicationHandle != nullptr) {
2771 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002772 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002773 } else {
2774 return applicationHandle->getName();
2775 }
Yi Kong9b14ac62018-07-17 13:48:38 -07002776 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002777 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002778 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002779 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002780 }
2781}
2782
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002783void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00002784 if (!isUserActivityEvent(eventEntry)) {
2785 // Not poking user activity if the event type does not represent a user activity
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002786 return;
2787 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002788 int32_t displayId = getTargetDisplayId(eventEntry);
chaviw98318de2021-05-19 16:45:23 -05002789 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Tiger Huang721e26f2018-07-24 22:26:19 +08002790 if (focusedWindowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05002791 const WindowInfo* info = focusedWindowHandle->getInfo();
2792 if (info->inputFeatures.test(WindowInfo::Feature::DISABLE_USER_ACTIVITY)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002793 if (DEBUG_DISPATCH_CYCLE) {
2794 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
2795 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002796 return;
2797 }
2798 }
2799
2800 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002801 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002802 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002803 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
2804 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002805 return;
2806 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002807
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002808 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002809 eventType = USER_ACTIVITY_EVENT_TOUCH;
2810 }
2811 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002812 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002813 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002814 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
2815 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002816 return;
2817 }
2818 eventType = USER_ACTIVITY_EVENT_BUTTON;
2819 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002820 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00002821 default: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002822 LOG_ALWAYS_FATAL("%s events are not user activity",
Dominik Laskowski75788452021-02-09 18:51:25 -08002823 ftl::enum_string(eventEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002824 break;
2825 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002826 }
2827
Prabir Pradhancef936d2021-07-21 16:17:52 +00002828 auto command = [this, eventTime = eventEntry.eventTime, eventType, displayId]()
2829 REQUIRES(mLock) {
2830 scoped_unlock unlock(mLock);
2831 mPolicy->pokeUserActivity(eventTime, eventType, displayId);
2832 };
2833 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002834}
2835
2836void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002837 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002838 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002839 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002840 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002841 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002842 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002843 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002844 ATRACE_NAME(message.c_str());
2845 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002846 if (DEBUG_DISPATCH_CYCLE) {
2847 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
2848 "globalScaleFactor=%f, pointerIds=0x%x %s",
2849 connection->getInputChannelName().c_str(), inputTarget.flags,
2850 inputTarget.globalScaleFactor, inputTarget.pointerIds.value,
2851 inputTarget.getPointerInfoString().c_str());
2852 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002853
2854 // Skip this event if the connection status is not normal.
2855 // We don't want to enqueue additional outbound events if the connection is broken.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08002856 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002857 if (DEBUG_DISPATCH_CYCLE) {
2858 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08002859 connection->getInputChannelName().c_str(),
2860 ftl::enum_string(connection->status).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002861 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002862 return;
2863 }
2864
2865 // Split a motion event if needed.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002866 if (inputTarget.flags & InputTarget::FLAG_SPLIT) {
2867 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
2868 "Entry type %s should not have FLAG_SPLIT",
Dominik Laskowski75788452021-02-09 18:51:25 -08002869 ftl::enum_string(eventEntry->type).c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002870
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002871 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002872 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002873 std::unique_ptr<MotionEntry> splitMotionEntry =
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002874 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002875 if (!splitMotionEntry) {
2876 return; // split event was dropped
2877 }
Arthur Hungb3307ee2021-10-14 10:57:37 +00002878 if (splitMotionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
2879 std::string reason = std::string("reason=pointer cancel on split window");
2880 android_log_event_list(LOGTAG_INPUT_CANCEL)
2881 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
2882 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002883 if (DEBUG_FOCUS) {
2884 ALOGD("channel '%s' ~ Split motion event.",
2885 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002886 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002887 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002888 enqueueDispatchEntriesLocked(currentTime, connection, std::move(splitMotionEntry),
2889 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002890 return;
2891 }
2892 }
2893
2894 // Not splitting. Enqueue dispatch entries for the event as is.
2895 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
2896}
2897
2898void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002899 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002900 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002901 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002902 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002903 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002904 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002905 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002906 ATRACE_NAME(message.c_str());
2907 }
2908
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002909 bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002910
2911 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07002912 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002913 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002914 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002915 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07002916 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002917 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07002918 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002919 InputTarget::FLAG_DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07002920 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002921 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002922 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002923 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002924
2925 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002926 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002927 startDispatchCycleLocked(currentTime, connection);
2928 }
2929}
2930
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002931void InputDispatcher::enqueueDispatchEntryLocked(const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002932 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002933 const InputTarget& inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002934 int32_t dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002935 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002936 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
2937 connection->getInputChannelName().c_str(),
2938 dispatchModeToString(dispatchMode).c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002939 ATRACE_NAME(message.c_str());
2940 }
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002941 int32_t inputTargetFlags = inputTarget.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002942 if (!(inputTargetFlags & dispatchMode)) {
2943 return;
2944 }
2945 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
2946
2947 // This is a new event.
2948 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002949 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002950 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002951
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002952 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
2953 // different EventEntry than what was passed in.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002954 EventEntry& newEntry = *(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002955 // Apply target flags and update the connection's input state.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002956 switch (newEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002957 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002958 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002959 dispatchEntry->resolvedEventId = keyEntry.id;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002960 dispatchEntry->resolvedAction = keyEntry.action;
2961 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002962
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002963 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
2964 dispatchEntry->resolvedFlags)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002965 if (DEBUG_DISPATCH_CYCLE) {
2966 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key "
2967 "event",
2968 connection->getInputChannelName().c_str());
2969 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002970 return; // skip the inconsistent event
2971 }
2972 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002973 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002974
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002975 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002976 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002977 // Assign a default value to dispatchEntry that will never be generated by InputReader,
2978 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
2979 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
2980 static_cast<int32_t>(IdGenerator::Source::OTHER);
2981 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002982 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2983 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
2984 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
2985 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
2986 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
2987 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2988 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
2989 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
2990 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
2991 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
2992 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002993 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002994 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002995 }
2996 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002997 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
2998 motionEntry.displayId)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002999 if (DEBUG_DISPATCH_CYCLE) {
3000 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover "
3001 "enter event",
3002 connection->getInputChannelName().c_str());
3003 }
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003004 // We keep the 'resolvedEventId' here equal to the original 'motionEntry.id' because
3005 // this is a one-to-one event conversion.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003006 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
3007 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003008
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003009 dispatchEntry->resolvedFlags = motionEntry.flags;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003010 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
3011 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
3012 }
3013 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
3014 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
3015 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003016
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003017 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
3018 dispatchEntry->resolvedFlags)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003019 if (DEBUG_DISPATCH_CYCLE) {
3020 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
3021 "event",
3022 connection->getInputChannelName().c_str());
3023 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003024 return; // skip the inconsistent event
3025 }
3026
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003027 dispatchEntry->resolvedEventId =
3028 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
3029 ? mIdGenerator.nextId()
3030 : motionEntry.id;
3031 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
3032 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
3033 ") to MotionEvent(id=0x%" PRIx32 ").",
3034 motionEntry.id, dispatchEntry->resolvedEventId);
3035 ATRACE_NAME(message.c_str());
3036 }
3037
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08003038 if ((motionEntry.flags & AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE) &&
3039 (motionEntry.policyFlags & POLICY_FLAG_TRUSTED)) {
3040 // Skip reporting pointer down outside focus to the policy.
3041 break;
3042 }
3043
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003044 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003045 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003046
3047 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003048 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003049 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003050 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003051 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3052 case EventEntry::Type::DRAG: {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003053 break;
3054 }
Chris Yef59a2f42020-10-16 12:55:26 -07003055 case EventEntry::Type::SENSOR: {
3056 LOG_ALWAYS_FATAL("SENSOR events should not go to apps via input channel");
3057 break;
3058 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003059 case EventEntry::Type::CONFIGURATION_CHANGED:
3060 case EventEntry::Type::DEVICE_RESET: {
3061 LOG_ALWAYS_FATAL("%s events should not go to apps",
Dominik Laskowski75788452021-02-09 18:51:25 -08003062 ftl::enum_string(newEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003063 break;
3064 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003065 }
3066
3067 // Remember that we are waiting for this dispatch to complete.
3068 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003069 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003070 }
3071
3072 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003073 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003074 traceOutboundQueueLength(*connection);
chaviw8c9cf542019-03-25 13:02:48 -07003075}
3076
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003077/**
3078 * This function is purely for debugging. It helps us understand where the user interaction
3079 * was taking place. For example, if user is touching launcher, we will see a log that user
3080 * started interacting with launcher. In that example, the event would go to the wallpaper as well.
3081 * We will see both launcher and wallpaper in that list.
3082 * Once the interaction with a particular set of connections starts, no new logs will be printed
3083 * until the set of interacted connections changes.
3084 *
3085 * The following items are skipped, to reduce the logspam:
3086 * ACTION_OUTSIDE: any windows that are receiving ACTION_OUTSIDE are not logged
3087 * ACTION_UP: any windows that receive ACTION_UP are not logged (for both keys and motions).
3088 * This includes situations like the soft BACK button key. When the user releases (lifts up the
3089 * finger) the back button, then navigation bar will inject KEYCODE_BACK with ACTION_UP.
3090 * Both of those ACTION_UP events would not be logged
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003091 */
3092void InputDispatcher::updateInteractionTokensLocked(const EventEntry& entry,
3093 const std::vector<InputTarget>& targets) {
3094 // Skip ACTION_UP events, and all events other than keys and motions
3095 if (entry.type == EventEntry::Type::KEY) {
3096 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
3097 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
3098 return;
3099 }
3100 } else if (entry.type == EventEntry::Type::MOTION) {
3101 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
3102 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
3103 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
3104 return;
3105 }
3106 } else {
3107 return; // Not a key or a motion
3108 }
3109
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07003110 std::unordered_set<sp<IBinder>, StrongPointerHash<IBinder>> newConnectionTokens;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003111 std::vector<sp<Connection>> newConnections;
3112 for (const InputTarget& target : targets) {
3113 if ((target.flags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) ==
3114 InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
3115 continue; // Skip windows that receive ACTION_OUTSIDE
3116 }
3117
3118 sp<IBinder> token = target.inputChannel->getConnectionToken();
3119 sp<Connection> connection = getConnectionLocked(token);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003120 if (connection == nullptr) {
3121 continue;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003122 }
3123 newConnectionTokens.insert(std::move(token));
3124 newConnections.emplace_back(connection);
3125 }
3126 if (newConnectionTokens == mInteractionConnectionTokens) {
3127 return; // no change
3128 }
3129 mInteractionConnectionTokens = newConnectionTokens;
3130
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003131 std::string targetList;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003132 for (const sp<Connection>& connection : newConnections) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003133 targetList += connection->getWindowName() + ", ";
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003134 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003135 std::string message = "Interaction with: " + targetList;
3136 if (targetList.empty()) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003137 message += "<none>";
3138 }
3139 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
3140}
3141
chaviwfd6d3512019-03-25 13:23:49 -07003142void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07003143 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07003144 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07003145 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
3146 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07003147 return;
3148 }
3149
Vishnu Nairc519ff72021-01-21 08:23:08 -08003150 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003151 if (focusedToken == token) {
3152 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07003153 return;
3154 }
3155
Prabir Pradhancef936d2021-07-21 16:17:52 +00003156 auto command = [this, token]() REQUIRES(mLock) {
3157 scoped_unlock unlock(mLock);
3158 mPolicy->onPointerDownOutsideFocus(token);
3159 };
3160 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003161}
3162
3163void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003164 const sp<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003165 if (ATRACE_ENABLED()) {
3166 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003167 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003168 ATRACE_NAME(message.c_str());
3169 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003170 if (DEBUG_DISPATCH_CYCLE) {
3171 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
3172 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003173
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003174 while (connection->status == Connection::Status::NORMAL && !connection->outboundQueue.empty()) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003175 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003176 dispatchEntry->deliveryTime = currentTime;
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003177 const std::chrono::nanoseconds timeout = getDispatchingTimeoutLocked(connection);
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003178 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003179
3180 // Publish the event.
3181 status_t status;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003182 const EventEntry& eventEntry = *(dispatchEntry->eventEntry);
3183 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003184 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003185 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3186 std::array<uint8_t, 32> hmac = getSignature(keyEntry, *dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003187
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003188 // Publish the key event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003189 status = connection->inputPublisher
3190 .publishKeyEvent(dispatchEntry->seq,
3191 dispatchEntry->resolvedEventId, keyEntry.deviceId,
3192 keyEntry.source, keyEntry.displayId,
3193 std::move(hmac), dispatchEntry->resolvedAction,
3194 dispatchEntry->resolvedFlags, keyEntry.keyCode,
3195 keyEntry.scanCode, keyEntry.metaState,
3196 keyEntry.repeatCount, keyEntry.downTime,
3197 keyEntry.eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003198 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003199 }
3200
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003201 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003202 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003203
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003204 PointerCoords scaledCoords[MAX_POINTERS];
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003205 const PointerCoords* usingCoords = motionEntry.pointerCoords;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003206
chaviw82357092020-01-28 13:13:06 -08003207 // Set the X and Y offset and X and Y scale depending on the input source.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003208 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) &&
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003209 !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
3210 float globalScaleFactor = dispatchEntry->globalScaleFactor;
chaviw82357092020-01-28 13:13:06 -08003211 if (globalScaleFactor != 1.0f) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003212 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3213 scaledCoords[i] = motionEntry.pointerCoords[i];
chaviw82357092020-01-28 13:13:06 -08003214 // Don't apply window scale here since we don't want scale to affect raw
3215 // coordinates. The scale will be sent back to the client and applied
3216 // later when requesting relative coordinates.
3217 scaledCoords[i].scale(globalScaleFactor, 1 /* windowXScale */,
3218 1 /* windowYScale */);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003219 }
3220 usingCoords = scaledCoords;
3221 }
3222 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003223 // We don't want the dispatch target to know.
3224 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003225 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003226 scaledCoords[i].clear();
3227 }
3228 usingCoords = scaledCoords;
3229 }
3230 }
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003231
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003232 std::array<uint8_t, 32> hmac = getSignature(motionEntry, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003233
3234 // Publish the motion event.
3235 status = connection->inputPublisher
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003236 .publishMotionEvent(dispatchEntry->seq,
3237 dispatchEntry->resolvedEventId,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003238 motionEntry.deviceId, motionEntry.source,
3239 motionEntry.displayId, std::move(hmac),
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003240 dispatchEntry->resolvedAction,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003241 motionEntry.actionButton,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003242 dispatchEntry->resolvedFlags,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003243 motionEntry.edgeFlags, motionEntry.metaState,
3244 motionEntry.buttonState,
3245 motionEntry.classification,
chaviw9eaa22c2020-07-01 16:21:27 -07003246 dispatchEntry->transform,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003247 motionEntry.xPrecision, motionEntry.yPrecision,
3248 motionEntry.xCursorPosition,
3249 motionEntry.yCursorPosition,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07003250 dispatchEntry->rawTransform,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003251 motionEntry.downTime, motionEntry.eventTime,
3252 motionEntry.pointerCount,
3253 motionEntry.pointerProperties, usingCoords);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003254 break;
3255 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003256
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003257 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003258 const FocusEntry& focusEntry = static_cast<const FocusEntry&>(eventEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003259 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003260 focusEntry.id,
Antonio Kantek3cfec7b2021-11-05 18:26:17 -07003261 focusEntry.hasFocus);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003262 break;
3263 }
3264
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003265 case EventEntry::Type::TOUCH_MODE_CHANGED: {
3266 const TouchModeEntry& touchModeEntry =
3267 static_cast<const TouchModeEntry&>(eventEntry);
3268 status = connection->inputPublisher
3269 .publishTouchModeEvent(dispatchEntry->seq, touchModeEntry.id,
3270 touchModeEntry.inTouchMode);
3271
3272 break;
3273 }
3274
Prabir Pradhan99987712020-11-10 18:43:05 -08003275 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3276 const auto& captureEntry =
3277 static_cast<const PointerCaptureChangedEntry&>(eventEntry);
3278 status = connection->inputPublisher
3279 .publishCaptureEvent(dispatchEntry->seq, captureEntry.id,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00003280 captureEntry.pointerCaptureRequest.enable);
Prabir Pradhan99987712020-11-10 18:43:05 -08003281 break;
3282 }
3283
arthurhungb89ccb02020-12-30 16:19:01 +08003284 case EventEntry::Type::DRAG: {
3285 const DragEntry& dragEntry = static_cast<const DragEntry&>(eventEntry);
3286 status = connection->inputPublisher.publishDragEvent(dispatchEntry->seq,
3287 dragEntry.id, dragEntry.x,
3288 dragEntry.y,
3289 dragEntry.isExiting);
3290 break;
3291 }
3292
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003293 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003294 case EventEntry::Type::DEVICE_RESET:
3295 case EventEntry::Type::SENSOR: {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003296 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
Dominik Laskowski75788452021-02-09 18:51:25 -08003297 ftl::enum_string(eventEntry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003298 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003299 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003300 }
3301
3302 // Check the result.
3303 if (status) {
3304 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003305 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003306 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003307 "This is unexpected because the wait queue is empty, so the pipe "
3308 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003309 "event to it, status=%s(%d)",
3310 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3311 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003312 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3313 } else {
3314 // Pipe is full and we are waiting for the app to finish process some events
3315 // before sending more events to it.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003316 if (DEBUG_DISPATCH_CYCLE) {
3317 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
3318 "waiting for the application to catch up",
3319 connection->getInputChannelName().c_str());
3320 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003321 }
3322 } else {
3323 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003324 "status=%s(%d)",
3325 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3326 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003327 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3328 }
3329 return;
3330 }
3331
3332 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003333 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
3334 connection->outboundQueue.end(),
3335 dispatchEntry));
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003336 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003337 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003338 if (connection->responsive) {
3339 mAnrTracker.insert(dispatchEntry->timeoutTime,
3340 connection->inputChannel->getConnectionToken());
3341 }
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003342 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003343 }
3344}
3345
chaviw09c8d2d2020-08-24 15:48:26 -07003346std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
3347 size_t size;
3348 switch (event.type) {
3349 case VerifiedInputEvent::Type::KEY: {
3350 size = sizeof(VerifiedKeyEvent);
3351 break;
3352 }
3353 case VerifiedInputEvent::Type::MOTION: {
3354 size = sizeof(VerifiedMotionEvent);
3355 break;
3356 }
3357 }
3358 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
3359 return mHmacKeyManager.sign(start, size);
3360}
3361
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003362const std::array<uint8_t, 32> InputDispatcher::getSignature(
3363 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003364 const int32_t actionMasked = dispatchEntry.resolvedAction & AMOTION_EVENT_ACTION_MASK;
3365 if (actionMasked != AMOTION_EVENT_ACTION_UP && actionMasked != AMOTION_EVENT_ACTION_DOWN) {
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003366 // Only sign events up and down events as the purely move events
3367 // are tied to their up/down counterparts so signing would be redundant.
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003368 return INVALID_HMAC;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003369 }
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003370
3371 VerifiedMotionEvent verifiedEvent =
3372 verifiedMotionEventFromMotionEntry(motionEntry, dispatchEntry.rawTransform);
3373 verifiedEvent.actionMasked = actionMasked;
3374 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
3375 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003376}
3377
3378const std::array<uint8_t, 32> InputDispatcher::getSignature(
3379 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
3380 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
3381 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
3382 verifiedEvent.action = dispatchEntry.resolvedAction;
chaviw09c8d2d2020-08-24 15:48:26 -07003383 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003384}
3385
Michael Wrightd02c5b62014-02-10 15:10:22 -08003386void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003387 const sp<Connection>& connection, uint32_t seq,
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10003388 bool handled, nsecs_t consumeTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003389 if (DEBUG_DISPATCH_CYCLE) {
3390 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
3391 connection->getInputChannelName().c_str(), seq, toString(handled));
3392 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003393
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003394 if (connection->status == Connection::Status::BROKEN ||
3395 connection->status == Connection::Status::ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003396 return;
3397 }
3398
3399 // Notify other system components and prepare to start the next dispatch cycle.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003400 auto command = [this, currentTime, connection, seq, handled, consumeTime]() REQUIRES(mLock) {
3401 doDispatchCycleFinishedCommand(currentTime, connection, seq, handled, consumeTime);
3402 };
3403 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003404}
3405
3406void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003407 const sp<Connection>& connection,
3408 bool notify) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003409 if (DEBUG_DISPATCH_CYCLE) {
3410 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
3411 connection->getInputChannelName().c_str(), toString(notify));
3412 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003413
3414 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003415 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003416 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003417 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003418 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003419
3420 // The connection appears to be unrecoverably broken.
3421 // Ignore already broken or zombie connections.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003422 if (connection->status == Connection::Status::NORMAL) {
3423 connection->status = Connection::Status::BROKEN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003424
3425 if (notify) {
3426 // Notify other system components.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003427 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
3428 connection->getInputChannelName().c_str());
3429
3430 auto command = [this, connection]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003431 scoped_unlock unlock(mLock);
3432 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
3433 };
3434 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003435 }
3436 }
3437}
3438
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003439void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
3440 while (!queue.empty()) {
3441 DispatchEntry* dispatchEntry = queue.front();
3442 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003443 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003444 }
3445}
3446
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003447void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003448 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003449 decrementPendingForegroundDispatches(*(dispatchEntry->eventEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003450 }
3451 delete dispatchEntry;
3452}
3453
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003454int InputDispatcher::handleReceiveCallback(int events, sp<IBinder> connectionToken) {
3455 std::scoped_lock _l(mLock);
3456 sp<Connection> connection = getConnectionLocked(connectionToken);
3457 if (connection == nullptr) {
3458 ALOGW("Received looper callback for unknown input channel token %p. events=0x%x",
3459 connectionToken.get(), events);
3460 return 0; // remove the callback
3461 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003462
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003463 bool notify;
3464 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
3465 if (!(events & ALOOPER_EVENT_INPUT)) {
3466 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
3467 "events=0x%x",
3468 connection->getInputChannelName().c_str(), events);
3469 return 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003470 }
3471
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003472 nsecs_t currentTime = now();
3473 bool gotOne = false;
3474 status_t status = OK;
3475 for (;;) {
3476 Result<InputPublisher::ConsumerResponse> result =
3477 connection->inputPublisher.receiveConsumerResponse();
3478 if (!result.ok()) {
3479 status = result.error().code();
3480 break;
3481 }
3482
3483 if (std::holds_alternative<InputPublisher::Finished>(*result)) {
3484 const InputPublisher::Finished& finish =
3485 std::get<InputPublisher::Finished>(*result);
3486 finishDispatchCycleLocked(currentTime, connection, finish.seq, finish.handled,
3487 finish.consumeTime);
3488 } else if (std::holds_alternative<InputPublisher::Timeline>(*result)) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003489 if (shouldReportMetricsForConnection(*connection)) {
3490 const InputPublisher::Timeline& timeline =
3491 std::get<InputPublisher::Timeline>(*result);
3492 mLatencyTracker
3493 .trackGraphicsLatency(timeline.inputEventId,
3494 connection->inputChannel->getConnectionToken(),
3495 std::move(timeline.graphicsTimeline));
3496 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003497 }
3498 gotOne = true;
3499 }
3500 if (gotOne) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003501 runCommandsLockedInterruptable();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003502 if (status == WOULD_BLOCK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003503 return 1;
3504 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003505 }
3506
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003507 notify = status != DEAD_OBJECT || !connection->monitor;
3508 if (notify) {
3509 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%s(%d)",
3510 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3511 status);
3512 }
3513 } else {
3514 // Monitor channels are never explicitly unregistered.
3515 // We do it automatically when the remote endpoint is closed so don't warn about them.
3516 const bool stillHaveWindowHandle =
3517 getWindowHandleLocked(connection->inputChannel->getConnectionToken()) != nullptr;
3518 notify = !connection->monitor && stillHaveWindowHandle;
3519 if (notify) {
3520 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. events=0x%x",
3521 connection->getInputChannelName().c_str(), events);
3522 }
3523 }
3524
3525 // Remove the channel.
3526 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), notify);
3527 return 0; // remove the callback
Michael Wrightd02c5b62014-02-10 15:10:22 -08003528}
3529
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003530void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08003531 const CancelationOptions& options) {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003532 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +00003533 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003534 }
3535}
3536
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003537void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003538 const CancelationOptions& options) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08003539 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003540 for (const Monitor& monitor : monitors) {
3541 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003542 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003543 }
3544}
3545
Michael Wrightd02c5b62014-02-10 15:10:22 -08003546void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003547 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07003548 sp<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003549 if (connection == nullptr) {
3550 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003551 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003552
3553 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003554}
3555
3556void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
3557 const sp<Connection>& connection, const CancelationOptions& options) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003558 if (connection->status == Connection::Status::BROKEN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003559 return;
3560 }
3561
3562 nsecs_t currentTime = now();
3563
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003564 std::vector<std::unique_ptr<EventEntry>> cancelationEvents =
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07003565 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003566
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003567 if (cancelationEvents.empty()) {
3568 return;
3569 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003570 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
3571 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
3572 "with reality: %s, mode=%d.",
3573 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
3574 options.mode);
3575 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003576
Arthur Hungb3307ee2021-10-14 10:57:37 +00003577 std::string reason = std::string("reason=").append(options.reason);
3578 android_log_event_list(LOGTAG_INPUT_CANCEL)
3579 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
3580
Svet Ganov5d3bc372020-01-26 23:11:07 -08003581 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05003582 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003583 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3584 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003585 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003586 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003587 target.globalScaleFactor = windowInfo->globalScaleFactor;
3588 }
3589 target.inputChannel = connection->inputChannel;
3590 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3591
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003592 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003593 std::unique_ptr<EventEntry> cancelationEventEntry = std::move(cancelationEvents[i]);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003594 switch (cancelationEventEntry->type) {
3595 case EventEntry::Type::KEY: {
3596 logOutboundKeyDetails("cancel - ",
3597 static_cast<const KeyEntry&>(*cancelationEventEntry));
3598 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003599 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003600 case EventEntry::Type::MOTION: {
3601 logOutboundMotionDetails("cancel - ",
3602 static_cast<const MotionEntry&>(*cancelationEventEntry));
3603 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003604 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003605 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003606 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003607 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3608 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08003609 LOG_ALWAYS_FATAL("Canceling %s events is not supported",
Dominik Laskowski75788452021-02-09 18:51:25 -08003610 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003611 break;
3612 }
3613 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003614 case EventEntry::Type::DEVICE_RESET:
3615 case EventEntry::Type::SENSOR: {
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003616 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08003617 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003618 break;
3619 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003620 }
3621
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003622 enqueueDispatchEntryLocked(connection, std::move(cancelationEventEntry), target,
3623 InputTarget::FLAG_DISPATCH_AS_IS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003624 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003625
3626 startDispatchCycleLocked(currentTime, connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003627}
3628
Svet Ganov5d3bc372020-01-26 23:11:07 -08003629void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
3630 const sp<Connection>& connection) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003631 if (connection->status == Connection::Status::BROKEN) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003632 return;
3633 }
3634
3635 nsecs_t currentTime = now();
3636
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003637 std::vector<std::unique_ptr<EventEntry>> downEvents =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003638 connection->inputState.synthesizePointerDownEvents(currentTime);
3639
3640 if (downEvents.empty()) {
3641 return;
3642 }
3643
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003644 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003645 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
3646 connection->getInputChannelName().c_str(), downEvents.size());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003647 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003648
3649 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05003650 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003651 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3652 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003653 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003654 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003655 target.globalScaleFactor = windowInfo->globalScaleFactor;
3656 }
3657 target.inputChannel = connection->inputChannel;
3658 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3659
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003660 for (std::unique_ptr<EventEntry>& downEventEntry : downEvents) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003661 switch (downEventEntry->type) {
3662 case EventEntry::Type::MOTION: {
3663 logOutboundMotionDetails("down - ",
3664 static_cast<const MotionEntry&>(*downEventEntry));
3665 break;
3666 }
3667
3668 case EventEntry::Type::KEY:
3669 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003670 case EventEntry::Type::TOUCH_MODE_CHANGED:
Svet Ganov5d3bc372020-01-26 23:11:07 -08003671 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08003672 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07003673 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003674 case EventEntry::Type::SENSOR:
3675 case EventEntry::Type::DRAG: {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003676 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08003677 ftl::enum_string(downEventEntry->type).c_str());
Svet Ganov5d3bc372020-01-26 23:11:07 -08003678 break;
3679 }
3680 }
3681
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003682 enqueueDispatchEntryLocked(connection, std::move(downEventEntry), target,
3683 InputTarget::FLAG_DISPATCH_AS_IS);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003684 }
3685
3686 startDispatchCycleLocked(currentTime, connection);
3687}
3688
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003689std::unique_ptr<MotionEntry> InputDispatcher::splitMotionEvent(
3690 const MotionEntry& originalMotionEntry, BitSet32 pointerIds) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003691 ALOG_ASSERT(pointerIds.value != 0);
3692
3693 uint32_t splitPointerIndexMap[MAX_POINTERS];
3694 PointerProperties splitPointerProperties[MAX_POINTERS];
3695 PointerCoords splitPointerCoords[MAX_POINTERS];
3696
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003697 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003698 uint32_t splitPointerCount = 0;
3699
3700 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003701 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003702 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003703 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003704 uint32_t pointerId = uint32_t(pointerProperties.id);
3705 if (pointerIds.hasBit(pointerId)) {
3706 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
3707 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
3708 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003709 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003710 splitPointerCount += 1;
3711 }
3712 }
3713
3714 if (splitPointerCount != pointerIds.count()) {
3715 // This is bad. We are missing some of the pointers that we expected to deliver.
3716 // Most likely this indicates that we received an ACTION_MOVE events that has
3717 // different pointer ids than we expected based on the previous ACTION_DOWN
3718 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
3719 // in this way.
3720 ALOGW("Dropping split motion event because the pointer count is %d but "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003721 "we expected there to be %d pointers. This probably means we received "
3722 "a broken sequence of pointer ids from the input device.",
3723 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07003724 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003725 }
3726
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003727 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003728 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003729 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
3730 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003731 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
3732 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003733 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003734 uint32_t pointerId = uint32_t(pointerProperties.id);
3735 if (pointerIds.hasBit(pointerId)) {
3736 if (pointerIds.count() == 1) {
3737 // The first/last pointer went down/up.
3738 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003739 ? AMOTION_EVENT_ACTION_DOWN
arthurhungea3f4fc2020-12-21 23:18:53 +08003740 : (originalMotionEntry.flags & AMOTION_EVENT_FLAG_CANCELED) != 0
3741 ? AMOTION_EVENT_ACTION_CANCEL
3742 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003743 } else {
3744 // A secondary pointer went down/up.
3745 uint32_t splitPointerIndex = 0;
3746 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
3747 splitPointerIndex += 1;
3748 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003749 action = maskedAction |
3750 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003751 }
3752 } else {
3753 // An unrelated pointer changed.
3754 action = AMOTION_EVENT_ACTION_MOVE;
3755 }
3756 }
3757
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003758 int32_t newId = mIdGenerator.nextId();
3759 if (ATRACE_ENABLED()) {
3760 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
3761 ") to MotionEvent(id=0x%" PRIx32 ").",
3762 originalMotionEntry.id, newId);
3763 ATRACE_NAME(message.c_str());
3764 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003765 std::unique_ptr<MotionEntry> splitMotionEntry =
3766 std::make_unique<MotionEntry>(newId, originalMotionEntry.eventTime,
3767 originalMotionEntry.deviceId, originalMotionEntry.source,
3768 originalMotionEntry.displayId,
3769 originalMotionEntry.policyFlags, action,
3770 originalMotionEntry.actionButton,
3771 originalMotionEntry.flags, originalMotionEntry.metaState,
3772 originalMotionEntry.buttonState,
3773 originalMotionEntry.classification,
3774 originalMotionEntry.edgeFlags,
3775 originalMotionEntry.xPrecision,
3776 originalMotionEntry.yPrecision,
3777 originalMotionEntry.xCursorPosition,
3778 originalMotionEntry.yCursorPosition,
3779 originalMotionEntry.downTime, splitPointerCount,
Prabir Pradhan5beda762021-12-10 09:30:08 +00003780 splitPointerProperties, splitPointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003781
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003782 if (originalMotionEntry.injectionState) {
3783 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003784 splitMotionEntry->injectionState->refCount += 1;
3785 }
3786
3787 return splitMotionEntry;
3788}
3789
3790void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003791 if (DEBUG_INBOUND_EVENT_DETAILS) {
3792 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
3793 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003794
Antonio Kantekf16f2832021-09-28 04:39:20 +00003795 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003796 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003797 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003798
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003799 std::unique_ptr<ConfigurationChangedEntry> newEntry =
3800 std::make_unique<ConfigurationChangedEntry>(args->id, args->eventTime);
3801 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003802 } // release lock
3803
3804 if (needWake) {
3805 mLooper->wake();
3806 }
3807}
3808
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003809/**
3810 * If one of the meta shortcuts is detected, process them here:
3811 * Meta + Backspace -> generate BACK
3812 * Meta + Enter -> generate HOME
3813 * This will potentially overwrite keyCode and metaState.
3814 */
3815void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003816 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003817 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
3818 int32_t newKeyCode = AKEYCODE_UNKNOWN;
3819 if (keyCode == AKEYCODE_DEL) {
3820 newKeyCode = AKEYCODE_BACK;
3821 } else if (keyCode == AKEYCODE_ENTER) {
3822 newKeyCode = AKEYCODE_HOME;
3823 }
3824 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003825 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003826 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003827 mReplacedKeys[replacement] = newKeyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003828 keyCode = newKeyCode;
3829 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3830 }
3831 } else if (action == AKEY_EVENT_ACTION_UP) {
3832 // In order to maintain a consistent stream of up and down events, check to see if the key
3833 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
3834 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003835 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003836 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003837 auto replacementIt = mReplacedKeys.find(replacement);
3838 if (replacementIt != mReplacedKeys.end()) {
3839 keyCode = replacementIt->second;
3840 mReplacedKeys.erase(replacementIt);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003841 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3842 }
3843 }
3844}
3845
Michael Wrightd02c5b62014-02-10 15:10:22 -08003846void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003847 if (DEBUG_INBOUND_EVENT_DETAILS) {
3848 ALOGD("notifyKey - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
3849 "policyFlags=0x%x, action=0x%x, "
3850 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
3851 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
3852 args->action, args->flags, args->keyCode, args->scanCode, args->metaState,
3853 args->downTime);
3854 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003855 if (!validateKeyEvent(args->action)) {
3856 return;
3857 }
3858
3859 uint32_t policyFlags = args->policyFlags;
3860 int32_t flags = args->flags;
3861 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07003862 // InputDispatcher tracks and generates key repeats on behalf of
3863 // whatever notifies it, so repeatCount should always be set to 0
3864 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003865 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
3866 policyFlags |= POLICY_FLAG_VIRTUAL;
3867 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
3868 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003869 if (policyFlags & POLICY_FLAG_FUNCTION) {
3870 metaState |= AMETA_FUNCTION_ON;
3871 }
3872
3873 policyFlags |= POLICY_FLAG_TRUSTED;
3874
Michael Wright78f24442014-08-06 15:55:28 -07003875 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003876 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07003877
Michael Wrightd02c5b62014-02-10 15:10:22 -08003878 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003879 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08003880 args->action, flags, keyCode, args->scanCode, metaState, repeatCount,
3881 args->downTime, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003882
Michael Wright2b3c3302018-03-02 17:19:13 +00003883 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003884 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003885 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3886 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003887 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003888 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003889
Antonio Kantekf16f2832021-09-28 04:39:20 +00003890 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003891 { // acquire lock
3892 mLock.lock();
3893
3894 if (shouldSendKeyToInputFilterLocked(args)) {
3895 mLock.unlock();
3896
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003897 policyFlags |= POLICY_FLAG_FILTERED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003898 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3899 return; // event was consumed by the filter
3900 }
3901
3902 mLock.lock();
3903 }
3904
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003905 std::unique_ptr<KeyEntry> newEntry =
3906 std::make_unique<KeyEntry>(args->id, args->eventTime, args->deviceId, args->source,
3907 args->displayId, policyFlags, args->action, flags,
3908 keyCode, args->scanCode, metaState, repeatCount,
3909 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003910
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003911 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003912 mLock.unlock();
3913 } // release lock
3914
3915 if (needWake) {
3916 mLooper->wake();
3917 }
3918}
3919
3920bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
3921 return mInputFilterEnabled;
3922}
3923
3924void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003925 if (DEBUG_INBOUND_EVENT_DETAILS) {
3926 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
3927 "displayId=%" PRId32 ", policyFlags=0x%x, "
3928 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
3929 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
3930 "yCursorPosition=%f, downTime=%" PRId64,
3931 args->id, args->eventTime, args->deviceId, args->source, args->displayId,
3932 args->policyFlags, args->action, args->actionButton, args->flags, args->metaState,
3933 args->buttonState, args->edgeFlags, args->xPrecision, args->yPrecision,
3934 args->xCursorPosition, args->yCursorPosition, args->downTime);
3935 for (uint32_t i = 0; i < args->pointerCount; i++) {
3936 ALOGD(" Pointer %d: id=%d, toolType=%d, "
3937 "x=%f, y=%f, pressure=%f, size=%f, "
3938 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
3939 "orientation=%f",
3940 i, args->pointerProperties[i].id, args->pointerProperties[i].toolType,
3941 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
3942 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
3943 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
3944 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
3945 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
3946 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
3947 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
3948 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
3949 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
3950 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003951 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003952 if (!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
3953 args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003954 return;
3955 }
3956
3957 uint32_t policyFlags = args->policyFlags;
3958 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003959
3960 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08003961 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003962 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3963 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003964 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003965 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003966
Antonio Kantekf16f2832021-09-28 04:39:20 +00003967 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003968 { // acquire lock
3969 mLock.lock();
3970
3971 if (shouldSendMotionToInputFilterLocked(args)) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07003972 ui::Transform displayTransform;
3973 if (const auto it = mDisplayInfos.find(args->displayId); it != mDisplayInfos.end()) {
3974 displayTransform = it->second.transform;
3975 }
3976
Michael Wrightd02c5b62014-02-10 15:10:22 -08003977 mLock.unlock();
3978
3979 MotionEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003980 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
3981 args->action, args->actionButton, args->flags, args->edgeFlags,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07003982 args->metaState, args->buttonState, args->classification,
Prabir Pradhan81420cc2021-09-06 10:28:50 -07003983 displayTransform, args->xPrecision, args->yPrecision,
3984 args->xCursorPosition, args->yCursorPosition, displayTransform,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07003985 args->downTime, args->eventTime, args->pointerCount,
3986 args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003987
3988 policyFlags |= POLICY_FLAG_FILTERED;
3989 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3990 return; // event was consumed by the filter
3991 }
3992
3993 mLock.lock();
3994 }
3995
3996 // Just enqueue a new motion event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003997 std::unique_ptr<MotionEntry> newEntry =
3998 std::make_unique<MotionEntry>(args->id, args->eventTime, args->deviceId,
3999 args->source, args->displayId, policyFlags,
4000 args->action, args->actionButton, args->flags,
4001 args->metaState, args->buttonState,
4002 args->classification, args->edgeFlags,
4003 args->xPrecision, args->yPrecision,
4004 args->xCursorPosition, args->yCursorPosition,
4005 args->downTime, args->pointerCount,
Prabir Pradhan5beda762021-12-10 09:30:08 +00004006 args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004007
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004008 if (args->id != android::os::IInputConstants::INVALID_INPUT_EVENT_ID &&
4009 IdGenerator::getSource(args->id) == IdGenerator::Source::INPUT_READER &&
4010 !mInputFilterEnabled) {
4011 const bool isDown = args->action == AMOTION_EVENT_ACTION_DOWN;
4012 mLatencyTracker.trackListener(args->id, isDown, args->eventTime, args->readTime);
4013 }
4014
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004015 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004016 mLock.unlock();
4017 } // release lock
4018
4019 if (needWake) {
4020 mLooper->wake();
4021 }
4022}
4023
Chris Yef59a2f42020-10-16 12:55:26 -07004024void InputDispatcher::notifySensor(const NotifySensorArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004025 if (DEBUG_INBOUND_EVENT_DETAILS) {
4026 ALOGD("notifySensor - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
4027 " sensorType=%s",
4028 args->id, args->eventTime, args->deviceId, args->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08004029 ftl::enum_string(args->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004030 }
Chris Yef59a2f42020-10-16 12:55:26 -07004031
Antonio Kantekf16f2832021-09-28 04:39:20 +00004032 bool needWake = false;
Chris Yef59a2f42020-10-16 12:55:26 -07004033 { // acquire lock
4034 mLock.lock();
4035
4036 // Just enqueue a new sensor event.
4037 std::unique_ptr<SensorEntry> newEntry =
4038 std::make_unique<SensorEntry>(args->id, args->eventTime, args->deviceId,
4039 args->source, 0 /* policyFlags*/, args->hwTimestamp,
4040 args->sensorType, args->accuracy,
4041 args->accuracyChanged, args->values);
4042
4043 needWake = enqueueInboundEventLocked(std::move(newEntry));
4044 mLock.unlock();
4045 } // release lock
4046
4047 if (needWake) {
4048 mLooper->wake();
4049 }
4050}
4051
Chris Yefb552902021-02-03 17:18:37 -08004052void InputDispatcher::notifyVibratorState(const NotifyVibratorStateArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004053 if (DEBUG_INBOUND_EVENT_DETAILS) {
4054 ALOGD("notifyVibratorState - eventTime=%" PRId64 ", device=%d, isOn=%d", args->eventTime,
4055 args->deviceId, args->isOn);
4056 }
Chris Yefb552902021-02-03 17:18:37 -08004057 mPolicy->notifyVibratorState(args->deviceId, args->isOn);
4058}
4059
Michael Wrightd02c5b62014-02-10 15:10:22 -08004060bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08004061 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004062}
4063
4064void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004065 if (DEBUG_INBOUND_EVENT_DETAILS) {
4066 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
4067 "switchMask=0x%08x",
4068 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
4069 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004070
4071 uint32_t policyFlags = args->policyFlags;
4072 policyFlags |= POLICY_FLAG_TRUSTED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004073 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004074}
4075
4076void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004077 if (DEBUG_INBOUND_EVENT_DETAILS) {
4078 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
4079 args->deviceId);
4080 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004081
Antonio Kantekf16f2832021-09-28 04:39:20 +00004082 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004083 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004084 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004085
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004086 std::unique_ptr<DeviceResetEntry> newEntry =
4087 std::make_unique<DeviceResetEntry>(args->id, args->eventTime, args->deviceId);
4088 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004089 } // release lock
4090
4091 if (needWake) {
4092 mLooper->wake();
4093 }
4094}
4095
Prabir Pradhan7e186182020-11-10 13:56:45 -08004096void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004097 if (DEBUG_INBOUND_EVENT_DETAILS) {
4098 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args->eventTime,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00004099 args->request.enable ? "true" : "false");
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004100 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004101
Antonio Kantekf16f2832021-09-28 04:39:20 +00004102 bool needWake = false;
Prabir Pradhan99987712020-11-10 18:43:05 -08004103 { // acquire lock
4104 std::scoped_lock _l(mLock);
4105 auto entry = std::make_unique<PointerCaptureChangedEntry>(args->id, args->eventTime,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00004106 args->request);
Prabir Pradhan99987712020-11-10 18:43:05 -08004107 needWake = enqueueInboundEventLocked(std::move(entry));
4108 } // release lock
4109
4110 if (needWake) {
4111 mLooper->wake();
4112 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004113}
4114
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004115InputEventInjectionResult InputDispatcher::injectInputEvent(
4116 const InputEvent* event, int32_t injectorPid, int32_t injectorUid,
4117 InputEventInjectionSync syncMode, std::chrono::milliseconds timeout, uint32_t policyFlags) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004118 if (DEBUG_INBOUND_EVENT_DETAILS) {
4119 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
4120 "syncMode=%d, timeout=%lld, policyFlags=0x%08x",
4121 event->getType(), injectorPid, injectorUid, syncMode, timeout.count(), policyFlags);
4122 }
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004123 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004124
4125 policyFlags |= POLICY_FLAG_INJECTED;
4126 if (hasInjectionPermission(injectorPid, injectorUid)) {
4127 policyFlags |= POLICY_FLAG_TRUSTED;
4128 }
4129
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004130 // For all injected events, set device id = VIRTUAL_KEYBOARD_ID. The only exception is events
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004131 // that have gone through the InputFilter. If the event passed through the InputFilter, assign
4132 // the provided device id. If the InputFilter is accessibility, and it modifies or synthesizes
4133 // the injected event, it is responsible for setting POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY.
4134 // For those events, we will set FLAG_IS_ACCESSIBILITY_EVENT to allow apps to distinguish them
4135 // from events that originate from actual hardware.
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004136 int32_t resolvedDeviceId = VIRTUAL_KEYBOARD_ID;
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004137 if (policyFlags & POLICY_FLAG_FILTERED) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004138 resolvedDeviceId = event->getDeviceId();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004139 }
4140
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004141 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004142 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004143 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004144 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
4145 int32_t action = incomingKey.getAction();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004146 if (!validateKeyEvent(action)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004147 return InputEventInjectionResult::FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004148 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004149
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004150 int32_t flags = incomingKey.getFlags();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004151 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4152 flags |= AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4153 }
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004154 int32_t keyCode = incomingKey.getKeyCode();
4155 int32_t metaState = incomingKey.getMetaState();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004156 accelerateMetaShortcuts(resolvedDeviceId, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004157 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004158 KeyEvent keyEvent;
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004159 keyEvent.initialize(incomingKey.getId(), resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004160 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
4161 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
4162 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004163
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004164 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
4165 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00004166 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004167
4168 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
4169 android::base::Timer t;
4170 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
4171 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4172 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
4173 std::to_string(t.duration().count()).c_str());
4174 }
4175 }
4176
4177 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004178 std::unique_ptr<KeyEntry> injectedEntry =
4179 std::make_unique<KeyEntry>(incomingKey.getId(), incomingKey.getEventTime(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004180 resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004181 incomingKey.getDisplayId(), policyFlags, action,
4182 flags, keyCode, incomingKey.getScanCode(), metaState,
4183 incomingKey.getRepeatCount(),
4184 incomingKey.getDownTime());
4185 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004186 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004187 }
4188
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004189 case AINPUT_EVENT_TYPE_MOTION: {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004190 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004191 const int32_t action = motionEvent.getAction();
4192 const bool isPointerEvent =
4193 isFromSource(event->getSource(), AINPUT_SOURCE_CLASS_POINTER);
4194 // If a pointer event has no displayId specified, inject it to the default display.
4195 const uint32_t displayId = isPointerEvent && (event->getDisplayId() == ADISPLAY_ID_NONE)
4196 ? ADISPLAY_ID_DEFAULT
4197 : event->getDisplayId();
4198 const size_t pointerCount = motionEvent.getPointerCount();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004199 const PointerProperties* pointerProperties = motionEvent.getPointerProperties();
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004200 const int32_t actionButton = motionEvent.getActionButton();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004201 int32_t flags = motionEvent.getFlags();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004202 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004203 return InputEventInjectionResult::FAILED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004204 }
4205
4206 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004207 nsecs_t eventTime = motionEvent.getEventTime();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004208 android::base::Timer t;
4209 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
4210 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4211 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
4212 std::to_string(t.duration().count()).c_str());
4213 }
4214 }
4215
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004216 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4217 flags |= AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4218 }
4219
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004220 mLock.lock();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004221 const nsecs_t* sampleEventTimes = motionEvent.getSampleEventTimes();
4222 const PointerCoords* samplePointerCoords = motionEvent.getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004223 std::unique_ptr<MotionEntry> injectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004224 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4225 resolvedDeviceId, motionEvent.getSource(),
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004226 displayId, policyFlags, action, actionButton,
4227 flags, motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004228 motionEvent.getButtonState(),
4229 motionEvent.getClassification(),
4230 motionEvent.getEdgeFlags(),
4231 motionEvent.getXPrecision(),
4232 motionEvent.getYPrecision(),
4233 motionEvent.getRawXCursorPosition(),
4234 motionEvent.getRawYCursorPosition(),
4235 motionEvent.getDownTime(), uint32_t(pointerCount),
Prabir Pradhan5beda762021-12-10 09:30:08 +00004236 pointerProperties, samplePointerCoords);
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004237 transformMotionEntryForInjectionLocked(*injectedEntry, motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004238 injectedEntries.push(std::move(injectedEntry));
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004239 for (size_t i = motionEvent.getHistorySize(); i > 0; i--) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004240 sampleEventTimes += 1;
4241 samplePointerCoords += pointerCount;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004242 std::unique_ptr<MotionEntry> nextInjectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004243 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4244 resolvedDeviceId, motionEvent.getSource(),
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004245 displayId, policyFlags, action, actionButton,
4246 flags, motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004247 motionEvent.getButtonState(),
4248 motionEvent.getClassification(),
4249 motionEvent.getEdgeFlags(),
4250 motionEvent.getXPrecision(),
4251 motionEvent.getYPrecision(),
4252 motionEvent.getRawXCursorPosition(),
4253 motionEvent.getRawYCursorPosition(),
4254 motionEvent.getDownTime(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004255 uint32_t(pointerCount), pointerProperties,
Prabir Pradhan5beda762021-12-10 09:30:08 +00004256 samplePointerCoords);
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004257 transformMotionEntryForInjectionLocked(*nextInjectedEntry,
4258 motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004259 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004260 }
4261 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004262 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004263
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004264 default:
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08004265 ALOGW("Cannot inject %s events", inputEventTypeToString(event->getType()));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004266 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004267 }
4268
4269 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004270 if (syncMode == InputEventInjectionSync::NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004271 injectionState->injectionIsAsync = true;
4272 }
4273
4274 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004275 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004276
4277 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004278 while (!injectedEntries.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004279 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004280 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004281 }
4282
4283 mLock.unlock();
4284
4285 if (needWake) {
4286 mLooper->wake();
4287 }
4288
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004289 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004290 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004291 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004292
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004293 if (syncMode == InputEventInjectionSync::NONE) {
4294 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004295 } else {
4296 for (;;) {
4297 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004298 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004299 break;
4300 }
4301
4302 nsecs_t remainingTimeout = endTime - now();
4303 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004304 if (DEBUG_INJECTION) {
4305 ALOGD("injectInputEvent - Timed out waiting for injection result "
4306 "to become available.");
4307 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004308 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004309 break;
4310 }
4311
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004312 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004313 }
4314
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004315 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
4316 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004317 while (injectionState->pendingForegroundDispatches != 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004318 if (DEBUG_INJECTION) {
4319 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
4320 injectionState->pendingForegroundDispatches);
4321 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004322 nsecs_t remainingTimeout = endTime - now();
4323 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004324 if (DEBUG_INJECTION) {
4325 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
4326 "dispatches to finish.");
4327 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004328 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004329 break;
4330 }
4331
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004332 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004333 }
4334 }
4335 }
4336
4337 injectionState->release();
4338 } // release lock
4339
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004340 if (DEBUG_INJECTION) {
4341 ALOGD("injectInputEvent - Finished with result %d. injectorPid=%d, injectorUid=%d",
4342 injectionResult, injectorPid, injectorUid);
4343 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004344
4345 return injectionResult;
4346}
4347
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004348std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05004349 std::array<uint8_t, 32> calculatedHmac;
4350 std::unique_ptr<VerifiedInputEvent> result;
4351 switch (event.getType()) {
4352 case AINPUT_EVENT_TYPE_KEY: {
4353 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
4354 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
4355 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004356 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05004357 break;
4358 }
4359 case AINPUT_EVENT_TYPE_MOTION: {
4360 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
4361 VerifiedMotionEvent verifiedMotionEvent =
4362 verifiedMotionEventFromMotionEvent(motionEvent);
4363 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004364 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05004365 break;
4366 }
4367 default: {
4368 ALOGE("Cannot verify events of type %" PRId32, event.getType());
4369 return nullptr;
4370 }
4371 }
4372 if (calculatedHmac == INVALID_HMAC) {
4373 return nullptr;
4374 }
4375 if (calculatedHmac != event.getHmac()) {
4376 return nullptr;
4377 }
4378 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004379}
4380
Michael Wrightd02c5b62014-02-10 15:10:22 -08004381bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004382 return injectorUid == 0 ||
4383 mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004384}
4385
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004386void InputDispatcher::setInjectionResult(EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004387 InputEventInjectionResult injectionResult) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004388 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004389 if (injectionState) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004390 if (DEBUG_INJECTION) {
4391 ALOGD("Setting input event injection result to %d. "
4392 "injectorPid=%d, injectorUid=%d",
4393 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
4394 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004395
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004396 if (injectionState->injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004397 // Log the outcome since the injector did not wait for the injection result.
4398 switch (injectionResult) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004399 case InputEventInjectionResult::SUCCEEDED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004400 ALOGV("Asynchronous input event injection succeeded.");
4401 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004402 case InputEventInjectionResult::FAILED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004403 ALOGW("Asynchronous input event injection failed.");
4404 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004405 case InputEventInjectionResult::PERMISSION_DENIED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004406 ALOGW("Asynchronous input event injection permission denied.");
4407 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004408 case InputEventInjectionResult::TIMED_OUT:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004409 ALOGW("Asynchronous input event injection timed out.");
4410 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004411 case InputEventInjectionResult::PENDING:
4412 ALOGE("Setting result to 'PENDING' for asynchronous injection");
4413 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004414 }
4415 }
4416
4417 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004418 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004419 }
4420}
4421
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004422void InputDispatcher::transformMotionEntryForInjectionLocked(
4423 MotionEntry& entry, const ui::Transform& injectedTransform) const {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004424 // Input injection works in the logical display coordinate space, but the input pipeline works
4425 // display space, so we need to transform the injected events accordingly.
4426 const auto it = mDisplayInfos.find(entry.displayId);
4427 if (it == mDisplayInfos.end()) return;
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004428 const auto& transformToDisplay = it->second.transform.inverse() * injectedTransform;
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004429
4430 for (uint32_t i = 0; i < entry.pointerCount; i++) {
4431 PointerCoords& pc = entry.pointerCoords[i];
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004432 // Make a copy of the injected coords. We cannot change them in place because some of them
4433 // are interdependent (for example, X coordinate might depend on the Y coordinate).
4434 PointerCoords injectedCoords = entry.pointerCoords[i];
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004435
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004436 BitSet64 bits(injectedCoords.bits);
4437 while (!bits.isEmpty()) {
4438 const auto axis = static_cast<int32_t>(bits.clearFirstMarkedBit());
4439 const float value =
4440 MotionEvent::calculateTransformedAxisValue(axis, entry.source,
4441 transformToDisplay, injectedCoords);
4442 pc.setAxisValue(axis, value);
4443 }
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004444 }
4445}
4446
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004447void InputDispatcher::incrementPendingForegroundDispatches(EventEntry& entry) {
4448 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004449 if (injectionState) {
4450 injectionState->pendingForegroundDispatches += 1;
4451 }
4452}
4453
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004454void InputDispatcher::decrementPendingForegroundDispatches(EventEntry& entry) {
4455 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004456 if (injectionState) {
4457 injectionState->pendingForegroundDispatches -= 1;
4458
4459 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004460 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004461 }
4462 }
4463}
4464
chaviw98318de2021-05-19 16:45:23 -05004465const std::vector<sp<WindowInfoHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004466 int32_t displayId) const {
chaviw98318de2021-05-19 16:45:23 -05004467 static const std::vector<sp<WindowInfoHandle>> EMPTY_WINDOW_HANDLES;
Vishnu Nairad321cd2020-08-20 16:40:21 -07004468 auto it = mWindowHandlesByDisplay.find(displayId);
4469 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08004470}
4471
chaviw98318de2021-05-19 16:45:23 -05004472sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08004473 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08004474 if (windowHandleToken == nullptr) {
4475 return nullptr;
4476 }
4477
Arthur Hungb92218b2018-08-14 12:00:21 +08004478 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004479 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4480 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004481 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004482 return windowHandle;
4483 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004484 }
4485 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004486 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004487}
4488
chaviw98318de2021-05-19 16:45:23 -05004489sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(const sp<IBinder>& windowHandleToken,
4490 int displayId) const {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004491 if (windowHandleToken == nullptr) {
4492 return nullptr;
4493 }
4494
chaviw98318de2021-05-19 16:45:23 -05004495 for (const sp<WindowInfoHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004496 if (windowHandle->getToken() == windowHandleToken) {
4497 return windowHandle;
4498 }
4499 }
4500 return nullptr;
4501}
4502
chaviw98318de2021-05-19 16:45:23 -05004503sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
4504 const sp<WindowInfoHandle>& windowHandle) const {
Mady Mellor017bcd12020-06-23 19:12:00 +00004505 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004506 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4507 for (const sp<WindowInfoHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08004508 if (handle->getId() == windowHandle->getId() &&
4509 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004510 if (windowHandle->getInfo()->displayId != it.first) {
4511 ALOGE("Found window %s in display %" PRId32
4512 ", but it should belong to display %" PRId32,
4513 windowHandle->getName().c_str(), it.first,
4514 windowHandle->getInfo()->displayId);
4515 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004516 return handle;
Arthur Hungb92218b2018-08-14 12:00:21 +08004517 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004518 }
4519 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004520 return nullptr;
4521}
4522
chaviw98318de2021-05-19 16:45:23 -05004523sp<WindowInfoHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004524 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(displayId);
4525 return getWindowHandleLocked(focusedToken, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004526}
4527
chaviw98318de2021-05-19 16:45:23 -05004528bool InputDispatcher::hasResponsiveConnectionLocked(WindowInfoHandle& windowHandle) const {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004529 sp<Connection> connection = getConnectionLocked(windowHandle.getToken());
4530 const bool noInputChannel =
chaviw98318de2021-05-19 16:45:23 -05004531 windowHandle.getInfo()->inputFeatures.test(WindowInfo::Feature::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004532 if (connection != nullptr && noInputChannel) {
4533 ALOGW("%s has feature NO_INPUT_CHANNEL, but it matched to connection %s",
4534 windowHandle.getName().c_str(), connection->inputChannel->getName().c_str());
4535 return false;
4536 }
4537
4538 if (connection == nullptr) {
4539 if (!noInputChannel) {
4540 ALOGI("Could not find connection for %s", windowHandle.getName().c_str());
4541 }
4542 return false;
4543 }
4544 if (!connection->responsive) {
4545 ALOGW("Window %s is not responsive", windowHandle.getName().c_str());
4546 return false;
4547 }
4548 return true;
4549}
4550
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004551std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
4552 const sp<IBinder>& token) const {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004553 auto connectionIt = mConnectionsByToken.find(token);
4554 if (connectionIt == mConnectionsByToken.end()) {
Robert Carr5c8a0262018-10-03 16:30:44 -07004555 return nullptr;
4556 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004557 return connectionIt->second->inputChannel;
Robert Carr5c8a0262018-10-03 16:30:44 -07004558}
4559
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004560void InputDispatcher::updateWindowHandlesForDisplayLocked(
chaviw98318de2021-05-19 16:45:23 -05004561 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
4562 if (windowInfoHandles.empty()) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004563 // Remove all handles on a display if there are no windows left.
4564 mWindowHandlesByDisplay.erase(displayId);
4565 return;
4566 }
4567
4568 // Since we compare the pointer of input window handles across window updates, we need
4569 // to make sure the handle object for the same window stays unchanged across updates.
chaviw98318de2021-05-19 16:45:23 -05004570 const std::vector<sp<WindowInfoHandle>>& oldHandles = getWindowHandlesLocked(displayId);
4571 std::unordered_map<int32_t /*id*/, sp<WindowInfoHandle>> oldHandlesById;
4572 for (const sp<WindowInfoHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07004573 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004574 }
4575
chaviw98318de2021-05-19 16:45:23 -05004576 std::vector<sp<WindowInfoHandle>> newHandles;
4577 for (const sp<WindowInfoHandle>& handle : windowInfoHandles) {
chaviw98318de2021-05-19 16:45:23 -05004578 const WindowInfo* info = handle->getInfo();
Siarhei Vishniakou64452932020-11-06 17:51:32 -06004579 if (getInputChannelLocked(handle->getToken()) == nullptr) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004580 const bool noInputChannel =
chaviw98318de2021-05-19 16:45:23 -05004581 info->inputFeatures.test(WindowInfo::Feature::NO_INPUT_CHANNEL);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004582 const bool canReceiveInput =
4583 !info->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) ||
4584 !info->inputConfig.test(WindowInfo::InputConfig::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004585 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07004586 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004587 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07004588 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004589 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004590 }
4591
4592 if (info->displayId != displayId) {
4593 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
4594 handle->getName().c_str(), displayId, info->displayId);
4595 continue;
4596 }
4597
Robert Carredd13602020-04-13 17:24:34 -07004598 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
4599 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviw98318de2021-05-19 16:45:23 -05004600 const sp<WindowInfoHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004601 oldHandle->updateFrom(handle);
4602 newHandles.push_back(oldHandle);
4603 } else {
4604 newHandles.push_back(handle);
4605 }
4606 }
4607
4608 // Insert or replace
4609 mWindowHandlesByDisplay[displayId] = newHandles;
4610}
4611
Arthur Hung72d8dc32020-03-28 00:48:39 +00004612void InputDispatcher::setInputWindows(
chaviw98318de2021-05-19 16:45:23 -05004613 const std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>>& handlesPerDisplay) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07004614 // TODO(b/198444055): Remove setInputWindows from InputDispatcher.
Arthur Hung72d8dc32020-03-28 00:48:39 +00004615 { // acquire lock
4616 std::scoped_lock _l(mLock);
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004617 for (const auto& [displayId, handles] : handlesPerDisplay) {
4618 setInputWindowsLocked(handles, displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004619 }
4620 }
4621 // Wake up poll loop since it may need to make new input dispatching choices.
4622 mLooper->wake();
4623}
4624
Arthur Hungb92218b2018-08-14 12:00:21 +08004625/**
4626 * Called from InputManagerService, update window handle list by displayId that can receive input.
4627 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
4628 * If set an empty list, remove all handles from the specific display.
4629 * For focused handle, check if need to change and send a cancel event to previous one.
4630 * For removed handle, check if need to send a cancel event if already in touch.
4631 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00004632void InputDispatcher::setInputWindowsLocked(
chaviw98318de2021-05-19 16:45:23 -05004633 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004634 if (DEBUG_FOCUS) {
4635 std::string windowList;
chaviw98318de2021-05-19 16:45:23 -05004636 for (const sp<WindowInfoHandle>& iwh : windowInfoHandles) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004637 windowList += iwh->getName() + " ";
4638 }
4639 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
4640 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004641
Prabir Pradhand65552b2021-10-07 11:23:50 -07004642 // Check preconditions for new input windows
chaviw98318de2021-05-19 16:45:23 -05004643 for (const sp<WindowInfoHandle>& window : windowInfoHandles) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07004644 const WindowInfo& info = *window->getInfo();
4645
4646 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
4647 const bool noInputWindow = info.inputFeatures.test(WindowInfo::Feature::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004648 if (noInputWindow && window->getToken() != nullptr) {
4649 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
4650 window->getName().c_str());
4651 window->releaseChannel();
4652 }
Prabir Pradhand65552b2021-10-07 11:23:50 -07004653
Prabir Pradhan5c85e052021-12-22 02:27:12 -08004654 // Ensure all spy windows are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004655 LOG_ALWAYS_FATAL_IF(info.isSpy() &&
4656 !info.inputConfig.test(
4657 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhan5c85e052021-12-22 02:27:12 -08004658 "%s has feature SPY, but is not a trusted overlay.",
4659 window->getName().c_str());
4660
Prabir Pradhand65552b2021-10-07 11:23:50 -07004661 // Ensure all stylus interceptors are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004662 LOG_ALWAYS_FATAL_IF(info.interceptsStylus() &&
4663 !info.inputConfig.test(
4664 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhand65552b2021-10-07 11:23:50 -07004665 "%s has feature INTERCEPTS_STYLUS, but is not a trusted overlay.",
4666 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004667 }
4668
Arthur Hung72d8dc32020-03-28 00:48:39 +00004669 // Copy old handles for release if they are no longer present.
chaviw98318de2021-05-19 16:45:23 -05004670 const std::vector<sp<WindowInfoHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004671
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004672 // Save the old windows' orientation by ID before it gets updated.
4673 std::unordered_map<int32_t, uint32_t> oldWindowOrientations;
chaviw98318de2021-05-19 16:45:23 -05004674 for (const sp<WindowInfoHandle>& handle : oldWindowHandles) {
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004675 oldWindowOrientations.emplace(handle->getId(),
4676 handle->getInfo()->transform.getOrientation());
4677 }
4678
chaviw98318de2021-05-19 16:45:23 -05004679 updateWindowHandlesForDisplayLocked(windowInfoHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004680
chaviw98318de2021-05-19 16:45:23 -05004681 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Vishnu Nair958da932020-08-21 17:12:37 -07004682 if (mLastHoverWindowHandle &&
4683 std::find(windowHandles.begin(), windowHandles.end(), mLastHoverWindowHandle) ==
4684 windowHandles.end()) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004685 mLastHoverWindowHandle = nullptr;
4686 }
4687
Vishnu Nairc519ff72021-01-21 08:23:08 -08004688 std::optional<FocusResolver::FocusChanges> changes =
4689 mFocusResolver.setInputWindows(displayId, windowHandles);
4690 if (changes) {
4691 onFocusChangedLocked(*changes);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004692 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004693
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004694 std::unordered_map<int32_t, TouchState>::iterator stateIt =
4695 mTouchStatesByDisplay.find(displayId);
4696 if (stateIt != mTouchStatesByDisplay.end()) {
4697 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00004698 for (size_t i = 0; i < state.windows.size();) {
4699 TouchedWindow& touchedWindow = state.windows[i];
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004700 if (getWindowHandleLocked(touchedWindow.windowHandle) == nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004701 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004702 ALOGD("Touched window was removed: %s in display %" PRId32,
4703 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004704 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004705 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00004706 getInputChannelLocked(touchedWindow.windowHandle->getToken());
4707 if (touchedInputChannel != nullptr) {
4708 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4709 "touched window was removed");
4710 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004711 // Since we are about to drop the touch, cancel the events for the wallpaper as
4712 // well.
4713 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND &&
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004714 touchedWindow.windowHandle->getInfo()->inputConfig.test(
4715 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004716 sp<WindowInfoHandle> wallpaper = state.getWallpaperWindow();
4717 if (wallpaper != nullptr) {
4718 sp<Connection> wallpaperConnection =
4719 getConnectionLocked(wallpaper->getToken());
Siarhei Vishniakou2b030972021-11-18 10:01:27 -08004720 if (wallpaperConnection != nullptr) {
4721 synthesizeCancelationEventsForConnectionLocked(wallpaperConnection,
4722 options);
4723 }
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004724 }
4725 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004726 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004727 state.windows.erase(state.windows.begin() + i);
4728 } else {
4729 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004730 }
4731 }
arthurhungb89ccb02020-12-30 16:19:01 +08004732
arthurhung6d4bed92021-03-17 11:59:33 +08004733 // If drag window is gone, it would receive a cancel event and broadcast the DRAG_END. We
arthurhungb89ccb02020-12-30 16:19:01 +08004734 // could just clear the state here.
arthurhung6d4bed92021-03-17 11:59:33 +08004735 if (mDragState &&
4736 std::find(windowHandles.begin(), windowHandles.end(), mDragState->dragWindow) ==
arthurhungb89ccb02020-12-30 16:19:01 +08004737 windowHandles.end()) {
arthurhung6d4bed92021-03-17 11:59:33 +08004738 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08004739 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004740 }
Arthur Hung25e2af12020-03-26 12:58:37 +00004741
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00004742 // Determine if the orientation of any of the input windows have changed, and cancel all
4743 // pointer events if necessary.
4744 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
4745 const sp<WindowInfoHandle> newWindowHandle = getWindowHandleLocked(oldWindowHandle);
4746 if (newWindowHandle != nullptr &&
4747 newWindowHandle->getInfo()->transform.getOrientation() !=
4748 oldWindowOrientations[oldWindowHandle->getId()]) {
4749 std::shared_ptr<InputChannel> inputChannel =
4750 getInputChannelLocked(newWindowHandle->getToken());
4751 if (inputChannel != nullptr) {
4752 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4753 "touched window's orientation changed");
4754 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004755 }
4756 }
4757 }
4758
Arthur Hung72d8dc32020-03-28 00:48:39 +00004759 // Release information for windows that are no longer present.
4760 // This ensures that unused input channels are released promptly.
4761 // Otherwise, they might stick around until the window handle is destroyed
4762 // which might not happen until the next GC.
chaviw98318de2021-05-19 16:45:23 -05004763 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004764 if (getWindowHandleLocked(oldWindowHandle) == nullptr) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004765 if (DEBUG_FOCUS) {
4766 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00004767 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004768 oldWindowHandle->releaseChannel();
Arthur Hung25e2af12020-03-26 12:58:37 +00004769 }
chaviw291d88a2019-02-14 10:33:58 -08004770 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004771}
4772
4773void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07004774 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004775 if (DEBUG_FOCUS) {
4776 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
4777 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
4778 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004779 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004780 std::scoped_lock _l(mLock);
Vishnu Nair599f1412021-06-21 10:39:58 -07004781 setFocusedApplicationLocked(displayId, inputApplicationHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004782 } // release lock
4783
4784 // Wake up poll loop since it may need to make new input dispatching choices.
4785 mLooper->wake();
4786}
4787
Vishnu Nair599f1412021-06-21 10:39:58 -07004788void InputDispatcher::setFocusedApplicationLocked(
4789 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
4790 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
4791 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
4792
4793 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
4794 return; // This application is already focused. No need to wake up or change anything.
4795 }
4796
4797 // Set the new application handle.
4798 if (inputApplicationHandle != nullptr) {
4799 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
4800 } else {
4801 mFocusedApplicationHandlesByDisplay.erase(displayId);
4802 }
4803
4804 // No matter what the old focused application was, stop waiting on it because it is
4805 // no longer focused.
4806 resetNoFocusedWindowTimeoutLocked();
4807}
4808
Tiger Huang721e26f2018-07-24 22:26:19 +08004809/**
4810 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
4811 * the display not specified.
4812 *
4813 * We track any unreleased events for each window. If a window loses the ability to receive the
4814 * released event, we will send a cancel event to it. So when the focused display is changed, we
4815 * cancel all the unreleased display-unspecified events for the focused window on the old focused
4816 * display. The display-specified events won't be affected.
4817 */
4818void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004819 if (DEBUG_FOCUS) {
4820 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
4821 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004822 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004823 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08004824
4825 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004826 sp<IBinder> oldFocusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08004827 mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07004828 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004829 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07004830 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08004831 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004832 CancelationOptions
4833 options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
4834 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004835 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08004836 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
4837 }
4838 }
4839 mFocusedDisplayId = displayId;
4840
Chris Ye3c2d6f52020-08-09 10:39:48 -07004841 // Find new focused window and validate
Vishnu Nairc519ff72021-01-21 08:23:08 -08004842 sp<IBinder> newFocusedWindowToken = mFocusResolver.getFocusedWindowToken(displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00004843 sendFocusChangedCommandLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08004844
Vishnu Nairad321cd2020-08-20 16:40:21 -07004845 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08004846 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairc519ff72021-01-21 08:23:08 -08004847 if (mFocusResolver.hasFocusedWindowTokens()) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004848 ALOGE("But another display has a focused window\n%s",
Vishnu Nairc519ff72021-01-21 08:23:08 -08004849 mFocusResolver.dumpFocusedWindows().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08004850 }
4851 }
4852 }
4853
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004854 if (DEBUG_FOCUS) {
4855 logDispatchStateLocked();
4856 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004857 } // release lock
4858
4859 // Wake up poll loop since it may need to make new input dispatching choices.
4860 mLooper->wake();
4861}
4862
Michael Wrightd02c5b62014-02-10 15:10:22 -08004863void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004864 if (DEBUG_FOCUS) {
4865 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
4866 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004867
4868 bool changed;
4869 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004870 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004871
4872 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
4873 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004874 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004875 }
4876
4877 if (mDispatchEnabled && !enabled) {
4878 resetAndDropEverythingLocked("dispatcher is being disabled");
4879 }
4880
4881 mDispatchEnabled = enabled;
4882 mDispatchFrozen = frozen;
4883 changed = true;
4884 } else {
4885 changed = false;
4886 }
4887
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004888 if (DEBUG_FOCUS) {
4889 logDispatchStateLocked();
4890 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004891 } // release lock
4892
4893 if (changed) {
4894 // Wake up poll loop since it may need to make new input dispatching choices.
4895 mLooper->wake();
4896 }
4897}
4898
4899void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004900 if (DEBUG_FOCUS) {
4901 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
4902 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004903
4904 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004905 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004906
4907 if (mInputFilterEnabled == enabled) {
4908 return;
4909 }
4910
4911 mInputFilterEnabled = enabled;
4912 resetAndDropEverythingLocked("input filter is being enabled or disabled");
4913 } // release lock
4914
4915 // Wake up poll loop since there might be work to do to drop everything.
4916 mLooper->wake();
4917}
4918
Antonio Kantekea47acb2021-12-23 12:41:25 -08004919bool InputDispatcher::setInTouchMode(bool inTouchMode, int32_t pid, int32_t uid,
4920 bool hasPermission) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00004921 bool needWake = false;
4922 {
4923 std::scoped_lock lock(mLock);
4924 if (mInTouchMode == inTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08004925 return false;
Antonio Kantekf16f2832021-09-28 04:39:20 +00004926 }
4927 if (DEBUG_TOUCH_MODE) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08004928 ALOGD("Request to change touch mode from %s to %s (calling pid=%d, uid=%d, "
4929 "hasPermission=%s)",
4930 toString(mInTouchMode), toString(inTouchMode), pid, uid, toString(hasPermission));
4931 }
4932 if (!hasPermission) {
4933 const sp<IBinder> focusedToken =
4934 mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
4935
4936 // TODO(b/198487159): if no window is currently focused, then we need to check the last
4937 // interacted window (within 1 second timeout). We should allow touch mode change
4938 // if the last interacted window owner's pid/uid match the calling ones.
4939 if (focusedToken == nullptr) {
4940 return false;
4941 }
4942 const sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(focusedToken);
4943 if (windowHandle == nullptr) {
4944 return false;
4945 }
4946 const WindowInfo* windowInfo = windowHandle->getInfo();
4947 if (pid != windowInfo->ownerPid || uid != windowInfo->ownerUid) {
4948 return false;
4949 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00004950 }
4951
4952 // TODO(b/198499018): Store touch mode per display.
4953 mInTouchMode = inTouchMode;
4954
Antonio Kantekf16f2832021-09-28 04:39:20 +00004955 auto entry = std::make_unique<TouchModeEntry>(mIdGenerator.nextId(), now(), inTouchMode);
4956 needWake = enqueueInboundEventLocked(std::move(entry));
4957 } // release lock
4958
4959 if (needWake) {
4960 mLooper->wake();
4961 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08004962 return true;
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08004963}
4964
Bernardo Rufinoea97d182020-08-19 14:43:14 +01004965void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
4966 if (opacity < 0 || opacity > 1) {
4967 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
4968 return;
4969 }
4970
4971 std::scoped_lock lock(mLock);
4972 mMaximumObscuringOpacityForTouch = opacity;
4973}
4974
4975void InputDispatcher::setBlockUntrustedTouchesMode(BlockUntrustedTouchesMode mode) {
4976 std::scoped_lock lock(mLock);
4977 mBlockUntrustedTouchesMode = mode;
4978}
4979
Arthur Hungabbb9d82021-09-01 14:52:30 +00004980std::pair<TouchState*, TouchedWindow*> InputDispatcher::findTouchStateAndWindowLocked(
4981 const sp<IBinder>& token) {
4982 for (auto& [displayId, state] : mTouchStatesByDisplay) {
4983 for (TouchedWindow& w : state.windows) {
4984 if (w.windowHandle->getToken() == token) {
4985 return std::make_pair(&state, &w);
4986 }
4987 }
4988 }
4989 return std::make_pair(nullptr, nullptr);
4990}
4991
arthurhungb89ccb02020-12-30 16:19:01 +08004992bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken,
4993 bool isDragDrop) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004994 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004995 if (DEBUG_FOCUS) {
4996 ALOGD("Trivial transfer to same window.");
4997 }
chaviwfbe5d9c2018-12-26 12:23:37 -08004998 return true;
4999 }
5000
Michael Wrightd02c5b62014-02-10 15:10:22 -08005001 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005002 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005003
Arthur Hungabbb9d82021-09-01 14:52:30 +00005004 // Find the target touch state and touched window by fromToken.
5005 auto [state, touchedWindow] = findTouchStateAndWindowLocked(fromToken);
5006 if (state == nullptr || touchedWindow == nullptr) {
5007 ALOGD("Focus transfer failed because from window is not being touched.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005008 return false;
5009 }
Arthur Hungabbb9d82021-09-01 14:52:30 +00005010
5011 const int32_t displayId = state->displayId;
5012 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(toToken, displayId);
5013 if (toWindowHandle == nullptr) {
5014 ALOGW("Cannot transfer focus because to window not found.");
5015 return false;
5016 }
5017
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005018 if (DEBUG_FOCUS) {
5019 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
Arthur Hungabbb9d82021-09-01 14:52:30 +00005020 touchedWindow->windowHandle->getName().c_str(),
5021 toWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005022 }
5023
Arthur Hungabbb9d82021-09-01 14:52:30 +00005024 // Erase old window.
5025 int32_t oldTargetFlags = touchedWindow->targetFlags;
5026 BitSet32 pointerIds = touchedWindow->pointerIds;
5027 state->removeWindowByToken(fromToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005028
Arthur Hungabbb9d82021-09-01 14:52:30 +00005029 // Add new window.
5030 int32_t newTargetFlags = oldTargetFlags &
5031 (InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_SPLIT |
5032 InputTarget::FLAG_DISPATCH_AS_IS);
5033 state->addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005034
Arthur Hungabbb9d82021-09-01 14:52:30 +00005035 // Store the dragging window.
5036 if (isDragDrop) {
5037 mDragState = std::make_unique<DragState>(toWindowHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005038 }
5039
Arthur Hungabbb9d82021-09-01 14:52:30 +00005040 // Synthesize cancel for old window and down for new window.
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005041 sp<Connection> fromConnection = getConnectionLocked(fromToken);
5042 sp<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005043 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08005044 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005045 CancelationOptions
5046 options(CancelationOptions::CANCEL_POINTER_EVENTS,
5047 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005048 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Svet Ganov5d3bc372020-01-26 23:11:07 -08005049 synthesizePointerDownEventsForConnectionLocked(toConnection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005050 }
5051
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005052 if (DEBUG_FOCUS) {
5053 logDispatchStateLocked();
5054 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005055 } // release lock
5056
5057 // Wake up poll loop since it may need to make new input dispatching choices.
5058 mLooper->wake();
5059 return true;
5060}
5061
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005062// Binder call
5063bool InputDispatcher::transferTouch(const sp<IBinder>& destChannelToken) {
5064 sp<IBinder> fromToken;
5065 { // acquire lock
5066 std::scoped_lock _l(mLock);
5067
Arthur Hungabbb9d82021-09-01 14:52:30 +00005068 auto it = std::find_if(mTouchStatesByDisplay.begin(), mTouchStatesByDisplay.end(),
5069 [](const auto& pair) { return pair.second.windows.size() == 1; });
5070 if (it == mTouchStatesByDisplay.end()) {
5071 ALOGW("Cannot transfer touch state because there is no exact window being touched");
5072 return false;
5073 }
5074 const int32_t displayId = it->first;
5075 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(destChannelToken, displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005076 if (toWindowHandle == nullptr) {
5077 ALOGW("Could not find window associated with token=%p", destChannelToken.get());
5078 return false;
5079 }
5080
Arthur Hungabbb9d82021-09-01 14:52:30 +00005081 TouchState& state = it->second;
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005082 const TouchedWindow& touchedWindow = state.windows[0];
5083 fromToken = touchedWindow.windowHandle->getToken();
5084 } // release lock
5085
5086 return transferTouchFocus(fromToken, destChannelToken);
5087}
5088
Michael Wrightd02c5b62014-02-10 15:10:22 -08005089void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005090 if (DEBUG_FOCUS) {
5091 ALOGD("Resetting and dropping all events (%s).", reason);
5092 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005093
5094 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
5095 synthesizeCancelationEventsForAllConnectionsLocked(options);
5096
5097 resetKeyRepeatLocked();
5098 releasePendingEventLocked();
5099 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005100 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005101
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005102 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08005103 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005104 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07005105 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005106}
5107
5108void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005109 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005110 dumpDispatchStateLocked(dump);
5111
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005112 std::istringstream stream(dump);
5113 std::string line;
5114
5115 while (std::getline(stream, line, '\n')) {
5116 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005117 }
5118}
5119
Prabir Pradhan99987712020-11-10 18:43:05 -08005120std::string InputDispatcher::dumpPointerCaptureStateLocked() {
5121 std::string dump;
5122
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005123 dump += StringPrintf(INDENT "Pointer Capture Requested: %s\n",
5124 toString(mCurrentPointerCaptureRequest.enable));
Prabir Pradhan99987712020-11-10 18:43:05 -08005125
5126 std::string windowName = "None";
5127 if (mWindowTokenWithPointerCapture) {
chaviw98318de2021-05-19 16:45:23 -05005128 const sp<WindowInfoHandle> captureWindowHandle =
Prabir Pradhan99987712020-11-10 18:43:05 -08005129 getWindowHandleLocked(mWindowTokenWithPointerCapture);
5130 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
5131 : "token has capture without window";
5132 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005133 dump += StringPrintf(INDENT "Current Window with Pointer Capture: %s\n", windowName.c_str());
Prabir Pradhan99987712020-11-10 18:43:05 -08005134
5135 return dump;
5136}
5137
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005138void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07005139 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
5140 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
5141 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08005142 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005143
Tiger Huang721e26f2018-07-24 22:26:19 +08005144 if (!mFocusedApplicationHandlesByDisplay.empty()) {
5145 dump += StringPrintf(INDENT "FocusedApplications:\n");
5146 for (auto& it : mFocusedApplicationHandlesByDisplay) {
5147 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07005148 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005149 const std::chrono::duration timeout =
5150 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005151 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005152 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005153 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08005154 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005155 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08005156 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005157 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005158
Vishnu Nairc519ff72021-01-21 08:23:08 -08005159 dump += mFocusResolver.dump();
Prabir Pradhan99987712020-11-10 18:43:05 -08005160 dump += dumpPointerCaptureStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005161
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005162 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005163 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005164 for (const std::pair<int32_t, TouchState>& pair : mTouchStatesByDisplay) {
5165 const TouchState& state = pair.second;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005166 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005167 state.displayId, toString(state.down), toString(state.split),
5168 state.deviceId, state.source);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005169 if (!state.windows.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005170 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08005171 for (size_t i = 0; i < state.windows.size(); i++) {
5172 const TouchedWindow& touchedWindow = state.windows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005173 dump += StringPrintf(INDENT4
5174 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
5175 i, touchedWindow.windowHandle->getName().c_str(),
5176 touchedWindow.pointerIds.value, touchedWindow.targetFlags);
Jeff Brownf086ddb2014-02-11 14:28:48 -08005177 }
5178 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005179 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08005180 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005181 }
5182 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005183 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005184 }
5185
arthurhung6d4bed92021-03-17 11:59:33 +08005186 if (mDragState) {
5187 dump += StringPrintf(INDENT "DragState:\n");
5188 mDragState->dump(dump, INDENT2);
5189 }
5190
Arthur Hungb92218b2018-08-14 12:00:21 +08005191 if (!mWindowHandlesByDisplay.empty()) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005192 for (const auto& [displayId, windowHandles] : mWindowHandlesByDisplay) {
5193 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", displayId);
5194 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
5195 const auto& displayInfo = it->second;
5196 dump += StringPrintf(INDENT2 "logicalSize=%dx%d\n", displayInfo.logicalWidth,
5197 displayInfo.logicalHeight);
5198 displayInfo.transform.dump(dump, "transform", INDENT4);
5199 } else {
5200 dump += INDENT2 "No DisplayInfo found!\n";
5201 }
5202
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005203 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08005204 dump += INDENT2 "Windows:\n";
5205 for (size_t i = 0; i < windowHandles.size(); i++) {
chaviw98318de2021-05-19 16:45:23 -05005206 const sp<WindowInfoHandle>& windowHandle = windowHandles[i];
5207 const WindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005208
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005209 dump += StringPrintf(INDENT3 "%zu: name='%s', id=%" PRId32 ", displayId=%d, "
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005210 "inputConfig=%s, alpha=%.2f, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005211 "frame=[%d,%d][%d,%d], globalScale=%f, "
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005212 "applicationInfo.name=%s, "
5213 "applicationInfo.token=%s, "
chaviw1ff3d1e2020-07-01 15:53:47 -07005214 "touchableRegion=",
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005215 i, windowInfo->name.c_str(), windowInfo->id,
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005216 windowInfo->displayId,
5217 windowInfo->inputConfig.string().c_str(),
5218 windowInfo->alpha, windowInfo->frameLeft,
5219 windowInfo->frameTop, windowInfo->frameRight,
5220 windowInfo->frameBottom, windowInfo->globalScaleFactor,
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005221 windowInfo->applicationInfo.name.c_str(),
5222 toString(windowInfo->applicationInfo.token).c_str());
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00005223 dump += dumpRegion(windowInfo->touchableRegion);
Michael Wright44753b12020-07-08 13:48:11 +01005224 dump += StringPrintf(", inputFeatures=%s",
5225 windowInfo->inputFeatures.string().c_str());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005226 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%" PRId64
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005227 "ms, hasToken=%s, "
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005228 "touchOcclusionMode=%s\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005229 windowInfo->ownerPid, windowInfo->ownerUid,
Bernardo Rufinoc2f1fad2020-11-04 17:30:57 +00005230 millis(windowInfo->dispatchingTimeout),
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00005231 toString(windowInfo->token != nullptr),
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005232 toString(windowInfo->touchOcclusionMode).c_str());
chaviw85b44202020-07-24 11:46:21 -07005233 windowInfo->transform.dump(dump, "transform", INDENT4);
Arthur Hungb92218b2018-08-14 12:00:21 +08005234 }
5235 } else {
5236 dump += INDENT2 "Windows: <none>\n";
5237 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005238 }
5239 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08005240 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005241 }
5242
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005243 if (!mGlobalMonitorsByDisplay.empty()) {
5244 for (const auto& [displayId, monitors] : mGlobalMonitorsByDisplay) {
5245 dump += StringPrintf(INDENT "Global monitors on display %d:\n", displayId);
Michael Wright3dd60e22019-03-27 22:06:44 +00005246 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005247 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005248 } else {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005249 dump += INDENT "Global Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005250 }
5251
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005252 const nsecs_t currentTime = now();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005253
5254 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005255 if (!mRecentQueue.empty()) {
5256 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005257 for (std::shared_ptr<EventEntry>& entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005258 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005259 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005260 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005261 }
5262 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005263 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005264 }
5265
5266 // Dump event currently being dispatched.
5267 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005268 dump += INDENT "PendingEvent:\n";
5269 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005270 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005271 dump += StringPrintf(", age=%" PRId64 "ms\n",
5272 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005273 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005274 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005275 }
5276
5277 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005278 if (!mInboundQueue.empty()) {
5279 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005280 for (std::shared_ptr<EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005281 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005282 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005283 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005284 }
5285 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005286 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005287 }
5288
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005289 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005290 dump += INDENT "ReplacedKeys:\n";
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005291 for (const std::pair<KeyReplacement, int32_t>& pair : mReplacedKeys) {
5292 const KeyReplacement& replacement = pair.first;
5293 int32_t newKeyCode = pair.second;
5294 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005295 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07005296 }
5297 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005298 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07005299 }
5300
Prabir Pradhancef936d2021-07-21 16:17:52 +00005301 if (!mCommandQueue.empty()) {
5302 dump += StringPrintf(INDENT "CommandQueue: size=%zu\n", mCommandQueue.size());
5303 } else {
5304 dump += INDENT "CommandQueue: <empty>\n";
5305 }
5306
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005307 if (!mConnectionsByToken.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005308 dump += INDENT "Connections:\n";
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005309 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005310 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005311 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005312 connection->inputChannel->getFd().get(),
5313 connection->getInputChannelName().c_str(),
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005314 connection->getWindowName().c_str(),
5315 ftl::enum_string(connection->status).c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005316 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005317
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005318 if (!connection->outboundQueue.empty()) {
5319 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
5320 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005321 dump += dumpQueue(connection->outboundQueue, currentTime);
5322
Michael Wrightd02c5b62014-02-10 15:10:22 -08005323 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005324 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005325 }
5326
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005327 if (!connection->waitQueue.empty()) {
5328 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
5329 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005330 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005331 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005332 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005333 }
5334 }
5335 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005336 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005337 }
5338
5339 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005340 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
5341 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005342 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005343 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005344 }
5345
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005346 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005347 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
5348 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
5349 ns2ms(mConfig.keyRepeatTimeout));
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00005350 dump += mLatencyTracker.dump(INDENT2);
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +00005351 dump += mLatencyAggregator.dump(INDENT2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005352}
5353
Michael Wright3dd60e22019-03-27 22:06:44 +00005354void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
5355 const size_t numMonitors = monitors.size();
5356 for (size_t i = 0; i < numMonitors; i++) {
5357 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005358 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005359 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
5360 dump += "\n";
5361 }
5362}
5363
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005364class LooperEventCallback : public LooperCallback {
5365public:
5366 LooperEventCallback(std::function<int(int events)> callback) : mCallback(callback) {}
5367 int handleEvent(int /*fd*/, int events, void* /*data*/) override { return mCallback(events); }
5368
5369private:
5370 std::function<int(int events)> mCallback;
5371};
5372
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005373Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(const std::string& name) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005374 if (DEBUG_CHANNEL_CREATION) {
5375 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
5376 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005377
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005378 std::unique_ptr<InputChannel> serverChannel;
Garfield Tan15601662020-09-22 15:32:38 -07005379 std::unique_ptr<InputChannel> clientChannel;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005380 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Garfield Tan15601662020-09-22 15:32:38 -07005381
5382 if (result) {
5383 return base::Error(result) << "Failed to open input channel pair with name " << name;
5384 }
5385
Michael Wrightd02c5b62014-02-10 15:10:22 -08005386 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005387 std::scoped_lock _l(mLock);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005388 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005389 int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005390 sp<Connection> connection =
5391 new Connection(std::move(serverChannel), false /*monitor*/, mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005392
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005393 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5394 ALOGE("Created a new connection, but the token %p is already known", token.get());
5395 }
5396 mConnectionsByToken.emplace(token, connection);
5397
5398 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5399 this, std::placeholders::_1, token);
5400
5401 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, new LooperEventCallback(callback), nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005402 } // release lock
5403
5404 // Wake the looper because some connections have changed.
5405 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005406 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005407}
5408
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005409Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(int32_t displayId,
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005410 const std::string& name,
5411 int32_t pid) {
Garfield Tan15601662020-09-22 15:32:38 -07005412 std::shared_ptr<InputChannel> serverChannel;
5413 std::unique_ptr<InputChannel> clientChannel;
5414 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
5415 if (result) {
5416 return base::Error(result) << "Failed to open input channel pair with name " << name;
5417 }
5418
Michael Wright3dd60e22019-03-27 22:06:44 +00005419 { // acquire lock
5420 std::scoped_lock _l(mLock);
5421
5422 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07005423 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
5424 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00005425 }
5426
Garfield Tan15601662020-09-22 15:32:38 -07005427 sp<Connection> connection = new Connection(serverChannel, true /*monitor*/, mIdGenerator);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005428 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005429 const int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005430
5431 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5432 ALOGE("Created a new connection, but the token %p is already known", token.get());
5433 }
5434 mConnectionsByToken.emplace(token, connection);
5435 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5436 this, std::placeholders::_1, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005437
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005438 mGlobalMonitorsByDisplay[displayId].emplace_back(serverChannel, pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005439
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005440 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, new LooperEventCallback(callback), nullptr);
Michael Wright3dd60e22019-03-27 22:06:44 +00005441 }
Garfield Tan15601662020-09-22 15:32:38 -07005442
Michael Wright3dd60e22019-03-27 22:06:44 +00005443 // Wake the looper because some connections have changed.
5444 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005445 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005446}
5447
Garfield Tan15601662020-09-22 15:32:38 -07005448status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005449 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005450 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005451
Garfield Tan15601662020-09-22 15:32:38 -07005452 status_t status = removeInputChannelLocked(connectionToken, false /*notify*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005453 if (status) {
5454 return status;
5455 }
5456 } // release lock
5457
5458 // Wake the poll loop because removing the connection may have changed the current
5459 // synchronization state.
5460 mLooper->wake();
5461 return OK;
5462}
5463
Garfield Tan15601662020-09-22 15:32:38 -07005464status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
5465 bool notify) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005466 sp<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005467 if (connection == nullptr) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005468 // Connection can be removed via socket hang up or an explicit call to 'removeInputChannel'
Michael Wrightd02c5b62014-02-10 15:10:22 -08005469 return BAD_VALUE;
5470 }
5471
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005472 removeConnectionLocked(connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07005473
Michael Wrightd02c5b62014-02-10 15:10:22 -08005474 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005475 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005476 }
5477
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005478 mLooper->removeFd(connection->inputChannel->getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005479
5480 nsecs_t currentTime = now();
5481 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
5482
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005483 connection->status = Connection::Status::ZOMBIE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005484 return OK;
5485}
5486
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005487void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005488 for (auto it = mGlobalMonitorsByDisplay.begin(); it != mGlobalMonitorsByDisplay.end();) {
5489 auto& [displayId, monitors] = *it;
5490 std::erase_if(monitors, [connectionToken](const Monitor& monitor) {
5491 return monitor.inputChannel->getConnectionToken() == connectionToken;
5492 });
Michael Wright3dd60e22019-03-27 22:06:44 +00005493
Michael Wright3dd60e22019-03-27 22:06:44 +00005494 if (monitors.empty()) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005495 it = mGlobalMonitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005496 } else {
5497 ++it;
5498 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005499 }
5500}
5501
Michael Wright3dd60e22019-03-27 22:06:44 +00005502status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005503 std::scoped_lock _l(mLock);
Michael Wright3dd60e22019-03-27 22:06:44 +00005504
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005505 const std::shared_ptr<InputChannel> requestingChannel = getInputChannelLocked(token);
5506 if (!requestingChannel) {
5507 ALOGW("Attempted to pilfer pointers from an un-registered channel or invalid token");
5508 return BAD_VALUE;
Michael Wright3dd60e22019-03-27 22:06:44 +00005509 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005510
5511 auto [statePtr, windowPtr] = findTouchStateAndWindowLocked(token);
5512 if (statePtr == nullptr || windowPtr == nullptr || !statePtr->down) {
5513 ALOGW("Attempted to pilfer points from a channel without any on-going pointer streams."
5514 " Ignoring.");
5515 return BAD_VALUE;
5516 }
5517
5518 TouchState& state = *statePtr;
5519
5520 // Send cancel events to all the input channels we're stealing from.
5521 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
5522 "input channel stole pointer stream");
5523 options.deviceId = state.deviceId;
5524 options.displayId = state.displayId;
5525 std::string canceledWindows;
5526 for (const TouchedWindow& window : state.windows) {
5527 const std::shared_ptr<InputChannel> channel =
5528 getInputChannelLocked(window.windowHandle->getToken());
5529 if (channel != nullptr && channel->getConnectionToken() != token) {
5530 synthesizeCancelationEventsForInputChannelLocked(channel, options);
5531 canceledWindows += canceledWindows.empty() ? "[" : ", ";
5532 canceledWindows += channel->getName();
5533 }
5534 }
5535 canceledWindows += canceledWindows.empty() ? "[]" : "]";
5536 ALOGI("Channel %s is stealing touch from %s", requestingChannel->getName().c_str(),
5537 canceledWindows.c_str());
5538
Prabir Pradhane680f9b2022-02-04 04:24:00 -08005539 // Prevent the gesture from being sent to any other windows.
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005540 state.filterWindowsExcept(token);
Prabir Pradhane680f9b2022-02-04 04:24:00 -08005541 state.preventNewTargets = true;
Michael Wright3dd60e22019-03-27 22:06:44 +00005542 return OK;
5543}
5544
Prabir Pradhan99987712020-11-10 18:43:05 -08005545void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
5546 { // acquire lock
5547 std::scoped_lock _l(mLock);
5548 if (DEBUG_FOCUS) {
chaviw98318de2021-05-19 16:45:23 -05005549 const sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(windowToken);
Prabir Pradhan99987712020-11-10 18:43:05 -08005550 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
5551 windowHandle != nullptr ? windowHandle->getName().c_str()
5552 : "token without window");
5553 }
5554
Vishnu Nairc519ff72021-01-21 08:23:08 -08005555 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08005556 if (focusedToken != windowToken) {
5557 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
5558 enabled ? "enable" : "disable");
5559 return;
5560 }
5561
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005562 if (enabled == mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08005563 ALOGW("Ignoring request to %s Pointer Capture: "
5564 "window has %s requested pointer capture.",
5565 enabled ? "enable" : "disable", enabled ? "already" : "not");
5566 return;
5567 }
5568
Christine Franksb768bb42021-11-29 12:11:31 -08005569 if (enabled) {
5570 if (std::find(mIneligibleDisplaysForPointerCapture.begin(),
5571 mIneligibleDisplaysForPointerCapture.end(),
5572 mFocusedDisplayId) != mIneligibleDisplaysForPointerCapture.end()) {
5573 ALOGW("Ignoring request to enable Pointer Capture: display is not eligible");
5574 return;
5575 }
5576 }
5577
Prabir Pradhan99987712020-11-10 18:43:05 -08005578 setPointerCaptureLocked(enabled);
5579 } // release lock
5580
5581 // Wake the thread to process command entries.
5582 mLooper->wake();
5583}
5584
Christine Franksb768bb42021-11-29 12:11:31 -08005585void InputDispatcher::setDisplayEligibilityForPointerCapture(int32_t displayId, bool isEligible) {
5586 { // acquire lock
5587 std::scoped_lock _l(mLock);
5588 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
5589 if (!isEligible) {
5590 mIneligibleDisplaysForPointerCapture.push_back(displayId);
5591 }
5592 } // release lock
5593}
5594
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005595std::optional<int32_t> InputDispatcher::findMonitorPidByTokenLocked(const sp<IBinder>& token) {
5596 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005597 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005598 if (monitor.inputChannel->getConnectionToken() == token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005599 return monitor.pid;
Michael Wright3dd60e22019-03-27 22:06:44 +00005600 }
5601 }
5602 }
5603 return std::nullopt;
5604}
5605
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005606sp<Connection> InputDispatcher::getConnectionLocked(const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005607 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005608 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08005609 }
5610
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005611 for (const auto& [token, connection] : mConnectionsByToken) {
5612 if (token == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005613 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005614 }
5615 }
Robert Carr4e670e52018-08-15 13:26:12 -07005616
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005617 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005618}
5619
Siarhei Vishniakouad991402020-10-28 11:40:09 -05005620std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
5621 sp<Connection> connection = getConnectionLocked(connectionToken);
5622 if (connection == nullptr) {
5623 return "<nullptr>";
5624 }
5625 return connection->getInputChannelName();
5626}
5627
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005628void InputDispatcher::removeConnectionLocked(const sp<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005629 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005630 mConnectionsByToken.erase(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005631}
5632
Prabir Pradhancef936d2021-07-21 16:17:52 +00005633void InputDispatcher::doDispatchCycleFinishedCommand(nsecs_t finishTime,
5634 const sp<Connection>& connection, uint32_t seq,
5635 bool handled, nsecs_t consumeTime) {
5636 // Handle post-event policy actions.
5637 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
5638 if (dispatchEntryIt == connection->waitQueue.end()) {
5639 return;
5640 }
5641 DispatchEntry* dispatchEntry = *dispatchEntryIt;
5642 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
5643 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
5644 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
5645 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
5646 }
5647 if (shouldReportFinishedEvent(*dispatchEntry, *connection)) {
5648 mLatencyTracker.trackFinishedEvent(dispatchEntry->eventEntry->id,
5649 connection->inputChannel->getConnectionToken(),
5650 dispatchEntry->deliveryTime, consumeTime, finishTime);
5651 }
5652
5653 bool restartEvent;
5654 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
5655 KeyEntry& keyEntry = static_cast<KeyEntry&>(*(dispatchEntry->eventEntry));
5656 restartEvent =
5657 afterKeyEventLockedInterruptable(connection, dispatchEntry, keyEntry, handled);
5658 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
5659 MotionEntry& motionEntry = static_cast<MotionEntry&>(*(dispatchEntry->eventEntry));
5660 restartEvent = afterMotionEventLockedInterruptable(connection, dispatchEntry, motionEntry,
5661 handled);
5662 } else {
5663 restartEvent = false;
5664 }
5665
5666 // Dequeue the event and start the next cycle.
5667 // Because the lock might have been released, it is possible that the
5668 // contents of the wait queue to have been drained, so we need to double-check
5669 // a few things.
5670 dispatchEntryIt = connection->findWaitQueueEntry(seq);
5671 if (dispatchEntryIt != connection->waitQueue.end()) {
5672 dispatchEntry = *dispatchEntryIt;
5673 connection->waitQueue.erase(dispatchEntryIt);
5674 const sp<IBinder>& connectionToken = connection->inputChannel->getConnectionToken();
5675 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
5676 if (!connection->responsive) {
5677 connection->responsive = isConnectionResponsive(*connection);
5678 if (connection->responsive) {
5679 // The connection was unresponsive, and now it's responsive.
5680 processConnectionResponsiveLocked(*connection);
5681 }
5682 }
5683 traceWaitQueueLength(*connection);
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005684 if (restartEvent && connection->status == Connection::Status::NORMAL) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005685 connection->outboundQueue.push_front(dispatchEntry);
5686 traceOutboundQueueLength(*connection);
5687 } else {
5688 releaseDispatchEntry(dispatchEntry);
5689 }
5690 }
5691
5692 // Start the next dispatch cycle for this connection.
5693 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005694}
5695
Prabir Pradhancef936d2021-07-21 16:17:52 +00005696void InputDispatcher::sendFocusChangedCommandLocked(const sp<IBinder>& oldToken,
5697 const sp<IBinder>& newToken) {
5698 auto command = [this, oldToken, newToken]() REQUIRES(mLock) {
5699 scoped_unlock unlock(mLock);
5700 mPolicy->notifyFocusChanged(oldToken, newToken);
5701 };
5702 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005703}
5704
Prabir Pradhancef936d2021-07-21 16:17:52 +00005705void InputDispatcher::sendDropWindowCommandLocked(const sp<IBinder>& token, float x, float y) {
5706 auto command = [this, token, x, y]() REQUIRES(mLock) {
5707 scoped_unlock unlock(mLock);
5708 mPolicy->notifyDropWindow(token, x, y);
5709 };
5710 postCommandLocked(std::move(command));
Robert Carrf759f162018-11-13 12:57:11 -08005711}
5712
Prabir Pradhancef936d2021-07-21 16:17:52 +00005713void InputDispatcher::sendUntrustedTouchCommandLocked(const std::string& obscuringPackage) {
5714 auto command = [this, obscuringPackage]() REQUIRES(mLock) {
5715 scoped_unlock unlock(mLock);
5716 mPolicy->notifyUntrustedTouch(obscuringPackage);
5717 };
5718 postCommandLocked(std::move(command));
arthurhungf452d0b2021-01-06 00:19:52 +08005719}
5720
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005721void InputDispatcher::onAnrLocked(const sp<Connection>& connection) {
5722 if (connection == nullptr) {
5723 LOG_ALWAYS_FATAL("Caller must check for nullness");
5724 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005725 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
5726 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005727 if (connection->waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005728 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005729 connection->inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005730 return;
5731 }
5732 /**
5733 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
5734 * may not be the one that caused the timeout to occur. One possibility is that window timeout
5735 * has changed. This could cause newer entries to time out before the already dispatched
5736 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
5737 * processes the events linearly. So providing information about the oldest entry seems to be
5738 * most useful.
5739 */
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005740 DispatchEntry* oldestEntry = *connection->waitQueue.begin();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005741 const nsecs_t currentWait = now() - oldestEntry->deliveryTime;
5742 std::string reason =
5743 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005744 connection->inputChannel->getName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005745 ns2ms(currentWait),
5746 oldestEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005747 sp<IBinder> connectionToken = connection->inputChannel->getConnectionToken();
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06005748 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005749
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005750 processConnectionUnresponsiveLocked(*connection, std::move(reason));
5751
5752 // Stop waking up for events on this connection, it is already unresponsive
5753 cancelEventsForAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005754}
5755
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005756void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
5757 std::string reason =
5758 StringPrintf("%s does not have a focused window", application->getName().c_str());
5759 updateLastAnrStateLocked(*application, reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005760
Prabir Pradhancef936d2021-07-21 16:17:52 +00005761 auto command = [this, application = std::move(application)]() REQUIRES(mLock) {
5762 scoped_unlock unlock(mLock);
5763 mPolicy->notifyNoFocusedWindowAnr(application);
5764 };
5765 postCommandLocked(std::move(command));
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00005766}
5767
chaviw98318de2021-05-19 16:45:23 -05005768void InputDispatcher::updateLastAnrStateLocked(const sp<WindowInfoHandle>& window,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005769 const std::string& reason) {
5770 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
5771 updateLastAnrStateLocked(windowLabel, reason);
5772}
5773
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005774void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
5775 const std::string& reason) {
5776 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005777 updateLastAnrStateLocked(windowLabel, reason);
5778}
5779
5780void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
5781 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005782 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07005783 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005784 struct tm tm;
5785 localtime_r(&t, &tm);
5786 char timestr[64];
5787 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005788 mLastAnrState.clear();
5789 mLastAnrState += INDENT "ANR:\n";
5790 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005791 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
5792 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005793 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005794}
5795
Prabir Pradhancef936d2021-07-21 16:17:52 +00005796void InputDispatcher::doInterceptKeyBeforeDispatchingCommand(const sp<IBinder>& focusedWindowToken,
5797 KeyEntry& entry) {
5798 const KeyEvent event = createKeyEvent(entry);
5799 nsecs_t delay = 0;
5800 { // release lock
5801 scoped_unlock unlock(mLock);
5802 android::base::Timer t;
5803 delay = mPolicy->interceptKeyBeforeDispatching(focusedWindowToken, &event,
5804 entry.policyFlags);
5805 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
5806 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
5807 std::to_string(t.duration().count()).c_str());
5808 }
5809 } // acquire lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08005810
5811 if (delay < 0) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005812 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
Prabir Pradhancef936d2021-07-21 16:17:52 +00005813 } else if (delay == 0) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005814 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005815 } else {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005816 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
5817 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005818 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005819}
5820
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005821void InputDispatcher::sendMonitorUnresponsiveCommandLocked(int32_t pid, std::string reason) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005822 auto command = [this, pid, reason = std::move(reason)]() REQUIRES(mLock) {
5823 scoped_unlock unlock(mLock);
5824 mPolicy->notifyMonitorUnresponsive(pid, reason);
5825 };
5826 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005827}
5828
Prabir Pradhancef936d2021-07-21 16:17:52 +00005829void InputDispatcher::sendWindowUnresponsiveCommandLocked(const sp<IBinder>& token,
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005830 std::string reason) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005831 auto command = [this, token, reason = std::move(reason)]() REQUIRES(mLock) {
5832 scoped_unlock unlock(mLock);
5833 mPolicy->notifyWindowUnresponsive(token, reason);
5834 };
5835 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005836}
5837
5838void InputDispatcher::sendMonitorResponsiveCommandLocked(int32_t pid) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005839 auto command = [this, pid]() REQUIRES(mLock) {
5840 scoped_unlock unlock(mLock);
5841 mPolicy->notifyMonitorResponsive(pid);
5842 };
5843 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005844}
5845
Prabir Pradhancef936d2021-07-21 16:17:52 +00005846void InputDispatcher::sendWindowResponsiveCommandLocked(const sp<IBinder>& connectionToken) {
5847 auto command = [this, connectionToken]() REQUIRES(mLock) {
5848 scoped_unlock unlock(mLock);
5849 mPolicy->notifyWindowResponsive(connectionToken);
5850 };
5851 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005852}
5853
5854/**
5855 * Tell the policy that a connection has become unresponsive so that it can start ANR.
5856 * Check whether the connection of interest is a monitor or a window, and add the corresponding
5857 * command entry to the command queue.
5858 */
5859void InputDispatcher::processConnectionUnresponsiveLocked(const Connection& connection,
5860 std::string reason) {
5861 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
5862 if (connection.monitor) {
5863 ALOGW("Monitor %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
5864 reason.c_str());
5865 std::optional<int32_t> pid = findMonitorPidByTokenLocked(connectionToken);
5866 if (!pid.has_value()) {
5867 ALOGE("Could not find unresponsive monitor for connection %s",
5868 connection.inputChannel->getName().c_str());
5869 return;
5870 }
5871 sendMonitorUnresponsiveCommandLocked(pid.value(), std::move(reason));
5872 return;
5873 }
5874 // If not a monitor, must be a window
5875 ALOGW("Window %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
5876 reason.c_str());
5877 sendWindowUnresponsiveCommandLocked(connectionToken, std::move(reason));
5878}
5879
5880/**
5881 * Tell the policy that a connection has become responsive so that it can stop ANR.
5882 */
5883void InputDispatcher::processConnectionResponsiveLocked(const Connection& connection) {
5884 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
5885 if (connection.monitor) {
5886 std::optional<int32_t> pid = findMonitorPidByTokenLocked(connectionToken);
5887 if (!pid.has_value()) {
5888 ALOGE("Could not find responsive monitor for connection %s",
5889 connection.inputChannel->getName().c_str());
5890 return;
5891 }
5892 sendMonitorResponsiveCommandLocked(pid.value());
5893 return;
5894 }
5895 // If not a monitor, must be a window
5896 sendWindowResponsiveCommandLocked(connectionToken);
5897}
5898
Prabir Pradhancef936d2021-07-21 16:17:52 +00005899bool InputDispatcher::afterKeyEventLockedInterruptable(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005900 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005901 KeyEntry& keyEntry, bool handled) {
5902 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005903 if (!handled) {
5904 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005905 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005906 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005907 return false;
5908 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005909
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005910 // Get the fallback key state.
5911 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005912 int32_t originalKeyCode = keyEntry.keyCode;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005913 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005914 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005915 connection->inputState.removeFallbackKey(originalKeyCode);
5916 }
5917
5918 if (handled || !dispatchEntry->hasForegroundTarget()) {
5919 // If the application handles the original key for which we previously
5920 // generated a fallback or if the window is not a foreground window,
5921 // then cancel the associated fallback key, if any.
5922 if (fallbackKeyCode != -1) {
5923 // Dispatch the unhandled key to the policy with the cancel flag.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005924 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
5925 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
5926 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
5927 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount,
5928 keyEntry.policyFlags);
5929 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005930 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005931 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005932
5933 mLock.unlock();
5934
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005935 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005936 keyEntry.policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005937
5938 mLock.lock();
5939
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005940 // Cancel the fallback key.
5941 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005942 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005943 "application handled the original non-fallback key "
5944 "or is no longer a foreground target, "
5945 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005946 options.keyCode = fallbackKeyCode;
5947 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005948 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005949 connection->inputState.removeFallbackKey(originalKeyCode);
5950 }
5951 } else {
5952 // If the application did not handle a non-fallback key, first check
5953 // that we are in a good state to perform unhandled key event processing
5954 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005955 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005956 if (fallbackKeyCode == -1 && !initialDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005957 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
5958 ALOGD("Unhandled key event: Skipping unhandled key event processing "
5959 "since this is not an initial down. "
5960 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
5961 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
5962 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005963 return false;
5964 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005965
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005966 // Dispatch the unhandled key to the policy.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005967 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
5968 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
5969 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
5970 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
5971 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005972 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005973
5974 mLock.unlock();
5975
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005976 bool fallback =
5977 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005978 &event, keyEntry.policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005979
5980 mLock.lock();
5981
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005982 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005983 connection->inputState.removeFallbackKey(originalKeyCode);
5984 return false;
5985 }
5986
5987 // Latch the fallback keycode for this key on an initial down.
5988 // The fallback keycode cannot change at any other point in the lifecycle.
5989 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005990 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005991 fallbackKeyCode = event.getKeyCode();
5992 } else {
5993 fallbackKeyCode = AKEYCODE_UNKNOWN;
5994 }
5995 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
5996 }
5997
5998 ALOG_ASSERT(fallbackKeyCode != -1);
5999
6000 // Cancel the fallback key if the policy decides not to send it anymore.
6001 // We will continue to dispatch the key to the policy but we will no
6002 // longer dispatch a fallback key to the application.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006003 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
6004 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006005 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6006 if (fallback) {
6007 ALOGD("Unhandled key event: Policy requested to send key %d"
6008 "as a fallback for %d, but on the DOWN it had requested "
6009 "to send %d instead. Fallback canceled.",
6010 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
6011 } else {
6012 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
6013 "but on the DOWN it had requested to send %d. "
6014 "Fallback canceled.",
6015 originalKeyCode, fallbackKeyCode);
6016 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006017 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006018
6019 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
6020 "canceling fallback, policy no longer desires it");
6021 options.keyCode = fallbackKeyCode;
6022 synthesizeCancelationEventsForConnectionLocked(connection, options);
6023
6024 fallback = false;
6025 fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006026 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006027 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006028 }
6029 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006030
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006031 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6032 {
6033 std::string msg;
6034 const KeyedVector<int32_t, int32_t>& fallbackKeys =
6035 connection->inputState.getFallbackKeys();
6036 for (size_t i = 0; i < fallbackKeys.size(); i++) {
6037 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
6038 }
6039 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
6040 fallbackKeys.size(), msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006041 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006042 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006043
6044 if (fallback) {
6045 // Restart the dispatch cycle using the fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006046 keyEntry.eventTime = event.getEventTime();
6047 keyEntry.deviceId = event.getDeviceId();
6048 keyEntry.source = event.getSource();
6049 keyEntry.displayId = event.getDisplayId();
6050 keyEntry.flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
6051 keyEntry.keyCode = fallbackKeyCode;
6052 keyEntry.scanCode = event.getScanCode();
6053 keyEntry.metaState = event.getMetaState();
6054 keyEntry.repeatCount = event.getRepeatCount();
6055 keyEntry.downTime = event.getDownTime();
6056 keyEntry.syntheticRepeat = false;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006057
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006058 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6059 ALOGD("Unhandled key event: Dispatching fallback key. "
6060 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
6061 originalKeyCode, fallbackKeyCode, keyEntry.metaState);
6062 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006063 return true; // restart the event
6064 } else {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006065 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6066 ALOGD("Unhandled key event: No fallback key.");
6067 }
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006068
6069 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006070 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006071 }
6072 }
6073 return false;
6074}
6075
Prabir Pradhancef936d2021-07-21 16:17:52 +00006076bool InputDispatcher::afterMotionEventLockedInterruptable(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006077 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006078 MotionEntry& motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006079 return false;
6080}
6081
Michael Wrightd02c5b62014-02-10 15:10:22 -08006082void InputDispatcher::traceInboundQueueLengthLocked() {
6083 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07006084 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006085 }
6086}
6087
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006088void InputDispatcher::traceOutboundQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006089 if (ATRACE_ENABLED()) {
6090 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006091 snprintf(counterName, sizeof(counterName), "oq:%s", connection.getWindowName().c_str());
6092 ATRACE_INT(counterName, connection.outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006093 }
6094}
6095
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006096void InputDispatcher::traceWaitQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006097 if (ATRACE_ENABLED()) {
6098 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006099 snprintf(counterName, sizeof(counterName), "wq:%s", connection.getWindowName().c_str());
6100 ATRACE_INT(counterName, connection.waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006101 }
6102}
6103
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006104void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006105 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006106
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006107 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08006108 dumpDispatchStateLocked(dump);
6109
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006110 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006111 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006112 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006113 }
6114}
6115
6116void InputDispatcher::monitor() {
6117 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006118 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006119 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006120 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006121}
6122
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006123/**
6124 * Wake up the dispatcher and wait until it processes all events and commands.
6125 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
6126 * this method can be safely called from any thread, as long as you've ensured that
6127 * the work you are interested in completing has already been queued.
6128 */
6129bool InputDispatcher::waitForIdle() {
6130 /**
6131 * Timeout should represent the longest possible time that a device might spend processing
6132 * events and commands.
6133 */
6134 constexpr std::chrono::duration TIMEOUT = 100ms;
6135 std::unique_lock lock(mLock);
6136 mLooper->wake();
6137 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
6138 return result == std::cv_status::no_timeout;
6139}
6140
Vishnu Naire798b472020-07-23 13:52:21 -07006141/**
6142 * Sets focus to the window identified by the token. This must be called
6143 * after updating any input window handles.
6144 *
6145 * Params:
6146 * request.token - input channel token used to identify the window that should gain focus.
6147 * request.focusedToken - the token that the caller expects currently to be focused. If the
6148 * specified token does not match the currently focused window, this request will be dropped.
6149 * If the specified focused token matches the currently focused window, the call will succeed.
6150 * Set this to "null" if this call should succeed no matter what the currently focused token is.
6151 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
6152 * when requesting the focus change. This determines which request gets
6153 * precedence if there is a focus change request from another source such as pointer down.
6154 */
Vishnu Nair958da932020-08-21 17:12:37 -07006155void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
6156 { // acquire lock
6157 std::scoped_lock _l(mLock);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006158 std::optional<FocusResolver::FocusChanges> changes =
6159 mFocusResolver.setFocusedWindow(request, getWindowHandlesLocked(request.displayId));
6160 if (changes) {
6161 onFocusChangedLocked(*changes);
Vishnu Nair958da932020-08-21 17:12:37 -07006162 }
6163 } // release lock
6164 // Wake up poll loop since it may need to make new input dispatching choices.
6165 mLooper->wake();
6166}
6167
Vishnu Nairc519ff72021-01-21 08:23:08 -08006168void InputDispatcher::onFocusChangedLocked(const FocusResolver::FocusChanges& changes) {
6169 if (changes.oldFocus) {
6170 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(changes.oldFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006171 if (focusedInputChannel) {
6172 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
6173 "focus left window");
6174 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006175 enqueueFocusEventLocked(changes.oldFocus, false /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006176 }
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006177 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08006178 if (changes.newFocus) {
6179 enqueueFocusEventLocked(changes.newFocus, true /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006180 }
6181
Prabir Pradhan99987712020-11-10 18:43:05 -08006182 // If a window has pointer capture, then it must have focus. We need to ensure that this
6183 // contract is upheld when pointer capture is being disabled due to a loss of window focus.
6184 // If the window loses focus before it loses pointer capture, then the window can be in a state
6185 // where it has pointer capture but not focus, violating the contract. Therefore we must
6186 // dispatch the pointer capture event before the focus event. Since focus events are added to
6187 // the front of the queue (above), we add the pointer capture event to the front of the queue
6188 // after the focus events are added. This ensures the pointer capture event ends up at the
6189 // front.
6190 disablePointerCaptureForcedLocked();
6191
Vishnu Nairc519ff72021-01-21 08:23:08 -08006192 if (mFocusedDisplayId == changes.displayId) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006193 sendFocusChangedCommandLocked(changes.oldFocus, changes.newFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006194 }
6195}
Vishnu Nair958da932020-08-21 17:12:37 -07006196
Prabir Pradhan99987712020-11-10 18:43:05 -08006197void InputDispatcher::disablePointerCaptureForcedLocked() {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006198 if (!mCurrentPointerCaptureRequest.enable && !mWindowTokenWithPointerCapture) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006199 return;
6200 }
6201
6202 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
6203
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006204 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006205 setPointerCaptureLocked(false);
6206 }
6207
6208 if (!mWindowTokenWithPointerCapture) {
6209 // No need to send capture changes because no window has capture.
6210 return;
6211 }
6212
6213 if (mPendingEvent != nullptr) {
6214 // Move the pending event to the front of the queue. This will give the chance
6215 // for the pending event to be dropped if it is a captured event.
6216 mInboundQueue.push_front(mPendingEvent);
6217 mPendingEvent = nullptr;
6218 }
6219
6220 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006221 mCurrentPointerCaptureRequest);
Prabir Pradhan99987712020-11-10 18:43:05 -08006222 mInboundQueue.push_front(std::move(entry));
6223}
6224
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006225void InputDispatcher::setPointerCaptureLocked(bool enable) {
6226 mCurrentPointerCaptureRequest.enable = enable;
6227 mCurrentPointerCaptureRequest.seq++;
6228 auto command = [this, request = mCurrentPointerCaptureRequest]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006229 scoped_unlock unlock(mLock);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006230 mPolicy->setPointerCapture(request);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006231 };
6232 postCommandLocked(std::move(command));
Prabir Pradhan99987712020-11-10 18:43:05 -08006233}
6234
Vishnu Nair599f1412021-06-21 10:39:58 -07006235void InputDispatcher::displayRemoved(int32_t displayId) {
6236 { // acquire lock
6237 std::scoped_lock _l(mLock);
6238 // Set an empty list to remove all handles from the specific display.
6239 setInputWindowsLocked(/* window handles */ {}, displayId);
6240 setFocusedApplicationLocked(displayId, nullptr);
6241 // Call focus resolver to clean up stale requests. This must be called after input windows
6242 // have been removed for the removed display.
6243 mFocusResolver.displayRemoved(displayId);
Christine Franksb768bb42021-11-29 12:11:31 -08006244 // Reset pointer capture eligibility, regardless of previous state.
6245 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
Vishnu Nair599f1412021-06-21 10:39:58 -07006246 } // release lock
6247
6248 // Wake up poll loop since it may need to make new input dispatching choices.
6249 mLooper->wake();
6250}
6251
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006252void InputDispatcher::onWindowInfosChanged(const std::vector<WindowInfo>& windowInfos,
6253 const std::vector<DisplayInfo>& displayInfos) {
chaviw15fab6f2021-06-07 14:15:52 -05006254 // The listener sends the windows as a flattened array. Separate the windows by display for
6255 // more convenient parsing.
6256 std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>> handlesPerDisplay;
chaviw15fab6f2021-06-07 14:15:52 -05006257 for (const auto& info : windowInfos) {
6258 handlesPerDisplay.emplace(info.displayId, std::vector<sp<WindowInfoHandle>>());
6259 handlesPerDisplay[info.displayId].push_back(new WindowInfoHandle(info));
6260 }
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006261
6262 { // acquire lock
6263 std::scoped_lock _l(mLock);
6264 mDisplayInfos.clear();
6265 for (const auto& displayInfo : displayInfos) {
6266 mDisplayInfos.emplace(displayInfo.displayId, displayInfo);
6267 }
6268
6269 for (const auto& [displayId, handles] : handlesPerDisplay) {
6270 setInputWindowsLocked(handles, displayId);
6271 }
6272 }
6273 // Wake up poll loop since it may need to make new input dispatching choices.
6274 mLooper->wake();
chaviw15fab6f2021-06-07 14:15:52 -05006275}
6276
Vishnu Nair062a8672021-09-03 16:07:44 -07006277bool InputDispatcher::shouldDropInput(
6278 const EventEntry& entry, const sp<android::gui::WindowInfoHandle>& windowHandle) const {
6279 if (windowHandle->getInfo()->inputFeatures.test(WindowInfo::Feature::DROP_INPUT) ||
6280 (windowHandle->getInfo()->inputFeatures.test(WindowInfo::Feature::DROP_INPUT_IF_OBSCURED) &&
6281 isWindowObscuredLocked(windowHandle))) {
6282 ALOGW("Dropping %s event targeting %s as requested by input feature %s on display "
6283 "%" PRId32 ".",
6284 ftl::enum_string(entry.type).c_str(), windowHandle->getName().c_str(),
6285 windowHandle->getInfo()->inputFeatures.string().c_str(),
6286 windowHandle->getInfo()->displayId);
6287 return true;
6288 }
6289 return false;
6290}
6291
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006292void InputDispatcher::DispatcherWindowListener::onWindowInfosChanged(
6293 const std::vector<gui::WindowInfo>& windowInfos,
6294 const std::vector<DisplayInfo>& displayInfos) {
6295 mDispatcher.onWindowInfosChanged(windowInfos, displayInfos);
6296}
6297
Arthur Hungdfd528e2021-12-08 13:23:04 +00006298void InputDispatcher::cancelCurrentTouch() {
6299 {
6300 std::scoped_lock _l(mLock);
6301 ALOGD("Canceling all ongoing pointer gestures on all displays.");
6302 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
6303 "cancel current touch");
6304 synthesizeCancelationEventsForAllConnectionsLocked(options);
6305
6306 mTouchStatesByDisplay.clear();
6307 mLastHoverWindowHandle.clear();
6308 }
6309 // Wake up poll loop since there might be work to do.
6310 mLooper->wake();
6311}
6312
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006313void InputDispatcher::setMonitorDispatchingTimeoutForTest(std::chrono::nanoseconds timeout) {
6314 std::scoped_lock _l(mLock);
6315 mMonitorDispatchingTimeout = timeout;
6316}
6317
Garfield Tane84e6f92019-08-29 17:28:41 -07006318} // namespace android::inputdispatcher