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