1 /* 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 #ifndef _UI_INPUT_DISPATCHER_H 18 #define _UI_INPUT_DISPATCHER_H 19 20 #include "AnrTracker.h" 21 #include "CancelationOptions.h" 22 #include "DragState.h" 23 #include "Entry.h" 24 #include "FocusResolver.h" 25 #include "InjectionState.h" 26 #include "InputDispatcherConfiguration.h" 27 #include "InputDispatcherInterface.h" 28 #include "InputDispatcherPolicyInterface.h" 29 #include "InputState.h" 30 #include "InputTarget.h" 31 #include "InputThread.h" 32 #include "LatencyAggregator.h" 33 #include "LatencyTracker.h" 34 #include "Monitor.h" 35 #include "TouchState.h" 36 #include "TouchedWindow.h" 37 38 #include <attestation/HmacKeyManager.h> 39 #include <gui/InputApplication.h> 40 #include <gui/WindowInfo.h> 41 #include <input/Input.h> 42 #include <input/InputTransport.h> 43 #include <limits.h> 44 #include <stddef.h> 45 #include <ui/Region.h> 46 #include <unistd.h> 47 #include <utils/BitSet.h> 48 #include <utils/Looper.h> 49 #include <utils/Timers.h> 50 #include <utils/threads.h> 51 #include <condition_variable> 52 #include <deque> 53 #include <optional> 54 #include <unordered_map> 55 #include <unordered_set> 56 57 #include <InputListener.h> 58 #include <InputReporterInterface.h> 59 #include <gui/WindowInfosListener.h> 60 61 namespace android::inputdispatcher { 62 63 class Connection; 64 65 /* Dispatches events to input targets. Some functions of the input dispatcher, such as 66 * identifying input targets, are controlled by a separate policy object. 67 * 68 * IMPORTANT INVARIANT: 69 * Because the policy can potentially block or cause re-entrance into the input dispatcher, 70 * the input dispatcher never calls into the policy while holding its internal locks. 71 * The implementation is also carefully designed to recover from scenarios such as an 72 * input channel becoming unregistered while identifying input targets or processing timeouts. 73 * 74 * Methods marked 'Locked' must be called with the lock acquired. 75 * 76 * Methods marked 'LockedInterruptible' must be called with the lock acquired but 77 * may during the course of their execution release the lock, call into the policy, and 78 * then reacquire the lock. The caller is responsible for recovering gracefully. 79 * 80 * A 'LockedInterruptible' method may called a 'Locked' method, but NOT vice-versa. 81 */ 82 class InputDispatcher : public android::InputDispatcherInterface { 83 public: 84 static constexpr bool kDefaultInTouchMode = true; 85 86 explicit InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy); 87 explicit InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy, 88 std::chrono::nanoseconds staleEventTimeout); 89 ~InputDispatcher() override; 90 91 void dump(std::string& dump) override; 92 void monitor() override; 93 bool waitForIdle() override; 94 status_t start() override; 95 status_t stop() override; 96 97 void notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) override; 98 void notifyKey(const NotifyKeyArgs* args) override; 99 void notifyMotion(const NotifyMotionArgs* args) override; 100 void notifySwitch(const NotifySwitchArgs* args) override; 101 void notifySensor(const NotifySensorArgs* args) override; 102 void notifyVibratorState(const NotifyVibratorStateArgs* args) override; 103 void notifyDeviceReset(const NotifyDeviceResetArgs* args) override; 104 void notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs* args) override; 105 106 android::os::InputEventInjectionResult injectInputEvent( 107 const InputEvent* event, std::optional<int32_t> targetUid, 108 android::os::InputEventInjectionSync syncMode, std::chrono::milliseconds timeout, 109 uint32_t policyFlags) override; 110 111 std::unique_ptr<VerifiedInputEvent> verifyInputEvent(const InputEvent& event) override; 112 113 void setInputWindows( 114 const std::unordered_map<int32_t, std::vector<sp<android::gui::WindowInfoHandle>>>& 115 handlesPerDisplay) override; 116 void setFocusedApplication( 117 int32_t displayId, 118 const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) override; 119 void setFocusedDisplay(int32_t displayId) override; 120 void setInputDispatchMode(bool enabled, bool frozen) override; 121 void setInputFilterEnabled(bool enabled) override; 122 bool setInTouchMode(bool inTouchMode, int32_t pid, int32_t uid, bool hasPermission) override; 123 void setMaximumObscuringOpacityForTouch(float opacity) override; 124 void setBlockUntrustedTouchesMode(android::os::BlockUntrustedTouchesMode mode) override; 125 126 bool transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken, 127 bool isDragDrop = false) override; 128 bool transferTouch(const sp<IBinder>& destChannelToken, int32_t displayId) override; 129 130 base::Result<std::unique_ptr<InputChannel>> createInputChannel( 131 const std::string& name) override; 132 void setFocusedWindow(const android::gui::FocusRequest&) override; 133 base::Result<std::unique_ptr<InputChannel>> createInputMonitor(int32_t displayId, 134 const std::string& name, 135 int32_t pid) override; 136 status_t removeInputChannel(const sp<IBinder>& connectionToken) override; 137 status_t pilferPointers(const sp<IBinder>& token) override; 138 void requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) override; 139 bool flushSensor(int deviceId, InputDeviceSensorType sensorType) override; 140 void setDisplayEligibilityForPointerCapture(int displayId, bool isEligible) override; 141 142 std::array<uint8_t, 32> sign(const VerifiedInputEvent& event) const; 143 144 void displayRemoved(int32_t displayId) override; 145 146 // Public because it's also used by tests to simulate the WindowInfosListener callback 147 void onWindowInfosChanged(const std::vector<android::gui::WindowInfo>& windowInfos, 148 const std::vector<android::gui::DisplayInfo>& displayInfos); 149 150 void cancelCurrentTouch() override; 151 152 // Public to allow tests to verify that a Monitor can get ANR. 153 void setMonitorDispatchingTimeoutForTest(std::chrono::nanoseconds timeout); 154 155 private: 156 enum class DropReason { 157 NOT_DROPPED, 158 POLICY, 159 APP_SWITCH, 160 DISABLED, 161 BLOCKED, 162 STALE, 163 NO_POINTER_CAPTURE, 164 }; 165 166 std::unique_ptr<InputThread> mThread; 167 168 sp<InputDispatcherPolicyInterface> mPolicy; 169 android::InputDispatcherConfiguration mConfig; 170 171 std::mutex mLock; 172 173 std::condition_variable mDispatcherIsAlive; 174 std::condition_variable mDispatcherEnteredIdle; 175 176 sp<Looper> mLooper; 177 178 std::shared_ptr<EventEntry> mPendingEvent GUARDED_BY(mLock); 179 std::deque<std::shared_ptr<EventEntry>> mInboundQueue GUARDED_BY(mLock); 180 std::deque<std::shared_ptr<EventEntry>> mRecentQueue GUARDED_BY(mLock); 181 182 // A command entry captures state and behavior for an action to be performed in the 183 // dispatch loop after the initial processing has taken place. It is essentially 184 // a kind of continuation used to postpone sensitive policy interactions to a point 185 // in the dispatch loop where it is safe to release the lock (generally after finishing 186 // the critical parts of the dispatch cycle). 187 // 188 // The special thing about commands is that they can voluntarily release and reacquire 189 // the dispatcher lock at will. Initially when the command starts running, the 190 // dispatcher lock is held. However, if the command needs to call into the policy to 191 // do some work, it can release the lock, do the work, then reacquire the lock again 192 // before returning. 193 // 194 // This mechanism is a bit clunky but it helps to preserve the invariant that the dispatch 195 // never calls into the policy while holding its lock. 196 // 197 // Commands are called with the lock held, but they can release and re-acquire the lock from 198 // within. 199 using Command = std::function<void()>; 200 std::deque<Command> mCommandQueue GUARDED_BY(mLock); 201 202 DropReason mLastDropReason GUARDED_BY(mLock); 203 204 const IdGenerator mIdGenerator; 205 206 // With each iteration, InputDispatcher nominally processes one queued event, 207 // a timeout, or a response from an input consumer. 208 // This method should only be called on the input dispatcher's own thread. 209 void dispatchOnce(); 210 211 void dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) REQUIRES(mLock); 212 213 // Enqueues an inbound event. Returns true if mLooper->wake() should be called. 214 bool enqueueInboundEventLocked(std::unique_ptr<EventEntry> entry) REQUIRES(mLock); 215 216 // Cleans up input state when dropping an inbound event. 217 void dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) REQUIRES(mLock); 218 219 // Enqueues a focus event. 220 void enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus, 221 const std::string& reason) REQUIRES(mLock); 222 // Enqueues a drag event. 223 void enqueueDragEventLocked(const sp<android::gui::WindowInfoHandle>& windowToken, 224 bool isExiting, const int32_t rawX, const int32_t rawY) 225 REQUIRES(mLock); 226 227 // Adds an event to a queue of recent events for debugging purposes. 228 void addRecentEventLocked(std::shared_ptr<EventEntry> entry) REQUIRES(mLock); 229 230 // App switch latency optimization. 231 bool mAppSwitchSawKeyDown GUARDED_BY(mLock); 232 nsecs_t mAppSwitchDueTime GUARDED_BY(mLock); 233 234 bool isAppSwitchKeyEvent(const KeyEntry& keyEntry); 235 bool isAppSwitchPendingLocked() REQUIRES(mLock); 236 void resetPendingAppSwitchLocked(bool handled) REQUIRES(mLock); 237 238 // Blocked event latency optimization. Drops old events when the user intends 239 // to transfer focus to a new application. 240 std::shared_ptr<EventEntry> mNextUnblockedEvent GUARDED_BY(mLock); 241 242 sp<android::gui::WindowInfoHandle> findTouchedWindowAtLocked( 243 int32_t displayId, int32_t x, int32_t y, TouchState* touchState, bool isStylus = false, 244 bool addOutsideTargets = false, bool ignoreDragWindow = false) REQUIRES(mLock); 245 246 std::vector<sp<android::gui::WindowInfoHandle>> findTouchedSpyWindowsAtLocked( 247 int32_t displayId, int32_t x, int32_t y, bool isStylus) const REQUIRES(mLock); 248 249 sp<android::gui::WindowInfoHandle> findTouchedForegroundWindowLocked(int32_t displayId) const 250 REQUIRES(mLock); 251 252 sp<Connection> getConnectionLocked(const sp<IBinder>& inputConnectionToken) const 253 REQUIRES(mLock); 254 255 std::string getConnectionNameLocked(const sp<IBinder>& connectionToken) const REQUIRES(mLock); 256 257 void removeConnectionLocked(const sp<Connection>& connection) REQUIRES(mLock); 258 259 template <typename T> 260 struct StrongPointerHash { operatorStrongPointerHash261 std::size_t operator()(const sp<T>& b) const { return std::hash<T*>{}(b.get()); } 262 }; 263 264 // All registered connections mapped by input channel token. 265 std::unordered_map<sp<IBinder>, sp<Connection>, StrongPointerHash<IBinder>> mConnectionsByToken 266 GUARDED_BY(mLock); 267 268 // Find a monitor pid by the provided token. 269 std::optional<int32_t> findMonitorPidByTokenLocked(const sp<IBinder>& token) REQUIRES(mLock); 270 271 // Input channels that will receive a copy of all input events sent to the provided display. 272 std::unordered_map<int32_t, std::vector<Monitor>> mGlobalMonitorsByDisplay GUARDED_BY(mLock); 273 274 const HmacKeyManager mHmacKeyManager; 275 const std::array<uint8_t, 32> getSignature(const MotionEntry& motionEntry, 276 const DispatchEntry& dispatchEntry) const; 277 const std::array<uint8_t, 32> getSignature(const KeyEntry& keyEntry, 278 const DispatchEntry& dispatchEntry) const; 279 280 // Event injection and synchronization. 281 std::condition_variable mInjectionResultAvailable; 282 void setInjectionResult(EventEntry& entry, 283 android::os::InputEventInjectionResult injectionResult); 284 void transformMotionEntryForInjectionLocked(MotionEntry&, 285 const ui::Transform& injectedTransform) const 286 REQUIRES(mLock); 287 288 std::condition_variable mInjectionSyncFinished; 289 void incrementPendingForegroundDispatches(EventEntry& entry); 290 void decrementPendingForegroundDispatches(EventEntry& entry); 291 292 // Key repeat tracking. 293 struct KeyRepeatState { 294 std::shared_ptr<KeyEntry> lastKeyEntry; // or null if no repeat 295 nsecs_t nextRepeatTime; 296 } mKeyRepeatState GUARDED_BY(mLock); 297 298 void resetKeyRepeatLocked() REQUIRES(mLock); 299 std::shared_ptr<KeyEntry> synthesizeKeyRepeatLocked(nsecs_t currentTime) REQUIRES(mLock); 300 301 // Key replacement tracking 302 struct KeyReplacement { 303 int32_t keyCode; 304 int32_t deviceId; 305 bool operator==(const KeyReplacement& rhs) const { 306 return keyCode == rhs.keyCode && deviceId == rhs.deviceId; 307 } 308 }; 309 struct KeyReplacementHash { operatorKeyReplacementHash310 size_t operator()(const KeyReplacement& key) const { 311 return std::hash<int32_t>()(key.keyCode) ^ (std::hash<int32_t>()(key.deviceId) << 1); 312 } 313 }; 314 // Maps the key code replaced, device id tuple to the key code it was replaced with 315 std::unordered_map<KeyReplacement, int32_t, KeyReplacementHash> mReplacedKeys GUARDED_BY(mLock); 316 // Process certain Meta + Key combinations 317 void accelerateMetaShortcuts(const int32_t deviceId, const int32_t action, int32_t& keyCode, 318 int32_t& metaState); 319 320 // Deferred command processing. 321 bool haveCommandsLocked() const REQUIRES(mLock); 322 bool runCommandsLockedInterruptable() REQUIRES(mLock); 323 void postCommandLocked(Command&& command) REQUIRES(mLock); 324 325 // The dispatching timeout to use for Monitors. 326 std::chrono::nanoseconds mMonitorDispatchingTimeout GUARDED_BY(mLock); 327 328 nsecs_t processAnrsLocked() REQUIRES(mLock); 329 std::chrono::nanoseconds getDispatchingTimeoutLocked(const sp<Connection>& connection) 330 REQUIRES(mLock); 331 332 // Input filter processing. 333 bool shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) REQUIRES(mLock); 334 bool shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) REQUIRES(mLock); 335 336 // Inbound event processing. 337 void drainInboundQueueLocked() REQUIRES(mLock); 338 void releasePendingEventLocked() REQUIRES(mLock); 339 void releaseInboundEventLocked(std::shared_ptr<EventEntry> entry) REQUIRES(mLock); 340 341 // Dispatch state. 342 bool mDispatchEnabled GUARDED_BY(mLock); 343 bool mDispatchFrozen GUARDED_BY(mLock); 344 bool mInputFilterEnabled GUARDED_BY(mLock); 345 bool mInTouchMode GUARDED_BY(mLock); 346 float mMaximumObscuringOpacityForTouch GUARDED_BY(mLock); 347 android::os::BlockUntrustedTouchesMode mBlockUntrustedTouchesMode GUARDED_BY(mLock); 348 349 class DispatcherWindowListener : public gui::WindowInfosListener { 350 public: DispatcherWindowListener(InputDispatcher & dispatcher)351 explicit DispatcherWindowListener(InputDispatcher& dispatcher) : mDispatcher(dispatcher){}; 352 void onWindowInfosChanged( 353 const std::vector<android::gui::WindowInfo>& windowInfos, 354 const std::vector<android::gui::DisplayInfo>& displayInfos) override; 355 356 private: 357 InputDispatcher& mDispatcher; 358 }; 359 sp<gui::WindowInfosListener> mWindowInfoListener; 360 361 std::unordered_map<int32_t /*displayId*/, std::vector<sp<android::gui::WindowInfoHandle>>> 362 mWindowHandlesByDisplay GUARDED_BY(mLock); 363 std::unordered_map<int32_t /*displayId*/, android::gui::DisplayInfo> mDisplayInfos 364 GUARDED_BY(mLock); 365 void setInputWindowsLocked( 366 const std::vector<sp<android::gui::WindowInfoHandle>>& inputWindowHandles, 367 int32_t displayId) REQUIRES(mLock); 368 // Get a reference to window handles by display, return an empty vector if not found. 369 const std::vector<sp<android::gui::WindowInfoHandle>>& getWindowHandlesLocked( 370 int32_t displayId) const REQUIRES(mLock); 371 sp<android::gui::WindowInfoHandle> getWindowHandleLocked( 372 const sp<IBinder>& windowHandleToken) const REQUIRES(mLock); 373 374 // Same function as above, but faster. Since displayId is provided, this avoids the need 375 // to loop through all displays. 376 sp<android::gui::WindowInfoHandle> getWindowHandleLocked(const sp<IBinder>& windowHandleToken, 377 int displayId) const REQUIRES(mLock); 378 sp<android::gui::WindowInfoHandle> getWindowHandleLocked( 379 const sp<android::gui::WindowInfoHandle>& windowHandle) const REQUIRES(mLock); 380 std::shared_ptr<InputChannel> getInputChannelLocked(const sp<IBinder>& windowToken) const 381 REQUIRES(mLock); 382 sp<android::gui::WindowInfoHandle> getFocusedWindowHandleLocked(int displayId) const 383 REQUIRES(mLock); 384 bool hasResponsiveConnectionLocked(android::gui::WindowInfoHandle& windowHandle) const 385 REQUIRES(mLock); 386 387 // Gets all the input targets (with their respective input channels) from the window handles 388 // passed as argument. 389 std::vector<InputTarget> getInputTargetsFromWindowHandlesLocked( 390 const std::vector<sp<android::gui::WindowInfoHandle>>& windowHandles) const 391 REQUIRES(mLock); 392 393 /* 394 * Validate and update InputWindowHandles for a given display. 395 */ 396 void updateWindowHandlesForDisplayLocked( 397 const std::vector<sp<android::gui::WindowInfoHandle>>& inputWindowHandles, 398 int32_t displayId) REQUIRES(mLock); 399 400 std::unordered_map<int32_t, TouchState> mTouchStatesByDisplay GUARDED_BY(mLock); 401 std::unique_ptr<DragState> mDragState GUARDED_BY(mLock); 402 403 void setFocusedApplicationLocked( 404 int32_t displayId, 405 const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) REQUIRES(mLock); 406 // Focused applications. 407 std::unordered_map<int32_t, std::shared_ptr<InputApplicationHandle>> 408 mFocusedApplicationHandlesByDisplay GUARDED_BY(mLock); 409 410 // Top focused display. 411 int32_t mFocusedDisplayId GUARDED_BY(mLock); 412 413 // Keeps track of the focused window per display and determines focus changes. 414 FocusResolver mFocusResolver GUARDED_BY(mLock); 415 416 // The enabled state of this request is true iff the focused window on the focused display has 417 // requested Pointer Capture. This request also contains the sequence number associated with the 418 // current request. The state of this variable should always be in sync with the state of 419 // Pointer Capture in the policy, and is only updated through setPointerCaptureLocked(request). 420 PointerCaptureRequest mCurrentPointerCaptureRequest GUARDED_BY(mLock); 421 422 // The window token that has Pointer Capture. 423 // This should be in sync with PointerCaptureChangedEvents dispatched to the input channel. 424 sp<IBinder> mWindowTokenWithPointerCapture GUARDED_BY(mLock); 425 426 // Displays that are ineligible for pointer capture. 427 // TODO(b/214621487): Remove or move to a display flag. 428 std::vector<int32_t> mIneligibleDisplaysForPointerCapture GUARDED_BY(mLock); 429 430 // Disable Pointer Capture as a result of loss of window focus. 431 void disablePointerCaptureForcedLocked() REQUIRES(mLock); 432 433 // Set the Pointer Capture state in the Policy. 434 void setPointerCaptureLocked(bool enable) REQUIRES(mLock); 435 436 // Dispatcher state at time of last ANR. 437 std::string mLastAnrState GUARDED_BY(mLock); 438 439 // The connection tokens of the channels that the user last interacted (used for debugging and 440 // when switching touch mode state). 441 std::unordered_set<sp<IBinder>, StrongPointerHash<IBinder>> mInteractionConnectionTokens 442 GUARDED_BY(mLock); 443 void updateInteractionTokensLocked(const EventEntry& entry, 444 const std::vector<InputTarget>& targets) REQUIRES(mLock); 445 446 // Dispatch inbound events. 447 bool dispatchConfigurationChangedLocked(nsecs_t currentTime, 448 const ConfigurationChangedEntry& entry) REQUIRES(mLock); 449 bool dispatchDeviceResetLocked(nsecs_t currentTime, const DeviceResetEntry& entry) 450 REQUIRES(mLock); 451 bool dispatchKeyLocked(nsecs_t currentTime, std::shared_ptr<KeyEntry> entry, 452 DropReason* dropReason, nsecs_t* nextWakeupTime) REQUIRES(mLock); 453 bool dispatchMotionLocked(nsecs_t currentTime, std::shared_ptr<MotionEntry> entry, 454 DropReason* dropReason, nsecs_t* nextWakeupTime) REQUIRES(mLock); 455 void dispatchFocusLocked(nsecs_t currentTime, std::shared_ptr<FocusEntry> entry) 456 REQUIRES(mLock); 457 void dispatchPointerCaptureChangedLocked( 458 nsecs_t currentTime, const std::shared_ptr<PointerCaptureChangedEntry>& entry, 459 DropReason& dropReason) REQUIRES(mLock); 460 void dispatchTouchModeChangeLocked(nsecs_t currentTime, 461 const std::shared_ptr<TouchModeEntry>& entry) 462 REQUIRES(mLock); 463 void dispatchEventLocked(nsecs_t currentTime, std::shared_ptr<EventEntry> entry, 464 const std::vector<InputTarget>& inputTargets) REQUIRES(mLock); 465 void dispatchSensorLocked(nsecs_t currentTime, const std::shared_ptr<SensorEntry>& entry, 466 DropReason* dropReason, nsecs_t* nextWakeupTime) REQUIRES(mLock); 467 void dispatchDragLocked(nsecs_t currentTime, std::shared_ptr<DragEntry> entry) REQUIRES(mLock); 468 void logOutboundKeyDetails(const char* prefix, const KeyEntry& entry); 469 void logOutboundMotionDetails(const char* prefix, const MotionEntry& entry); 470 471 /** 472 * This field is set if there is no focused window, and we have an event that requires 473 * a focused window to be dispatched (for example, a KeyEvent). 474 * When this happens, we will wait until *mNoFocusedWindowTimeoutTime before 475 * dropping the event and raising an ANR for that application. 476 * This is useful if an application is slow to add a focused window. 477 */ 478 std::optional<nsecs_t> mNoFocusedWindowTimeoutTime GUARDED_BY(mLock); 479 480 // Amount of time to allow for an event to be dispatched (measured since its eventTime) 481 // before considering it stale and dropping it. 482 const std::chrono::nanoseconds mStaleEventTimeout; 483 bool isStaleEvent(nsecs_t currentTime, const EventEntry& entry); 484 485 bool shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) REQUIRES(mLock); 486 487 /** 488 * Time to stop waiting for the events to be processed while trying to dispatch a key. 489 * When this time expires, we just send the pending key event to the currently focused window, 490 * without waiting on other events to be processed first. 491 */ 492 std::optional<nsecs_t> mKeyIsWaitingForEventsTimeout GUARDED_BY(mLock); 493 bool shouldWaitToSendKeyLocked(nsecs_t currentTime, const char* focusedWindowName) 494 REQUIRES(mLock); 495 496 /** 497 * The focused application at the time when no focused window was present. 498 * Used to raise an ANR when we have no focused window. 499 */ 500 std::shared_ptr<InputApplicationHandle> mAwaitedFocusedApplication GUARDED_BY(mLock); 501 /** 502 * The displayId that the focused application is associated with. 503 */ 504 int32_t mAwaitedApplicationDisplayId GUARDED_BY(mLock); 505 void processNoFocusedWindowAnrLocked() REQUIRES(mLock); 506 507 /** 508 * Tell policy about a window or a monitor that just became unresponsive. Starts ANR. 509 */ 510 void processConnectionUnresponsiveLocked(const Connection& connection, std::string reason) 511 REQUIRES(mLock); 512 /** 513 * Tell policy about a window or a monitor that just became responsive. 514 */ 515 void processConnectionResponsiveLocked(const Connection& connection) REQUIRES(mLock); 516 517 void sendWindowUnresponsiveCommandLocked(const sp<IBinder>& connectionToken, 518 std::optional<int32_t> pid, std::string reason) 519 REQUIRES(mLock); 520 void sendWindowResponsiveCommandLocked(const sp<IBinder>& connectionToken, 521 std::optional<int32_t> pid) REQUIRES(mLock); 522 523 // Optimization: AnrTracker is used to quickly find which connection is due for a timeout next. 524 // AnrTracker must be kept in-sync with all responsive connection.waitQueues. 525 // If a connection is not responsive, then the entries should not be added to the AnrTracker. 526 // Once a connection becomes unresponsive, its entries are removed from AnrTracker to 527 // prevent unneeded wakeups. 528 AnrTracker mAnrTracker GUARDED_BY(mLock); 529 530 // Contains the last window which received a hover event. 531 sp<android::gui::WindowInfoHandle> mLastHoverWindowHandle GUARDED_BY(mLock); 532 533 void cancelEventsForAnrLocked(const sp<Connection>& connection) REQUIRES(mLock); 534 // If a focused application changes, we should stop counting down the "no focused window" time, 535 // because we will have no way of knowing when the previous application actually added a window. 536 // This also means that we will miss cases like pulling down notification shade when the 537 // focused application does not have a focused window (no ANR will be raised if notification 538 // shade is pulled down while we are counting down the timeout). 539 void resetNoFocusedWindowTimeoutLocked() REQUIRES(mLock); 540 541 int32_t getTargetDisplayId(const EventEntry& entry); 542 android::os::InputEventInjectionResult findFocusedWindowTargetsLocked( 543 nsecs_t currentTime, const EventEntry& entry, std::vector<InputTarget>& inputTargets, 544 nsecs_t* nextWakeupTime) REQUIRES(mLock); 545 android::os::InputEventInjectionResult findTouchedWindowTargetsLocked( 546 nsecs_t currentTime, const MotionEntry& entry, std::vector<InputTarget>& inputTargets, 547 nsecs_t* nextWakeupTime, bool* outConflictingPointerActions) REQUIRES(mLock); 548 std::vector<Monitor> selectResponsiveMonitorsLocked( 549 const std::vector<Monitor>& gestureMonitors) const REQUIRES(mLock); 550 551 void addWindowTargetLocked(const sp<android::gui::WindowInfoHandle>& windowHandle, 552 int32_t targetFlags, BitSet32 pointerIds, 553 std::vector<InputTarget>& inputTargets) REQUIRES(mLock); 554 void addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets, int32_t displayId) 555 REQUIRES(mLock); 556 void pokeUserActivityLocked(const EventEntry& eventEntry) REQUIRES(mLock); 557 // Enqueue a drag event if needed, and update the touch state. 558 // Uses findTouchedWindowTargetsLocked to make the decision 559 void addDragEventLocked(const MotionEntry& entry) REQUIRES(mLock); 560 void finishDragAndDrop(int32_t displayId, float x, float y) REQUIRES(mLock); 561 562 struct TouchOcclusionInfo { 563 bool hasBlockingOcclusion; 564 float obscuringOpacity; 565 std::string obscuringPackage; 566 int32_t obscuringUid; 567 std::vector<std::string> debugInfo; 568 }; 569 570 TouchOcclusionInfo computeTouchOcclusionInfoLocked( 571 const sp<android::gui::WindowInfoHandle>& windowHandle, int32_t x, int32_t y) const 572 REQUIRES(mLock); 573 bool isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const REQUIRES(mLock); 574 bool isWindowObscuredAtPointLocked(const sp<android::gui::WindowInfoHandle>& windowHandle, 575 int32_t x, int32_t y) const REQUIRES(mLock); 576 bool isWindowObscuredLocked(const sp<android::gui::WindowInfoHandle>& windowHandle) const 577 REQUIRES(mLock); 578 std::string dumpWindowForTouchOcclusion(const android::gui::WindowInfo* info, 579 bool isTouchWindow) const; 580 std::string getApplicationWindowLabel(const InputApplicationHandle* applicationHandle, 581 const sp<android::gui::WindowInfoHandle>& windowHandle); 582 583 bool shouldDropInput(const EventEntry& entry, 584 const sp<android::gui::WindowInfoHandle>& windowHandle) const 585 REQUIRES(mLock); 586 587 // Manage the dispatch cycle for a single connection. 588 // These methods are deliberately not Interruptible because doing all of the work 589 // with the mutex held makes it easier to ensure that connection invariants are maintained. 590 // If needed, the methods post commands to run later once the critical bits are done. 591 void prepareDispatchCycleLocked(nsecs_t currentTime, const sp<Connection>& connection, 592 std::shared_ptr<EventEntry>, const InputTarget& inputTarget) 593 REQUIRES(mLock); 594 void enqueueDispatchEntriesLocked(nsecs_t currentTime, const sp<Connection>& connection, 595 std::shared_ptr<EventEntry>, const InputTarget& inputTarget) 596 REQUIRES(mLock); 597 void enqueueDispatchEntryLocked(const sp<Connection>& connection, std::shared_ptr<EventEntry>, 598 const InputTarget& inputTarget, int32_t dispatchMode) 599 REQUIRES(mLock); 600 void startDispatchCycleLocked(nsecs_t currentTime, const sp<Connection>& connection) 601 REQUIRES(mLock); 602 void finishDispatchCycleLocked(nsecs_t currentTime, const sp<Connection>& connection, 603 uint32_t seq, bool handled, nsecs_t consumeTime) REQUIRES(mLock); 604 void abortBrokenDispatchCycleLocked(nsecs_t currentTime, const sp<Connection>& connection, 605 bool notify) REQUIRES(mLock); 606 void drainDispatchQueue(std::deque<DispatchEntry*>& queue); 607 void releaseDispatchEntry(DispatchEntry* dispatchEntry); 608 int handleReceiveCallback(int events, sp<IBinder> connectionToken); 609 // The action sent should only be of type AMOTION_EVENT_* 610 void dispatchPointerDownOutsideFocus(uint32_t source, int32_t action, 611 const sp<IBinder>& newToken) REQUIRES(mLock); 612 613 void synthesizeCancelationEventsForAllConnectionsLocked(const CancelationOptions& options) 614 REQUIRES(mLock); 615 void synthesizeCancelationEventsForMonitorsLocked(const CancelationOptions& options) 616 REQUIRES(mLock); 617 void synthesizeCancelationEventsForInputChannelLocked( 618 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) 619 REQUIRES(mLock); 620 void synthesizeCancelationEventsForConnectionLocked(const sp<Connection>& connection, 621 const CancelationOptions& options) 622 REQUIRES(mLock); 623 624 void synthesizePointerDownEventsForConnectionLocked(const sp<Connection>& connection, 625 int32_t targetFlags) REQUIRES(mLock); 626 627 void synthesizeCancelationEventsForWindowLocked( 628 const sp<android::gui::WindowInfoHandle>& windowHandle, 629 const CancelationOptions& options) REQUIRES(mLock); 630 631 // Splitting motion events across windows. 632 std::unique_ptr<MotionEntry> splitMotionEvent(const MotionEntry& originalMotionEntry, 633 BitSet32 pointerIds); 634 635 // Reset and drop everything the dispatcher is doing. 636 void resetAndDropEverythingLocked(const char* reason) REQUIRES(mLock); 637 638 // Dump state. 639 void dumpDispatchStateLocked(std::string& dump) REQUIRES(mLock); 640 void dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors); 641 void logDispatchStateLocked() REQUIRES(mLock); 642 std::string dumpPointerCaptureStateLocked() REQUIRES(mLock); 643 644 // Registration. 645 void removeMonitorChannelLocked(const sp<IBinder>& connectionToken) REQUIRES(mLock); 646 status_t removeInputChannelLocked(const sp<IBinder>& connectionToken, bool notify) 647 REQUIRES(mLock); 648 649 // Interesting events that we might like to log or tell the framework about. 650 void doDispatchCycleFinishedCommand(nsecs_t finishTime, const sp<Connection>& connection, 651 uint32_t seq, bool handled, nsecs_t consumeTime) 652 REQUIRES(mLock); 653 void doInterceptKeyBeforeDispatchingCommand(const sp<IBinder>& focusedWindowToken, 654 KeyEntry& entry) REQUIRES(mLock); 655 void onFocusChangedLocked(const FocusResolver::FocusChanges& changes) REQUIRES(mLock); 656 void sendFocusChangedCommandLocked(const sp<IBinder>& oldToken, const sp<IBinder>& newToken) 657 REQUIRES(mLock); 658 void sendDropWindowCommandLocked(const sp<IBinder>& token, float x, float y) REQUIRES(mLock); 659 void sendUntrustedTouchCommandLocked(const std::string& obscuringPackage) REQUIRES(mLock); 660 void onAnrLocked(const sp<Connection>& connection) REQUIRES(mLock); 661 void onAnrLocked(std::shared_ptr<InputApplicationHandle> application) REQUIRES(mLock); 662 void updateLastAnrStateLocked(const sp<android::gui::WindowInfoHandle>& window, 663 const std::string& reason) REQUIRES(mLock); 664 void updateLastAnrStateLocked(const InputApplicationHandle& application, 665 const std::string& reason) REQUIRES(mLock); 666 void updateLastAnrStateLocked(const std::string& windowLabel, const std::string& reason) 667 REQUIRES(mLock); 668 bool afterKeyEventLockedInterruptable(const sp<Connection>& connection, 669 DispatchEntry* dispatchEntry, KeyEntry& keyEntry, 670 bool handled) REQUIRES(mLock); 671 bool afterMotionEventLockedInterruptable(const sp<Connection>& connection, 672 DispatchEntry* dispatchEntry, MotionEntry& motionEntry, 673 bool handled) REQUIRES(mLock); 674 675 // Find touched state and touched window by token. 676 std::pair<TouchState*, TouchedWindow*> findTouchStateAndWindowLocked(const sp<IBinder>& token) 677 REQUIRES(mLock); 678 679 // Statistics gathering. 680 LatencyAggregator mLatencyAggregator GUARDED_BY(mLock); 681 LatencyTracker mLatencyTracker GUARDED_BY(mLock); 682 void traceInboundQueueLengthLocked() REQUIRES(mLock); 683 void traceOutboundQueueLength(const Connection& connection); 684 void traceWaitQueueLength(const Connection& connection); 685 686 // Check window ownership 687 bool focusedWindowIsOwnedByLocked(int32_t pid, int32_t uid) REQUIRES(mLock); 688 bool recentWindowsAreOwnedByLocked(int32_t pid, int32_t uid) REQUIRES(mLock); 689 690 sp<InputReporterInterface> mReporter; 691 692 void slipWallpaperTouch(int32_t targetFlags, 693 const sp<android::gui::WindowInfoHandle>& oldWindowHandle, 694 const sp<android::gui::WindowInfoHandle>& newWindowHandle, 695 TouchState& state, const BitSet32& pointerIds) REQUIRES(mLock); 696 void transferWallpaperTouch(int32_t oldTargetFlags, int32_t newTargetFlags, 697 const sp<android::gui::WindowInfoHandle> fromWindowHandle, 698 const sp<android::gui::WindowInfoHandle> toWindowHandle, 699 TouchState& state, const BitSet32& pointerIds) REQUIRES(mLock); 700 701 sp<android::gui::WindowInfoHandle> findWallpaperWindowBelow( 702 const sp<android::gui::WindowInfoHandle>& windowHandle) const REQUIRES(mLock); 703 }; 704 705 } // namespace android::inputdispatcher 706 707 #endif // _UI_INPUT_DISPATCHER_H 708