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 "InputTarget.h" 29 #include "InputThread.h" 30 #include "LatencyAggregator.h" 31 #include "LatencyTracker.h" 32 #include "Monitor.h" 33 #include "TouchState.h" 34 #include "TouchedWindow.h" 35 #include "trace/InputTracerInterface.h" 36 #include "trace/InputTracingBackendInterface.h" 37 38 #include <attestation/HmacKeyManager.h> 39 #include <gui/InputApplication.h> 40 #include <gui/WindowInfosUpdate.h> 41 #include <input/Input.h> 42 #include <input/InputTransport.h> 43 #include <limits.h> 44 #include <powermanager/PowerManager.h> 45 #include <stddef.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 <bitset> 52 #include <condition_variable> 53 #include <deque> 54 #include <optional> 55 #include <unordered_map> 56 #include <unordered_set> 57 58 #include <InputListener.h> 59 #include <InputReporterInterface.h> 60 #include <gui/WindowInfosListener.h> 61 62 namespace android::inputdispatcher { 63 64 class Connection; 65 66 /* Dispatches events to input targets. Some functions of the input dispatcher, such as 67 * identifying input targets, are controlled by a separate policy object. 68 * 69 * IMPORTANT INVARIANT: 70 * Because the policy can potentially block or cause re-entrance into the input dispatcher, 71 * the input dispatcher never calls into the policy while holding its internal locks. 72 * The implementation is also carefully designed to recover from scenarios such as an 73 * input channel becoming unregistered while identifying input targets or processing timeouts. 74 * 75 * Methods marked 'Locked' must be called with the lock acquired. 76 * 77 * Methods marked 'LockedInterruptible' must be called with the lock acquired but 78 * may during the course of their execution release the lock, call into the policy, and 79 * then reacquire the lock. The caller is responsible for recovering gracefully. 80 * 81 * A 'LockedInterruptible' method may called a 'Locked' method, but NOT vice-versa. 82 */ 83 class InputDispatcher : public android::InputDispatcherInterface { 84 public: 85 static constexpr bool kDefaultInTouchMode = true; 86 87 explicit InputDispatcher(InputDispatcherPolicyInterface& policy); 88 // Constructor used for testing. 89 explicit InputDispatcher(InputDispatcherPolicyInterface&, 90 std::unique_ptr<trace::InputTracingBackendInterface>); 91 ~InputDispatcher() override; 92 93 void dump(std::string& dump) const override; 94 void monitor() override; 95 bool waitForIdle() const override; 96 status_t start() override; 97 status_t stop() override; 98 99 void notifyInputDevicesChanged(const NotifyInputDevicesChangedArgs& args) override; 100 void notifyConfigurationChanged(const NotifyConfigurationChangedArgs& args) override; 101 void notifyKey(const NotifyKeyArgs& args) override; 102 void notifyMotion(const NotifyMotionArgs& args) override; 103 void notifySwitch(const NotifySwitchArgs& args) override; 104 void notifySensor(const NotifySensorArgs& args) override; 105 void notifyVibratorState(const NotifyVibratorStateArgs& args) override; 106 void notifyDeviceReset(const NotifyDeviceResetArgs& args) override; 107 void notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs& args) override; 108 109 android::os::InputEventInjectionResult injectInputEvent( 110 const InputEvent* event, std::optional<gui::Uid> targetUid, 111 android::os::InputEventInjectionSync syncMode, std::chrono::milliseconds timeout, 112 uint32_t policyFlags) override; 113 114 std::unique_ptr<VerifiedInputEvent> verifyInputEvent(const InputEvent& event) override; 115 116 void setFocusedApplication( 117 ui::LogicalDisplayId displayId, 118 const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) override; 119 void setFocusedDisplay(ui::LogicalDisplayId displayId) override; 120 void setMinTimeBetweenUserActivityPokes(std::chrono::milliseconds interval) override; 121 void setInputDispatchMode(bool enabled, bool frozen) override; 122 void setInputFilterEnabled(bool enabled) override; 123 bool setInTouchMode(bool inTouchMode, gui::Pid pid, gui::Uid uid, bool hasPermission, 124 ui::LogicalDisplayId displayId) override; 125 void setMaximumObscuringOpacityForTouch(float opacity) override; 126 127 bool transferTouchGesture(const sp<IBinder>& fromToken, const sp<IBinder>& toToken, 128 bool isDragDrop = false) override; 129 bool transferTouchOnDisplay(const sp<IBinder>& destChannelToken, 130 ui::LogicalDisplayId displayId) override; 131 132 base::Result<std::unique_ptr<InputChannel>> createInputChannel( 133 const std::string& name) override; 134 void setFocusedWindow(const android::gui::FocusRequest&) override; 135 base::Result<std::unique_ptr<InputChannel>> createInputMonitor(ui::LogicalDisplayId displayId, 136 const std::string& name, 137 gui::Pid pid) override; 138 status_t removeInputChannel(const sp<IBinder>& connectionToken) override; 139 status_t pilferPointers(const sp<IBinder>& token) override; 140 void requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) override; 141 bool flushSensor(int deviceId, InputDeviceSensorType sensorType) override; 142 void setDisplayEligibilityForPointerCapture(ui::LogicalDisplayId displayId, 143 bool isEligible) override; 144 145 std::array<uint8_t, 32> sign(const VerifiedInputEvent& event) const; 146 147 void displayRemoved(ui::LogicalDisplayId displayId) override; 148 149 // Public because it's also used by tests to simulate the WindowInfosListener callback 150 void onWindowInfosChanged(const gui::WindowInfosUpdate&); 151 152 void cancelCurrentTouch() override; 153 154 // Public to allow tests to verify that a Monitor can get ANR. 155 void setMonitorDispatchingTimeoutForTest(std::chrono::nanoseconds timeout); 156 157 void setKeyRepeatConfiguration(std::chrono::nanoseconds timeout, 158 std::chrono::nanoseconds delay) override; 159 160 bool isPointerInWindow(const sp<IBinder>& token, ui::LogicalDisplayId displayId, 161 DeviceId deviceId, int32_t pointerId) override; 162 163 void setInputMethodConnectionIsActive(bool isActive) override; 164 165 private: 166 enum class DropReason { 167 NOT_DROPPED, 168 POLICY, 169 DISABLED, 170 BLOCKED, 171 STALE, 172 NO_POINTER_CAPTURE, 173 }; 174 175 std::unique_ptr<InputThread> mThread; 176 177 InputDispatcherPolicyInterface& mPolicy; 178 android::InputDispatcherConfiguration mConfig GUARDED_BY(mLock); 179 180 mutable std::mutex mLock; 181 182 std::condition_variable mDispatcherIsAlive; 183 mutable std::condition_variable mDispatcherEnteredIdle; 184 185 // Input event tracer. The tracer will only exist on builds where input tracing is allowed. 186 std::unique_ptr<trace::InputTracerInterface> mTracer GUARDED_BY(mLock); 187 188 sp<Looper> mLooper; 189 190 std::shared_ptr<const EventEntry> mPendingEvent GUARDED_BY(mLock); 191 std::deque<std::shared_ptr<const EventEntry>> mInboundQueue GUARDED_BY(mLock); 192 std::deque<std::shared_ptr<const EventEntry>> mRecentQueue GUARDED_BY(mLock); 193 194 // A command entry captures state and behavior for an action to be performed in the 195 // dispatch loop after the initial processing has taken place. It is essentially 196 // a kind of continuation used to postpone sensitive policy interactions to a point 197 // in the dispatch loop where it is safe to release the lock (generally after finishing 198 // the critical parts of the dispatch cycle). 199 // 200 // The special thing about commands is that they can voluntarily release and reacquire 201 // the dispatcher lock at will. Initially when the command starts running, the 202 // dispatcher lock is held. However, if the command needs to call into the policy to 203 // do some work, it can release the lock, do the work, then reacquire the lock again 204 // before returning. 205 // 206 // This mechanism is a bit clunky but it helps to preserve the invariant that the dispatch 207 // never calls into the policy while holding its lock. 208 // 209 // Commands are called with the lock held, but they can release and re-acquire the lock from 210 // within. 211 using Command = std::function<void()>; 212 std::deque<Command> mCommandQueue GUARDED_BY(mLock); 213 214 DropReason mLastDropReason GUARDED_BY(mLock); 215 216 const IdGenerator mIdGenerator GUARDED_BY(mLock); 217 218 int64_t mWindowInfosVsyncId GUARDED_BY(mLock); 219 220 std::chrono::milliseconds mMinTimeBetweenUserActivityPokes GUARDED_BY(mLock); 221 222 /** Stores the latest user-activity poke event times per user activity types. */ 223 std::array<nsecs_t, USER_ACTIVITY_EVENT_LAST + 1> mLastUserActivityTimes GUARDED_BY(mLock); 224 225 // With each iteration, InputDispatcher nominally processes one queued event, 226 // a timeout, or a response from an input consumer. 227 // This method should only be called on the input dispatcher's own thread. 228 void dispatchOnce(); 229 230 void dispatchOnceInnerLocked(nsecs_t& nextWakeupTime) REQUIRES(mLock); 231 232 // Enqueues an inbound event. Returns true if mLooper->wake() should be called. 233 bool enqueueInboundEventLocked(std::unique_ptr<EventEntry> entry) REQUIRES(mLock); 234 235 // Cleans up input state when dropping an inbound event. 236 void dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) REQUIRES(mLock); 237 238 // Enqueues a focus event. 239 void enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus, 240 const std::string& reason) REQUIRES(mLock); 241 // Enqueues a drag event. 242 void enqueueDragEventLocked(const sp<android::gui::WindowInfoHandle>& windowToken, 243 bool isExiting, const int32_t rawX, const int32_t rawY) 244 REQUIRES(mLock); 245 246 // Adds an event to a queue of recent events for debugging purposes. 247 void addRecentEventLocked(std::shared_ptr<const EventEntry> entry) REQUIRES(mLock); 248 249 // Blocked event latency optimization. Drops old events when the user intends 250 // to transfer focus to a new application. 251 std::shared_ptr<const EventEntry> mNextUnblockedEvent GUARDED_BY(mLock); 252 253 sp<android::gui::WindowInfoHandle> findTouchedWindowAtLocked( 254 ui::LogicalDisplayId displayId, float x, float y, bool isStylus = false, 255 bool ignoreDragWindow = false) const REQUIRES(mLock); 256 std::vector<InputTarget> findOutsideTargetsLocked( 257 ui::LogicalDisplayId displayId, const sp<android::gui::WindowInfoHandle>& touchedWindow, 258 int32_t pointerId) const REQUIRES(mLock); 259 260 std::vector<sp<android::gui::WindowInfoHandle>> findTouchedSpyWindowsAtLocked( 261 ui::LogicalDisplayId displayId, float x, float y, bool isStylus) const REQUIRES(mLock); 262 263 sp<android::gui::WindowInfoHandle> findTouchedForegroundWindowLocked( 264 ui::LogicalDisplayId displayId) const REQUIRES(mLock); 265 266 std::shared_ptr<Connection> getConnectionLocked(const sp<IBinder>& inputConnectionToken) const 267 REQUIRES(mLock); 268 269 std::string getConnectionNameLocked(const sp<IBinder>& connectionToken) const REQUIRES(mLock); 270 271 void removeConnectionLocked(const std::shared_ptr<Connection>& connection) REQUIRES(mLock); 272 273 status_t pilferPointersLocked(const sp<IBinder>& token) REQUIRES(mLock); 274 275 template <typename T> 276 struct StrongPointerHash { operatorStrongPointerHash277 std::size_t operator()(const sp<T>& b) const { return std::hash<T*>{}(b.get()); } 278 }; 279 280 // All registered connections mapped by input channel token. 281 std::unordered_map<sp<IBinder>, std::shared_ptr<Connection>, StrongPointerHash<IBinder>> 282 mConnectionsByToken GUARDED_BY(mLock); 283 284 // Find a monitor pid by the provided token. 285 std::optional<gui::Pid> findMonitorPidByTokenLocked(const sp<IBinder>& token) REQUIRES(mLock); 286 287 // Input channels that will receive a copy of all input events sent to the provided display. 288 std::unordered_map<ui::LogicalDisplayId, std::vector<Monitor>> mGlobalMonitorsByDisplay 289 GUARDED_BY(mLock); 290 291 const HmacKeyManager mHmacKeyManager; 292 const std::array<uint8_t, 32> getSignature(const MotionEntry& motionEntry, 293 const DispatchEntry& dispatchEntry) const; 294 const std::array<uint8_t, 32> getSignature(const KeyEntry& keyEntry, 295 const DispatchEntry& dispatchEntry) const; 296 297 // Event injection and synchronization. 298 std::condition_variable mInjectionResultAvailable; 299 void setInjectionResult(const EventEntry& entry, 300 android::os::InputEventInjectionResult injectionResult); 301 void transformMotionEntryForInjectionLocked(MotionEntry&, 302 const ui::Transform& injectedTransform) const 303 REQUIRES(mLock); 304 // Per-display correction of injected events 305 std::map<android::ui::LogicalDisplayId, InputVerifier> mInputFilterVerifiersByDisplay 306 GUARDED_BY(mLock); 307 std::condition_variable mInjectionSyncFinished; 308 void incrementPendingForegroundDispatches(const EventEntry& entry); 309 void decrementPendingForegroundDispatches(const EventEntry& entry); 310 311 // Key repeat tracking. 312 struct KeyRepeatState { 313 std::shared_ptr<const KeyEntry> lastKeyEntry; // or null if no repeat 314 nsecs_t nextRepeatTime; 315 } mKeyRepeatState GUARDED_BY(mLock); 316 317 void resetKeyRepeatLocked() REQUIRES(mLock); 318 std::shared_ptr<KeyEntry> synthesizeKeyRepeatLocked(nsecs_t currentTime) REQUIRES(mLock); 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( 330 const std::shared_ptr<Connection>& connection) 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<const 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 float mMaximumObscuringOpacityForTouch GUARDED_BY(mLock); 346 347 // This map is not really needed, but it helps a lot with debugging (dumpsys input). 348 // In the java layer, touch mode states are spread across multiple DisplayContent objects, 349 // making harder to snapshot and retrieve them. 350 std::map<ui::LogicalDisplayId /*displayId*/, bool /*inTouchMode*/> mTouchModePerDisplay 351 GUARDED_BY(mLock); 352 353 class DispatcherWindowListener : public gui::WindowInfosListener { 354 public: DispatcherWindowListener(InputDispatcher & dispatcher)355 explicit DispatcherWindowListener(InputDispatcher& dispatcher) : mDispatcher(dispatcher){}; 356 void onWindowInfosChanged(const gui::WindowInfosUpdate&) override; 357 358 private: 359 InputDispatcher& mDispatcher; 360 }; 361 sp<gui::WindowInfosListener> mWindowInfoListener; 362 363 std::unordered_map<ui::LogicalDisplayId /*displayId*/, 364 std::vector<sp<android::gui::WindowInfoHandle>>> 365 mWindowHandlesByDisplay GUARDED_BY(mLock); 366 std::unordered_map<ui::LogicalDisplayId /*displayId*/, android::gui::DisplayInfo> mDisplayInfos 367 GUARDED_BY(mLock); 368 void setInputWindowsLocked( 369 const std::vector<sp<android::gui::WindowInfoHandle>>& inputWindowHandles, 370 ui::LogicalDisplayId displayId) REQUIRES(mLock); 371 // Get a reference to window handles by display, return an empty vector if not found. 372 const std::vector<sp<android::gui::WindowInfoHandle>>& getWindowHandlesLocked( 373 ui::LogicalDisplayId displayId) const REQUIRES(mLock); 374 ui::Transform getTransformLocked(ui::LogicalDisplayId displayId) const REQUIRES(mLock); 375 376 sp<android::gui::WindowInfoHandle> getWindowHandleLocked( 377 const sp<IBinder>& windowHandleToken, 378 std::optional<ui::LogicalDisplayId> displayId = {}) const REQUIRES(mLock); 379 sp<android::gui::WindowInfoHandle> getWindowHandleLocked( 380 const sp<android::gui::WindowInfoHandle>& windowHandle) const REQUIRES(mLock); 381 sp<android::gui::WindowInfoHandle> getFocusedWindowHandleLocked( 382 ui::LogicalDisplayId displayId) const REQUIRES(mLock); 383 bool canWindowReceiveMotionLocked(const sp<android::gui::WindowInfoHandle>& window, 384 const MotionEntry& motionEntry) const REQUIRES(mLock); 385 386 // Returns all the input targets (with their respective input channels) from the window handles 387 // passed as argument. 388 std::vector<InputTarget> getInputTargetsFromWindowHandlesLocked( 389 const std::vector<sp<android::gui::WindowInfoHandle>>& windowHandles) const 390 REQUIRES(mLock); 391 392 /* 393 * Validate and update InputWindowHandles for a given display. 394 */ 395 void updateWindowHandlesForDisplayLocked( 396 const std::vector<sp<android::gui::WindowInfoHandle>>& inputWindowHandles, 397 ui::LogicalDisplayId displayId) REQUIRES(mLock); 398 399 std::unordered_map<ui::LogicalDisplayId /*displayId*/, TouchState> mTouchStatesByDisplay 400 GUARDED_BY(mLock); 401 std::unique_ptr<DragState> mDragState GUARDED_BY(mLock); 402 403 void setFocusedApplicationLocked( 404 ui::LogicalDisplayId displayId, 405 const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) REQUIRES(mLock); 406 // Focused applications. 407 std::unordered_map<ui::LogicalDisplayId /*displayId*/, std::shared_ptr<InputApplicationHandle>> 408 mFocusedApplicationHandlesByDisplay GUARDED_BY(mLock); 409 410 // Top focused display. 411 ui::LogicalDisplayId 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<ui::LogicalDisplayId /*displayId*/> mIneligibleDisplaysForPointerCapture 429 GUARDED_BY(mLock); 430 431 // Disable Pointer Capture as a result of loss of window focus. 432 void disablePointerCaptureForcedLocked() REQUIRES(mLock); 433 434 // Set the Pointer Capture state in the Policy. 435 // The window is not nullptr for requests to enable, otherwise it is nullptr. 436 void setPointerCaptureLocked(const sp<IBinder>& window) REQUIRES(mLock); 437 438 // Dispatcher state at time of last ANR. 439 std::string mLastAnrState GUARDED_BY(mLock); 440 441 // The connection tokens of the channels that the user last interacted (used for debugging and 442 // when switching touch mode state). 443 std::unordered_set<sp<IBinder>, StrongPointerHash<IBinder>> mInteractionConnectionTokens 444 GUARDED_BY(mLock); 445 void processInteractionsLocked(const EventEntry& entry, const std::vector<InputTarget>& targets) 446 REQUIRES(mLock); 447 448 // Dispatch inbound events. 449 bool dispatchConfigurationChangedLocked(nsecs_t currentTime, 450 const ConfigurationChangedEntry& entry) REQUIRES(mLock); 451 bool dispatchDeviceResetLocked(nsecs_t currentTime, const DeviceResetEntry& entry) 452 REQUIRES(mLock); 453 bool dispatchKeyLocked(nsecs_t currentTime, std::shared_ptr<const KeyEntry> entry, 454 DropReason* dropReason, nsecs_t& nextWakeupTime) REQUIRES(mLock); 455 bool dispatchMotionLocked(nsecs_t currentTime, std::shared_ptr<const MotionEntry> entry, 456 DropReason* dropReason, nsecs_t& nextWakeupTime) REQUIRES(mLock); 457 void dispatchFocusLocked(nsecs_t currentTime, std::shared_ptr<const FocusEntry> entry) 458 REQUIRES(mLock); 459 void dispatchPointerCaptureChangedLocked( 460 nsecs_t currentTime, const std::shared_ptr<const PointerCaptureChangedEntry>& entry, 461 DropReason& dropReason) REQUIRES(mLock); 462 void dispatchTouchModeChangeLocked(nsecs_t currentTime, 463 const std::shared_ptr<const TouchModeEntry>& entry) 464 REQUIRES(mLock); 465 void dispatchEventLocked(nsecs_t currentTime, std::shared_ptr<const EventEntry> entry, 466 const std::vector<InputTarget>& inputTargets) REQUIRES(mLock); 467 void dispatchSensorLocked(nsecs_t currentTime, const std::shared_ptr<const SensorEntry>& entry, 468 DropReason* dropReason, nsecs_t& nextWakeupTime) REQUIRES(mLock); 469 void dispatchDragLocked(nsecs_t currentTime, std::shared_ptr<const DragEntry> entry) 470 REQUIRES(mLock); 471 void logOutboundKeyDetails(const char* prefix, const KeyEntry& entry); 472 void logOutboundMotionDetails(const char* prefix, const MotionEntry& entry); 473 474 /** 475 * This field is set if there is no focused window, and we have an event that requires 476 * a focused window to be dispatched (for example, a KeyEvent). 477 * When this happens, we will wait until *mNoFocusedWindowTimeoutTime before 478 * dropping the event and raising an ANR for that application. 479 * This is useful if an application is slow to add a focused window. 480 */ 481 std::optional<nsecs_t> mNoFocusedWindowTimeoutTime GUARDED_BY(mLock); 482 483 bool isStaleEvent(nsecs_t currentTime, const EventEntry& entry); 484 485 bool shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) const 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 ui::LogicalDisplayId 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<gui::Pid> pid, std::string reason) 519 REQUIRES(mLock); 520 void sendWindowResponsiveCommandLocked(const sp<IBinder>& connectionToken, 521 std::optional<gui::Pid> 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 void cancelEventsForAnrLocked(const std::shared_ptr<Connection>& connection) REQUIRES(mLock); 531 // If a focused application changes, we should stop counting down the "no focused window" time, 532 // because we will have no way of knowing when the previous application actually added a window. 533 // This also means that we will miss cases like pulling down notification shade when the 534 // focused application does not have a focused window (no ANR will be raised if notification 535 // shade is pulled down while we are counting down the timeout). 536 void resetNoFocusedWindowTimeoutLocked() REQUIRES(mLock); 537 538 ui::LogicalDisplayId getTargetDisplayId(const EventEntry& entry); 539 sp<android::gui::WindowInfoHandle> findFocusedWindowTargetLocked( 540 nsecs_t currentTime, const EventEntry& entry, nsecs_t& nextWakeupTime, 541 android::os::InputEventInjectionResult& outInjectionResult) REQUIRES(mLock); 542 std::vector<InputTarget> findTouchedWindowTargetsLocked( 543 nsecs_t currentTime, const MotionEntry& entry, 544 android::os::InputEventInjectionResult& outInjectionResult) REQUIRES(mLock); 545 std::vector<Monitor> selectResponsiveMonitorsLocked( 546 const std::vector<Monitor>& gestureMonitors) const REQUIRES(mLock); 547 548 std::optional<InputTarget> createInputTargetLocked( 549 const sp<android::gui::WindowInfoHandle>& windowHandle, 550 InputTarget::DispatchMode dispatchMode, ftl::Flags<InputTarget::Flags> targetFlags, 551 std::optional<nsecs_t> firstDownTimeInTarget) const REQUIRES(mLock); 552 void addWindowTargetLocked(const sp<android::gui::WindowInfoHandle>& windowHandle, 553 InputTarget::DispatchMode dispatchMode, 554 ftl::Flags<InputTarget::Flags> targetFlags, 555 std::optional<nsecs_t> firstDownTimeInTarget, 556 std::vector<InputTarget>& inputTargets) const REQUIRES(mLock); 557 void addPointerWindowTargetLocked(const sp<android::gui::WindowInfoHandle>& windowHandle, 558 InputTarget::DispatchMode dispatchMode, 559 ftl::Flags<InputTarget::Flags> targetFlags, 560 std::bitset<MAX_POINTER_ID + 1> pointerIds, 561 std::optional<nsecs_t> firstDownTimeInTarget, 562 std::vector<InputTarget>& inputTargets) const REQUIRES(mLock); 563 void addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets, 564 ui::LogicalDisplayId displayId) REQUIRES(mLock); 565 void pokeUserActivityLocked(const EventEntry& eventEntry) REQUIRES(mLock); 566 // Enqueue a drag event if needed, and update the touch state. 567 // Uses findTouchedWindowTargetsLocked to make the decision 568 void addDragEventLocked(const MotionEntry& entry) REQUIRES(mLock); 569 void finishDragAndDrop(ui::LogicalDisplayId displayId, float x, float y) REQUIRES(mLock); 570 571 struct TouchOcclusionInfo { 572 bool hasBlockingOcclusion; 573 float obscuringOpacity; 574 std::string obscuringPackage; 575 gui::Uid obscuringUid = gui::Uid::INVALID; 576 std::vector<std::string> debugInfo; 577 }; 578 579 TouchOcclusionInfo computeTouchOcclusionInfoLocked( 580 const sp<android::gui::WindowInfoHandle>& windowHandle, float x, float y) const 581 REQUIRES(mLock); 582 bool isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const REQUIRES(mLock); 583 bool isWindowObscuredAtPointLocked(const sp<android::gui::WindowInfoHandle>& windowHandle, 584 float x, float y) const REQUIRES(mLock); 585 bool isWindowObscuredLocked(const sp<android::gui::WindowInfoHandle>& windowHandle) const 586 REQUIRES(mLock); 587 std::string dumpWindowForTouchOcclusion(const android::gui::WindowInfo* info, 588 bool isTouchWindow) const; 589 std::string getApplicationWindowLabel(const InputApplicationHandle* applicationHandle, 590 const sp<android::gui::WindowInfoHandle>& windowHandle); 591 592 bool shouldDropInput(const EventEntry& entry, 593 const sp<android::gui::WindowInfoHandle>& windowHandle) const 594 REQUIRES(mLock); 595 596 // Manage the dispatch cycle for a single connection. 597 // These methods are deliberately not Interruptible because doing all of the work 598 // with the mutex held makes it easier to ensure that connection invariants are maintained. 599 // If needed, the methods post commands to run later once the critical bits are done. 600 void prepareDispatchCycleLocked(nsecs_t currentTime, 601 const std::shared_ptr<Connection>& connection, 602 std::shared_ptr<const EventEntry>, 603 const InputTarget& inputTarget) REQUIRES(mLock); 604 void enqueueDispatchEntryAndStartDispatchCycleLocked( 605 nsecs_t currentTime, const std::shared_ptr<Connection>& connection, 606 std::shared_ptr<const EventEntry>, const InputTarget& inputTarget) REQUIRES(mLock); 607 void enqueueDispatchEntryLocked(const std::shared_ptr<Connection>& connection, 608 std::shared_ptr<const EventEntry>, 609 const InputTarget& inputTarget) REQUIRES(mLock); 610 status_t publishMotionEvent(Connection& connection, DispatchEntry& dispatchEntry) const; 611 void startDispatchCycleLocked(nsecs_t currentTime, 612 const std::shared_ptr<Connection>& connection) REQUIRES(mLock); 613 void finishDispatchCycleLocked(nsecs_t currentTime, 614 const std::shared_ptr<Connection>& connection, uint32_t seq, 615 bool handled, nsecs_t consumeTime) REQUIRES(mLock); 616 void abortBrokenDispatchCycleLocked(nsecs_t currentTime, 617 const std::shared_ptr<Connection>& connection, bool notify) 618 REQUIRES(mLock); 619 void drainDispatchQueue(std::deque<std::unique_ptr<DispatchEntry>>& queue); 620 void releaseDispatchEntry(std::unique_ptr<DispatchEntry> dispatchEntry); 621 int handleReceiveCallback(int events, sp<IBinder> connectionToken); 622 // The action sent should only be of type AMOTION_EVENT_* 623 void dispatchPointerDownOutsideFocus(uint32_t source, int32_t action, 624 const sp<IBinder>& newToken) REQUIRES(mLock); 625 626 void synthesizeCancelationEventsForAllConnectionsLocked(const CancelationOptions& options) 627 REQUIRES(mLock); 628 void synthesizeCancelationEventsForMonitorsLocked(const CancelationOptions& options) 629 REQUIRES(mLock); 630 void synthesizeCancelationEventsForWindowLocked(const sp<gui::WindowInfoHandle>&, 631 const CancelationOptions&, 632 const std::shared_ptr<Connection>& = nullptr) 633 REQUIRES(mLock); 634 // This is a convenience function used to generate cancellation for a connection without having 635 // to check whether it's a monitor or a window. For non-monitors, the window handle must not be 636 // null. Always prefer the "-ForWindow" method above when explicitly dealing with windows. 637 void synthesizeCancelationEventsForConnectionLocked( 638 const std::shared_ptr<Connection>& connection, const CancelationOptions& options, 639 const sp<gui::WindowInfoHandle>& window) REQUIRES(mLock); 640 641 void synthesizePointerDownEventsForConnectionLocked( 642 const nsecs_t downTime, const std::shared_ptr<Connection>& connection, 643 ftl::Flags<InputTarget::Flags> targetFlags, 644 const std::unique_ptr<trace::EventTrackerInterface>& traceTracker) REQUIRES(mLock); 645 646 // Splitting motion events across windows. When splitting motion event for a target, 647 // splitDownTime refers to the time of first 'down' event on that particular target 648 std::unique_ptr<MotionEntry> splitMotionEvent(const MotionEntry& originalMotionEntry, 649 std::bitset<MAX_POINTER_ID + 1> pointerIds, 650 nsecs_t splitDownTime) REQUIRES(mLock); 651 652 // Reset and drop everything the dispatcher is doing. 653 void resetAndDropEverythingLocked(const char* reason) REQUIRES(mLock); 654 655 // Dump state. 656 void dumpDispatchStateLocked(std::string& dump) const REQUIRES(mLock); 657 void dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) const; 658 void logDispatchStateLocked() const REQUIRES(mLock); 659 std::string dumpPointerCaptureStateLocked() const REQUIRES(mLock); 660 661 // Registration. 662 void removeMonitorChannelLocked(const sp<IBinder>& connectionToken) REQUIRES(mLock); 663 status_t removeInputChannelLocked(const sp<IBinder>& connectionToken, bool notify) 664 REQUIRES(mLock); 665 666 // Interesting events that we might like to log or tell the framework about. 667 void doDispatchCycleFinishedCommand(nsecs_t finishTime, 668 const std::shared_ptr<Connection>& connection, uint32_t seq, 669 bool handled, nsecs_t consumeTime) REQUIRES(mLock); 670 void doInterceptKeyBeforeDispatchingCommand(const sp<IBinder>& focusedWindowToken, 671 const KeyEntry& entry) REQUIRES(mLock); 672 void onFocusChangedLocked(const FocusResolver::FocusChanges& changes, 673 const std::unique_ptr<trace::EventTrackerInterface>& traceTracker, 674 const sp<gui::WindowInfoHandle> removedFocusedWindowHandle = nullptr) 675 REQUIRES(mLock); 676 void sendFocusChangedCommandLocked(const sp<IBinder>& oldToken, const sp<IBinder>& newToken) 677 REQUIRES(mLock); 678 void sendDropWindowCommandLocked(const sp<IBinder>& token, float x, float y) REQUIRES(mLock); 679 void onAnrLocked(const std::shared_ptr<Connection>& connection) REQUIRES(mLock); 680 void onAnrLocked(std::shared_ptr<InputApplicationHandle> application) REQUIRES(mLock); 681 void updateLastAnrStateLocked(const sp<android::gui::WindowInfoHandle>& window, 682 const std::string& reason) REQUIRES(mLock); 683 void updateLastAnrStateLocked(const InputApplicationHandle& application, 684 const std::string& reason) REQUIRES(mLock); 685 void updateLastAnrStateLocked(const std::string& windowLabel, const std::string& reason) 686 REQUIRES(mLock); 687 std::map<ui::LogicalDisplayId /*displayId*/, InputVerifier> mVerifiersByDisplay; 688 // Returns a fallback KeyEntry that should be sent to the connection, if required. 689 std::unique_ptr<const KeyEntry> afterKeyEventLockedInterruptable( 690 const std::shared_ptr<Connection>& connection, DispatchEntry* dispatchEntry, 691 bool handled) REQUIRES(mLock); 692 693 // Find touched state and touched window by token. 694 std::tuple<TouchState*, TouchedWindow*, ui::LogicalDisplayId /*displayId*/> 695 findTouchStateWindowAndDisplayLocked(const sp<IBinder>& token) REQUIRES(mLock); 696 697 // Statistics gathering. 698 LatencyAggregator mLatencyAggregator GUARDED_BY(mLock); 699 LatencyTracker mLatencyTracker GUARDED_BY(mLock); 700 void traceInboundQueueLengthLocked() REQUIRES(mLock); 701 void traceOutboundQueueLength(const Connection& connection); 702 void traceWaitQueueLength(const Connection& connection); 703 704 // Check window ownership 705 bool focusedWindowIsOwnedByLocked(gui::Pid pid, gui::Uid uid) REQUIRES(mLock); 706 bool recentWindowsAreOwnedByLocked(gui::Pid pid, gui::Uid uid) REQUIRES(mLock); 707 708 sp<InputReporterInterface> mReporter; 709 710 void slipWallpaperTouch(ftl::Flags<InputTarget::Flags> targetFlags, 711 const sp<android::gui::WindowInfoHandle>& oldWindowHandle, 712 const sp<android::gui::WindowInfoHandle>& newWindowHandle, 713 TouchState& state, DeviceId deviceId, 714 const PointerProperties& pointerProperties, 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, DeviceId deviceId, 721 const std::vector<PointerProperties>& pointers, 722 const std::unique_ptr<trace::EventTrackerInterface>& traceTracker) 723 REQUIRES(mLock); 724 725 sp<android::gui::WindowInfoHandle> findWallpaperWindowBelow( 726 const sp<android::gui::WindowInfoHandle>& windowHandle) const REQUIRES(mLock); 727 }; 728 729 } // namespace android::inputdispatcher 730