/services/input/InputDispatcher.h

https://github.com/aizuzi/platform_frameworks_base · C Header · 1123 lines · 633 code · 210 blank · 280 comment · 11 complexity · aaba9d79627767f56e569b3ad7b026c1 MD5 · raw file

  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. #ifndef _UI_INPUT_DISPATCHER_H
  17. #define _UI_INPUT_DISPATCHER_H
  18. #include <input/Input.h>
  19. #include <input/InputTransport.h>
  20. #include <utils/KeyedVector.h>
  21. #include <utils/Vector.h>
  22. #include <utils/threads.h>
  23. #include <utils/Timers.h>
  24. #include <utils/RefBase.h>
  25. #include <utils/String8.h>
  26. #include <utils/Looper.h>
  27. #include <utils/BitSet.h>
  28. #include <cutils/atomic.h>
  29. #include <stddef.h>
  30. #include <unistd.h>
  31. #include <limits.h>
  32. #include "InputWindow.h"
  33. #include "InputApplication.h"
  34. #include "InputListener.h"
  35. namespace android {
  36. /*
  37. * Constants used to report the outcome of input event injection.
  38. */
  39. enum {
  40. /* (INTERNAL USE ONLY) Specifies that injection is pending and its outcome is unknown. */
  41. INPUT_EVENT_INJECTION_PENDING = -1,
  42. /* Injection succeeded. */
  43. INPUT_EVENT_INJECTION_SUCCEEDED = 0,
  44. /* Injection failed because the injector did not have permission to inject
  45. * into the application with input focus. */
  46. INPUT_EVENT_INJECTION_PERMISSION_DENIED = 1,
  47. /* Injection failed because there were no available input targets. */
  48. INPUT_EVENT_INJECTION_FAILED = 2,
  49. /* Injection failed due to a timeout. */
  50. INPUT_EVENT_INJECTION_TIMED_OUT = 3
  51. };
  52. /*
  53. * Constants used to determine the input event injection synchronization mode.
  54. */
  55. enum {
  56. /* Injection is asynchronous and is assumed always to be successful. */
  57. INPUT_EVENT_INJECTION_SYNC_NONE = 0,
  58. /* Waits for previous events to be dispatched so that the input dispatcher can determine
  59. * whether input event injection willbe permitted based on the current input focus.
  60. * Does not wait for the input event to finish processing. */
  61. INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_RESULT = 1,
  62. /* Waits for the input event to be completely processed. */
  63. INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_FINISHED = 2,
  64. };
  65. /*
  66. * An input target specifies how an input event is to be dispatched to a particular window
  67. * including the window's input channel, control flags, a timeout, and an X / Y offset to
  68. * be added to input event coordinates to compensate for the absolute position of the
  69. * window area.
  70. */
  71. struct InputTarget {
  72. enum {
  73. /* This flag indicates that the event is being delivered to a foreground application. */
  74. FLAG_FOREGROUND = 1 << 0,
  75. /* This flag indicates that the target of a MotionEvent is partly or wholly
  76. * obscured by another visible window above it. The motion event should be
  77. * delivered with flag AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED. */
  78. FLAG_WINDOW_IS_OBSCURED = 1 << 1,
  79. /* This flag indicates that a motion event is being split across multiple windows. */
  80. FLAG_SPLIT = 1 << 2,
  81. /* This flag indicates that the pointer coordinates dispatched to the application
  82. * will be zeroed out to avoid revealing information to an application. This is
  83. * used in conjunction with FLAG_DISPATCH_AS_OUTSIDE to prevent apps not sharing
  84. * the same UID from watching all touches. */
  85. FLAG_ZERO_COORDS = 1 << 3,
  86. /* This flag indicates that the event should be sent as is.
  87. * Should always be set unless the event is to be transmuted. */
  88. FLAG_DISPATCH_AS_IS = 1 << 8,
  89. /* This flag indicates that a MotionEvent with AMOTION_EVENT_ACTION_DOWN falls outside
  90. * of the area of this target and so should instead be delivered as an
  91. * AMOTION_EVENT_ACTION_OUTSIDE to this target. */
  92. FLAG_DISPATCH_AS_OUTSIDE = 1 << 9,
  93. /* This flag indicates that a hover sequence is starting in the given window.
  94. * The event is transmuted into ACTION_HOVER_ENTER. */
  95. FLAG_DISPATCH_AS_HOVER_ENTER = 1 << 10,
  96. /* This flag indicates that a hover event happened outside of a window which handled
  97. * previous hover events, signifying the end of the current hover sequence for that
  98. * window.
  99. * The event is transmuted into ACTION_HOVER_ENTER. */
  100. FLAG_DISPATCH_AS_HOVER_EXIT = 1 << 11,
  101. /* This flag indicates that the event should be canceled.
  102. * It is used to transmute ACTION_MOVE into ACTION_CANCEL when a touch slips
  103. * outside of a window. */
  104. FLAG_DISPATCH_AS_SLIPPERY_EXIT = 1 << 12,
  105. /* This flag indicates that the event should be dispatched as an initial down.
  106. * It is used to transmute ACTION_MOVE into ACTION_DOWN when a touch slips
  107. * into a new window. */
  108. FLAG_DISPATCH_AS_SLIPPERY_ENTER = 1 << 13,
  109. /* Mask for all dispatch modes. */
  110. FLAG_DISPATCH_MASK = FLAG_DISPATCH_AS_IS
  111. | FLAG_DISPATCH_AS_OUTSIDE
  112. | FLAG_DISPATCH_AS_HOVER_ENTER
  113. | FLAG_DISPATCH_AS_HOVER_EXIT
  114. | FLAG_DISPATCH_AS_SLIPPERY_EXIT
  115. | FLAG_DISPATCH_AS_SLIPPERY_ENTER,
  116. };
  117. // The input channel to be targeted.
  118. sp<InputChannel> inputChannel;
  119. // Flags for the input target.
  120. int32_t flags;
  121. // The x and y offset to add to a MotionEvent as it is delivered.
  122. // (ignored for KeyEvents)
  123. float xOffset, yOffset;
  124. // Scaling factor to apply to MotionEvent as it is delivered.
  125. // (ignored for KeyEvents)
  126. float scaleFactor;
  127. // The subset of pointer ids to include in motion events dispatched to this input target
  128. // if FLAG_SPLIT is set.
  129. BitSet32 pointerIds;
  130. };
  131. /*
  132. * Input dispatcher configuration.
  133. *
  134. * Specifies various options that modify the behavior of the input dispatcher.
  135. * The values provided here are merely defaults. The actual values will come from ViewConfiguration
  136. * and are passed into the dispatcher during initialization.
  137. */
  138. struct InputDispatcherConfiguration {
  139. // The key repeat initial timeout.
  140. nsecs_t keyRepeatTimeout;
  141. // The key repeat inter-key delay.
  142. nsecs_t keyRepeatDelay;
  143. InputDispatcherConfiguration() :
  144. keyRepeatTimeout(500 * 1000000LL),
  145. keyRepeatDelay(50 * 1000000LL) { }
  146. };
  147. /*
  148. * Input dispatcher policy interface.
  149. *
  150. * The input reader policy is used by the input reader to interact with the Window Manager
  151. * and other system components.
  152. *
  153. * The actual implementation is partially supported by callbacks into the DVM
  154. * via JNI. This interface is also mocked in the unit tests.
  155. */
  156. class InputDispatcherPolicyInterface : public virtual RefBase {
  157. protected:
  158. InputDispatcherPolicyInterface() { }
  159. virtual ~InputDispatcherPolicyInterface() { }
  160. public:
  161. /* Notifies the system that a configuration change has occurred. */
  162. virtual void notifyConfigurationChanged(nsecs_t when) = 0;
  163. /* Notifies the system that an application is not responding.
  164. * Returns a new timeout to continue waiting, or 0 to abort dispatch. */
  165. virtual nsecs_t notifyANR(const sp<InputApplicationHandle>& inputApplicationHandle,
  166. const sp<InputWindowHandle>& inputWindowHandle,
  167. const String8& reason) = 0;
  168. /* Notifies the system that an input channel is unrecoverably broken. */
  169. virtual void notifyInputChannelBroken(const sp<InputWindowHandle>& inputWindowHandle) = 0;
  170. /* Gets the input dispatcher configuration. */
  171. virtual void getDispatcherConfiguration(InputDispatcherConfiguration* outConfig) = 0;
  172. /* Returns true if automatic key repeating is enabled. */
  173. virtual bool isKeyRepeatEnabled() = 0;
  174. /* Filters an input event.
  175. * Return true to dispatch the event unmodified, false to consume the event.
  176. * A filter can also transform and inject events later by passing POLICY_FLAG_FILTERED
  177. * to injectInputEvent.
  178. */
  179. virtual bool filterInputEvent(const InputEvent* inputEvent, uint32_t policyFlags) = 0;
  180. /* Intercepts a key event immediately before queueing it.
  181. * The policy can use this method as an opportunity to perform power management functions
  182. * and early event preprocessing such as updating policy flags.
  183. *
  184. * This method is expected to set the POLICY_FLAG_PASS_TO_USER policy flag if the event
  185. * should be dispatched to applications.
  186. */
  187. virtual void interceptKeyBeforeQueueing(const KeyEvent* keyEvent, uint32_t& policyFlags) = 0;
  188. /* Intercepts a touch, trackball or other motion event before queueing it.
  189. * The policy can use this method as an opportunity to perform power management functions
  190. * and early event preprocessing such as updating policy flags.
  191. *
  192. * This method is expected to set the POLICY_FLAG_PASS_TO_USER policy flag if the event
  193. * should be dispatched to applications.
  194. */
  195. virtual void interceptMotionBeforeQueueing(nsecs_t when, uint32_t& policyFlags) = 0;
  196. /* Allows the policy a chance to intercept a key before dispatching. */
  197. virtual nsecs_t interceptKeyBeforeDispatching(const sp<InputWindowHandle>& inputWindowHandle,
  198. const KeyEvent* keyEvent, uint32_t policyFlags) = 0;
  199. /* Allows the policy a chance to perform default processing for an unhandled key.
  200. * Returns an alternate keycode to redispatch as a fallback, or 0 to give up. */
  201. virtual bool dispatchUnhandledKey(const sp<InputWindowHandle>& inputWindowHandle,
  202. const KeyEvent* keyEvent, uint32_t policyFlags, KeyEvent* outFallbackKeyEvent) = 0;
  203. /* Notifies the policy about switch events.
  204. */
  205. virtual void notifySwitch(nsecs_t when,
  206. uint32_t switchValues, uint32_t switchMask, uint32_t policyFlags) = 0;
  207. /* Poke user activity for an event dispatched to a window. */
  208. virtual void pokeUserActivity(nsecs_t eventTime, int32_t eventType) = 0;
  209. /* Checks whether a given application pid/uid has permission to inject input events
  210. * into other applications.
  211. *
  212. * This method is special in that its implementation promises to be non-reentrant and
  213. * is safe to call while holding other locks. (Most other methods make no such guarantees!)
  214. */
  215. virtual bool checkInjectEventsPermissionNonReentrant(
  216. int32_t injectorPid, int32_t injectorUid) = 0;
  217. };
  218. /* Notifies the system about input events generated by the input reader.
  219. * The dispatcher is expected to be mostly asynchronous. */
  220. class InputDispatcherInterface : public virtual RefBase, public InputListenerInterface {
  221. protected:
  222. InputDispatcherInterface() { }
  223. virtual ~InputDispatcherInterface() { }
  224. public:
  225. /* Dumps the state of the input dispatcher.
  226. *
  227. * This method may be called on any thread (usually by the input manager). */
  228. virtual void dump(String8& dump) = 0;
  229. /* Called by the heatbeat to ensures that the dispatcher has not deadlocked. */
  230. virtual void monitor() = 0;
  231. /* Runs a single iteration of the dispatch loop.
  232. * Nominally processes one queued event, a timeout, or a response from an input consumer.
  233. *
  234. * This method should only be called on the input dispatcher thread.
  235. */
  236. virtual void dispatchOnce() = 0;
  237. /* Injects an input event and optionally waits for sync.
  238. * The synchronization mode determines whether the method blocks while waiting for
  239. * input injection to proceed.
  240. * Returns one of the INPUT_EVENT_INJECTION_XXX constants.
  241. *
  242. * This method may be called on any thread (usually by the input manager).
  243. */
  244. virtual int32_t injectInputEvent(const InputEvent* event,
  245. int32_t injectorPid, int32_t injectorUid, int32_t syncMode, int32_t timeoutMillis,
  246. uint32_t policyFlags) = 0;
  247. /* Sets the list of input windows.
  248. *
  249. * This method may be called on any thread (usually by the input manager).
  250. */
  251. virtual void setInputWindows(const Vector<sp<InputWindowHandle> >& inputWindowHandles) = 0;
  252. /* Sets the focused application.
  253. *
  254. * This method may be called on any thread (usually by the input manager).
  255. */
  256. virtual void setFocusedApplication(
  257. const sp<InputApplicationHandle>& inputApplicationHandle) = 0;
  258. /* Sets the input dispatching mode.
  259. *
  260. * This method may be called on any thread (usually by the input manager).
  261. */
  262. virtual void setInputDispatchMode(bool enabled, bool frozen) = 0;
  263. /* Sets whether input event filtering is enabled.
  264. * When enabled, incoming input events are sent to the policy's filterInputEvent
  265. * method instead of being dispatched. The filter is expected to use
  266. * injectInputEvent to inject the events it would like to have dispatched.
  267. * It should include POLICY_FLAG_FILTERED in the policy flags during injection.
  268. */
  269. virtual void setInputFilterEnabled(bool enabled) = 0;
  270. /* Transfers touch focus from the window associated with one channel to the
  271. * window associated with the other channel.
  272. *
  273. * Returns true on success. False if the window did not actually have touch focus.
  274. */
  275. virtual bool transferTouchFocus(const sp<InputChannel>& fromChannel,
  276. const sp<InputChannel>& toChannel) = 0;
  277. /* Registers or unregister input channels that may be used as targets for input events.
  278. * If monitor is true, the channel will receive a copy of all input events.
  279. *
  280. * These methods may be called on any thread (usually by the input manager).
  281. */
  282. virtual status_t registerInputChannel(const sp<InputChannel>& inputChannel,
  283. const sp<InputWindowHandle>& inputWindowHandle, bool monitor) = 0;
  284. virtual status_t unregisterInputChannel(const sp<InputChannel>& inputChannel) = 0;
  285. };
  286. /* Dispatches events to input targets. Some functions of the input dispatcher, such as
  287. * identifying input targets, are controlled by a separate policy object.
  288. *
  289. * IMPORTANT INVARIANT:
  290. * Because the policy can potentially block or cause re-entrance into the input dispatcher,
  291. * the input dispatcher never calls into the policy while holding its internal locks.
  292. * The implementation is also carefully designed to recover from scenarios such as an
  293. * input channel becoming unregistered while identifying input targets or processing timeouts.
  294. *
  295. * Methods marked 'Locked' must be called with the lock acquired.
  296. *
  297. * Methods marked 'LockedInterruptible' must be called with the lock acquired but
  298. * may during the course of their execution release the lock, call into the policy, and
  299. * then reacquire the lock. The caller is responsible for recovering gracefully.
  300. *
  301. * A 'LockedInterruptible' method may called a 'Locked' method, but NOT vice-versa.
  302. */
  303. class InputDispatcher : public InputDispatcherInterface {
  304. protected:
  305. virtual ~InputDispatcher();
  306. public:
  307. explicit InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy);
  308. virtual void dump(String8& dump);
  309. virtual void monitor();
  310. virtual void dispatchOnce();
  311. virtual void notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args);
  312. virtual void notifyKey(const NotifyKeyArgs* args);
  313. virtual void notifyMotion(const NotifyMotionArgs* args);
  314. virtual void notifySwitch(const NotifySwitchArgs* args);
  315. virtual void notifyDeviceReset(const NotifyDeviceResetArgs* args);
  316. virtual int32_t injectInputEvent(const InputEvent* event,
  317. int32_t injectorPid, int32_t injectorUid, int32_t syncMode, int32_t timeoutMillis,
  318. uint32_t policyFlags);
  319. virtual void setInputWindows(const Vector<sp<InputWindowHandle> >& inputWindowHandles);
  320. virtual void setFocusedApplication(const sp<InputApplicationHandle>& inputApplicationHandle);
  321. virtual void setInputDispatchMode(bool enabled, bool frozen);
  322. virtual void setInputFilterEnabled(bool enabled);
  323. virtual bool transferTouchFocus(const sp<InputChannel>& fromChannel,
  324. const sp<InputChannel>& toChannel);
  325. virtual status_t registerInputChannel(const sp<InputChannel>& inputChannel,
  326. const sp<InputWindowHandle>& inputWindowHandle, bool monitor);
  327. virtual status_t unregisterInputChannel(const sp<InputChannel>& inputChannel);
  328. private:
  329. template <typename T>
  330. struct Link {
  331. T* next;
  332. T* prev;
  333. protected:
  334. inline Link() : next(NULL), prev(NULL) { }
  335. };
  336. struct InjectionState {
  337. mutable int32_t refCount;
  338. int32_t injectorPid;
  339. int32_t injectorUid;
  340. int32_t injectionResult; // initially INPUT_EVENT_INJECTION_PENDING
  341. bool injectionIsAsync; // set to true if injection is not waiting for the result
  342. int32_t pendingForegroundDispatches; // the number of foreground dispatches in progress
  343. InjectionState(int32_t injectorPid, int32_t injectorUid);
  344. void release();
  345. private:
  346. ~InjectionState();
  347. };
  348. struct EventEntry : Link<EventEntry> {
  349. enum {
  350. TYPE_CONFIGURATION_CHANGED,
  351. TYPE_DEVICE_RESET,
  352. TYPE_KEY,
  353. TYPE_MOTION
  354. };
  355. mutable int32_t refCount;
  356. int32_t type;
  357. nsecs_t eventTime;
  358. uint32_t policyFlags;
  359. InjectionState* injectionState;
  360. bool dispatchInProgress; // initially false, set to true while dispatching
  361. inline bool isInjected() const { return injectionState != NULL; }
  362. void release();
  363. virtual void appendDescription(String8& msg) const = 0;
  364. protected:
  365. EventEntry(int32_t type, nsecs_t eventTime, uint32_t policyFlags);
  366. virtual ~EventEntry();
  367. void releaseInjectionState();
  368. };
  369. struct ConfigurationChangedEntry : EventEntry {
  370. ConfigurationChangedEntry(nsecs_t eventTime);
  371. virtual void appendDescription(String8& msg) const;
  372. protected:
  373. virtual ~ConfigurationChangedEntry();
  374. };
  375. struct DeviceResetEntry : EventEntry {
  376. int32_t deviceId;
  377. DeviceResetEntry(nsecs_t eventTime, int32_t deviceId);
  378. virtual void appendDescription(String8& msg) const;
  379. protected:
  380. virtual ~DeviceResetEntry();
  381. };
  382. struct KeyEntry : EventEntry {
  383. int32_t deviceId;
  384. uint32_t source;
  385. int32_t action;
  386. int32_t flags;
  387. int32_t keyCode;
  388. int32_t scanCode;
  389. int32_t metaState;
  390. int32_t repeatCount;
  391. nsecs_t downTime;
  392. bool syntheticRepeat; // set to true for synthetic key repeats
  393. enum InterceptKeyResult {
  394. INTERCEPT_KEY_RESULT_UNKNOWN,
  395. INTERCEPT_KEY_RESULT_SKIP,
  396. INTERCEPT_KEY_RESULT_CONTINUE,
  397. INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER,
  398. };
  399. InterceptKeyResult interceptKeyResult; // set based on the interception result
  400. nsecs_t interceptKeyWakeupTime; // used with INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER
  401. KeyEntry(nsecs_t eventTime,
  402. int32_t deviceId, uint32_t source, uint32_t policyFlags, int32_t action,
  403. int32_t flags, int32_t keyCode, int32_t scanCode, int32_t metaState,
  404. int32_t repeatCount, nsecs_t downTime);
  405. virtual void appendDescription(String8& msg) const;
  406. void recycle();
  407. protected:
  408. virtual ~KeyEntry();
  409. };
  410. struct MotionEntry : EventEntry {
  411. nsecs_t eventTime;
  412. int32_t deviceId;
  413. uint32_t source;
  414. int32_t action;
  415. int32_t flags;
  416. int32_t metaState;
  417. int32_t buttonState;
  418. int32_t edgeFlags;
  419. float xPrecision;
  420. float yPrecision;
  421. nsecs_t downTime;
  422. int32_t displayId;
  423. uint32_t pointerCount;
  424. PointerProperties pointerProperties[MAX_POINTERS];
  425. PointerCoords pointerCoords[MAX_POINTERS];
  426. MotionEntry(nsecs_t eventTime,
  427. int32_t deviceId, uint32_t source, uint32_t policyFlags,
  428. int32_t action, int32_t flags,
  429. int32_t metaState, int32_t buttonState, int32_t edgeFlags,
  430. float xPrecision, float yPrecision,
  431. nsecs_t downTime, int32_t displayId, uint32_t pointerCount,
  432. const PointerProperties* pointerProperties, const PointerCoords* pointerCoords);
  433. virtual void appendDescription(String8& msg) const;
  434. protected:
  435. virtual ~MotionEntry();
  436. };
  437. // Tracks the progress of dispatching a particular event to a particular connection.
  438. struct DispatchEntry : Link<DispatchEntry> {
  439. const uint32_t seq; // unique sequence number, never 0
  440. EventEntry* eventEntry; // the event to dispatch
  441. int32_t targetFlags;
  442. float xOffset;
  443. float yOffset;
  444. float scaleFactor;
  445. nsecs_t deliveryTime; // time when the event was actually delivered
  446. // Set to the resolved action and flags when the event is enqueued.
  447. int32_t resolvedAction;
  448. int32_t resolvedFlags;
  449. DispatchEntry(EventEntry* eventEntry,
  450. int32_t targetFlags, float xOffset, float yOffset, float scaleFactor);
  451. ~DispatchEntry();
  452. inline bool hasForegroundTarget() const {
  453. return targetFlags & InputTarget::FLAG_FOREGROUND;
  454. }
  455. inline bool isSplit() const {
  456. return targetFlags & InputTarget::FLAG_SPLIT;
  457. }
  458. private:
  459. static volatile int32_t sNextSeqAtomic;
  460. static uint32_t nextSeq();
  461. };
  462. // A command entry captures state and behavior for an action to be performed in the
  463. // dispatch loop after the initial processing has taken place. It is essentially
  464. // a kind of continuation used to postpone sensitive policy interactions to a point
  465. // in the dispatch loop where it is safe to release the lock (generally after finishing
  466. // the critical parts of the dispatch cycle).
  467. //
  468. // The special thing about commands is that they can voluntarily release and reacquire
  469. // the dispatcher lock at will. Initially when the command starts running, the
  470. // dispatcher lock is held. However, if the command needs to call into the policy to
  471. // do some work, it can release the lock, do the work, then reacquire the lock again
  472. // before returning.
  473. //
  474. // This mechanism is a bit clunky but it helps to preserve the invariant that the dispatch
  475. // never calls into the policy while holding its lock.
  476. //
  477. // Commands are implicitly 'LockedInterruptible'.
  478. struct CommandEntry;
  479. typedef void (InputDispatcher::*Command)(CommandEntry* commandEntry);
  480. class Connection;
  481. struct CommandEntry : Link<CommandEntry> {
  482. CommandEntry(Command command);
  483. ~CommandEntry();
  484. Command command;
  485. // parameters for the command (usage varies by command)
  486. sp<Connection> connection;
  487. nsecs_t eventTime;
  488. KeyEntry* keyEntry;
  489. sp<InputApplicationHandle> inputApplicationHandle;
  490. sp<InputWindowHandle> inputWindowHandle;
  491. String8 reason;
  492. int32_t userActivityEventType;
  493. uint32_t seq;
  494. bool handled;
  495. };
  496. // Generic queue implementation.
  497. template <typename T>
  498. struct Queue {
  499. T* head;
  500. T* tail;
  501. inline Queue() : head(NULL), tail(NULL) {
  502. }
  503. inline bool isEmpty() const {
  504. return !head;
  505. }
  506. inline void enqueueAtTail(T* entry) {
  507. entry->prev = tail;
  508. if (tail) {
  509. tail->next = entry;
  510. } else {
  511. head = entry;
  512. }
  513. entry->next = NULL;
  514. tail = entry;
  515. }
  516. inline void enqueueAtHead(T* entry) {
  517. entry->next = head;
  518. if (head) {
  519. head->prev = entry;
  520. } else {
  521. tail = entry;
  522. }
  523. entry->prev = NULL;
  524. head = entry;
  525. }
  526. inline void dequeue(T* entry) {
  527. if (entry->prev) {
  528. entry->prev->next = entry->next;
  529. } else {
  530. head = entry->next;
  531. }
  532. if (entry->next) {
  533. entry->next->prev = entry->prev;
  534. } else {
  535. tail = entry->prev;
  536. }
  537. }
  538. inline T* dequeueAtHead() {
  539. T* entry = head;
  540. head = entry->next;
  541. if (head) {
  542. head->prev = NULL;
  543. } else {
  544. tail = NULL;
  545. }
  546. return entry;
  547. }
  548. uint32_t count() const;
  549. };
  550. /* Specifies which events are to be canceled and why. */
  551. struct CancelationOptions {
  552. enum Mode {
  553. CANCEL_ALL_EVENTS = 0,
  554. CANCEL_POINTER_EVENTS = 1,
  555. CANCEL_NON_POINTER_EVENTS = 2,
  556. CANCEL_FALLBACK_EVENTS = 3,
  557. };
  558. // The criterion to use to determine which events should be canceled.
  559. Mode mode;
  560. // Descriptive reason for the cancelation.
  561. const char* reason;
  562. // The specific keycode of the key event to cancel, or -1 to cancel any key event.
  563. int32_t keyCode;
  564. // The specific device id of events to cancel, or -1 to cancel events from any device.
  565. int32_t deviceId;
  566. CancelationOptions(Mode mode, const char* reason) :
  567. mode(mode), reason(reason), keyCode(-1), deviceId(-1) { }
  568. };
  569. /* Tracks dispatched key and motion event state so that cancelation events can be
  570. * synthesized when events are dropped. */
  571. class InputState {
  572. public:
  573. InputState();
  574. ~InputState();
  575. // Returns true if there is no state to be canceled.
  576. bool isNeutral() const;
  577. // Returns true if the specified source is known to have received a hover enter
  578. // motion event.
  579. bool isHovering(int32_t deviceId, uint32_t source, int32_t displayId) const;
  580. // Records tracking information for a key event that has just been published.
  581. // Returns true if the event should be delivered, false if it is inconsistent
  582. // and should be skipped.
  583. bool trackKey(const KeyEntry* entry, int32_t action, int32_t flags);
  584. // Records tracking information for a motion event that has just been published.
  585. // Returns true if the event should be delivered, false if it is inconsistent
  586. // and should be skipped.
  587. bool trackMotion(const MotionEntry* entry, int32_t action, int32_t flags);
  588. // Synthesizes cancelation events for the current state and resets the tracked state.
  589. void synthesizeCancelationEvents(nsecs_t currentTime,
  590. Vector<EventEntry*>& outEvents, const CancelationOptions& options);
  591. // Clears the current state.
  592. void clear();
  593. // Copies pointer-related parts of the input state to another instance.
  594. void copyPointerStateTo(InputState& other) const;
  595. // Gets the fallback key associated with a keycode.
  596. // Returns -1 if none.
  597. // Returns AKEYCODE_UNKNOWN if we are only dispatching the unhandled key to the policy.
  598. int32_t getFallbackKey(int32_t originalKeyCode);
  599. // Sets the fallback key for a particular keycode.
  600. void setFallbackKey(int32_t originalKeyCode, int32_t fallbackKeyCode);
  601. // Removes the fallback key for a particular keycode.
  602. void removeFallbackKey(int32_t originalKeyCode);
  603. inline const KeyedVector<int32_t, int32_t>& getFallbackKeys() const {
  604. return mFallbackKeys;
  605. }
  606. private:
  607. struct KeyMemento {
  608. int32_t deviceId;
  609. uint32_t source;
  610. int32_t keyCode;
  611. int32_t scanCode;
  612. int32_t metaState;
  613. int32_t flags;
  614. nsecs_t downTime;
  615. uint32_t policyFlags;
  616. };
  617. struct MotionMemento {
  618. int32_t deviceId;
  619. uint32_t source;
  620. int32_t flags;
  621. float xPrecision;
  622. float yPrecision;
  623. nsecs_t downTime;
  624. int32_t displayId;
  625. uint32_t pointerCount;
  626. PointerProperties pointerProperties[MAX_POINTERS];
  627. PointerCoords pointerCoords[MAX_POINTERS];
  628. bool hovering;
  629. uint32_t policyFlags;
  630. void setPointers(const MotionEntry* entry);
  631. };
  632. Vector<KeyMemento> mKeyMementos;
  633. Vector<MotionMemento> mMotionMementos;
  634. KeyedVector<int32_t, int32_t> mFallbackKeys;
  635. ssize_t findKeyMemento(const KeyEntry* entry) const;
  636. ssize_t findMotionMemento(const MotionEntry* entry, bool hovering) const;
  637. void addKeyMemento(const KeyEntry* entry, int32_t flags);
  638. void addMotionMemento(const MotionEntry* entry, int32_t flags, bool hovering);
  639. static bool shouldCancelKey(const KeyMemento& memento,
  640. const CancelationOptions& options);
  641. static bool shouldCancelMotion(const MotionMemento& memento,
  642. const CancelationOptions& options);
  643. };
  644. /* Manages the dispatch state associated with a single input channel. */
  645. class Connection : public RefBase {
  646. protected:
  647. virtual ~Connection();
  648. public:
  649. enum Status {
  650. // Everything is peachy.
  651. STATUS_NORMAL,
  652. // An unrecoverable communication error has occurred.
  653. STATUS_BROKEN,
  654. // The input channel has been unregistered.
  655. STATUS_ZOMBIE
  656. };
  657. Status status;
  658. sp<InputChannel> inputChannel; // never null
  659. sp<InputWindowHandle> inputWindowHandle; // may be null
  660. bool monitor;
  661. InputPublisher inputPublisher;
  662. InputState inputState;
  663. // True if the socket is full and no further events can be published until
  664. // the application consumes some of the input.
  665. bool inputPublisherBlocked;
  666. // Queue of events that need to be published to the connection.
  667. Queue<DispatchEntry> outboundQueue;
  668. // Queue of events that have been published to the connection but that have not
  669. // yet received a "finished" response from the application.
  670. Queue<DispatchEntry> waitQueue;
  671. explicit Connection(const sp<InputChannel>& inputChannel,
  672. const sp<InputWindowHandle>& inputWindowHandle, bool monitor);
  673. inline const char* getInputChannelName() const { return inputChannel->getName().string(); }
  674. const char* getWindowName() const;
  675. const char* getStatusLabel() const;
  676. DispatchEntry* findWaitQueueEntry(uint32_t seq);
  677. };
  678. enum DropReason {
  679. DROP_REASON_NOT_DROPPED = 0,
  680. DROP_REASON_POLICY = 1,
  681. DROP_REASON_APP_SWITCH = 2,
  682. DROP_REASON_DISABLED = 3,
  683. DROP_REASON_BLOCKED = 4,
  684. DROP_REASON_STALE = 5,
  685. };
  686. sp<InputDispatcherPolicyInterface> mPolicy;
  687. InputDispatcherConfiguration mConfig;
  688. Mutex mLock;
  689. Condition mDispatcherIsAliveCondition;
  690. sp<Looper> mLooper;
  691. EventEntry* mPendingEvent;
  692. Queue<EventEntry> mInboundQueue;
  693. Queue<EventEntry> mRecentQueue;
  694. Queue<CommandEntry> mCommandQueue;
  695. void dispatchOnceInnerLocked(nsecs_t* nextWakeupTime);
  696. // Enqueues an inbound event. Returns true if mLooper->wake() should be called.
  697. bool enqueueInboundEventLocked(EventEntry* entry);
  698. // Cleans up input state when dropping an inbound event.
  699. void dropInboundEventLocked(EventEntry* entry, DropReason dropReason);
  700. // Adds an event to a queue of recent events for debugging purposes.
  701. void addRecentEventLocked(EventEntry* entry);
  702. // App switch latency optimization.
  703. bool mAppSwitchSawKeyDown;
  704. nsecs_t mAppSwitchDueTime;
  705. static bool isAppSwitchKeyCode(int32_t keyCode);
  706. bool isAppSwitchKeyEventLocked(KeyEntry* keyEntry);
  707. bool isAppSwitchPendingLocked();
  708. void resetPendingAppSwitchLocked(bool handled);
  709. // Stale event latency optimization.
  710. static bool isStaleEventLocked(nsecs_t currentTime, EventEntry* entry);
  711. // Blocked event latency optimization. Drops old events when the user intends
  712. // to transfer focus to a new application.
  713. EventEntry* mNextUnblockedEvent;
  714. sp<InputWindowHandle> findTouchedWindowAtLocked(int32_t displayId, int32_t x, int32_t y);
  715. // All registered connections mapped by channel file descriptor.
  716. KeyedVector<int, sp<Connection> > mConnectionsByFd;
  717. ssize_t getConnectionIndexLocked(const sp<InputChannel>& inputChannel);
  718. // Input channels that will receive a copy of all input events.
  719. Vector<sp<InputChannel> > mMonitoringChannels;
  720. // Event injection and synchronization.
  721. Condition mInjectionResultAvailableCondition;
  722. bool hasInjectionPermission(int32_t injectorPid, int32_t injectorUid);
  723. void setInjectionResultLocked(EventEntry* entry, int32_t injectionResult);
  724. Condition mInjectionSyncFinishedCondition;
  725. void incrementPendingForegroundDispatchesLocked(EventEntry* entry);
  726. void decrementPendingForegroundDispatchesLocked(EventEntry* entry);
  727. // Key repeat tracking.
  728. struct KeyRepeatState {
  729. KeyEntry* lastKeyEntry; // or null if no repeat
  730. nsecs_t nextRepeatTime;
  731. } mKeyRepeatState;
  732. void resetKeyRepeatLocked();
  733. KeyEntry* synthesizeKeyRepeatLocked(nsecs_t currentTime);
  734. // Deferred command processing.
  735. bool haveCommandsLocked() const;
  736. bool runCommandsLockedInterruptible();
  737. CommandEntry* postCommandLocked(Command command);
  738. // Input filter processing.
  739. bool shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args);
  740. bool shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args);
  741. // Inbound event processing.
  742. void drainInboundQueueLocked();
  743. void releasePendingEventLocked();
  744. void releaseInboundEventLocked(EventEntry* entry);
  745. // Dispatch state.
  746. bool mDispatchEnabled;
  747. bool mDispatchFrozen;
  748. bool mInputFilterEnabled;
  749. Vector<sp<InputWindowHandle> > mWindowHandles;
  750. sp<InputWindowHandle> getWindowHandleLocked(const sp<InputChannel>& inputChannel) const;
  751. bool hasWindowHandleLocked(const sp<InputWindowHandle>& windowHandle) const;
  752. // Focus tracking for keys, trackball, etc.
  753. sp<InputWindowHandle> mFocusedWindowHandle;
  754. // Focus tracking for touch.
  755. struct TouchedWindow {
  756. sp<InputWindowHandle> windowHandle;
  757. int32_t targetFlags;
  758. BitSet32 pointerIds; // zero unless target flag FLAG_SPLIT is set
  759. };
  760. struct TouchState {
  761. bool down;
  762. bool split;
  763. int32_t deviceId; // id of the device that is currently down, others are rejected
  764. uint32_t source; // source of the device that is current down, others are rejected
  765. int32_t displayId; // id to the display that currently has a touch, others are rejected
  766. Vector<TouchedWindow> windows;
  767. TouchState();
  768. ~TouchState();
  769. void reset();
  770. void copyFrom(const TouchState& other);
  771. void addOrUpdateWindow(const sp<InputWindowHandle>& windowHandle,
  772. int32_t targetFlags, BitSet32 pointerIds);
  773. void removeWindow(const sp<InputWindowHandle>& windowHandle);
  774. void filterNonAsIsTouchWindows();
  775. sp<InputWindowHandle> getFirstForegroundWindowHandle() const;
  776. bool isSlippery() const;
  777. };
  778. TouchState mTouchState;
  779. TouchState mTempTouchState;
  780. // Focused application.
  781. sp<InputApplicationHandle> mFocusedApplicationHandle;
  782. // Dispatcher state at time of last ANR.
  783. String8 mLastANRState;
  784. // Dispatch inbound events.
  785. bool dispatchConfigurationChangedLocked(
  786. nsecs_t currentTime, ConfigurationChangedEntry* entry);
  787. bool dispatchDeviceResetLocked(
  788. nsecs_t currentTime, DeviceResetEntry* entry);
  789. bool dispatchKeyLocked(
  790. nsecs_t currentTime, KeyEntry* entry,
  791. DropReason* dropReason, nsecs_t* nextWakeupTime);
  792. bool dispatchMotionLocked(
  793. nsecs_t currentTime, MotionEntry* entry,
  794. DropReason* dropReason, nsecs_t* nextWakeupTime);
  795. void dispatchEventLocked(nsecs_t currentTime, EventEntry* entry,
  796. const Vector<InputTarget>& inputTargets);
  797. void logOutboundKeyDetailsLocked(const char* prefix, const KeyEntry* entry);
  798. void logOutboundMotionDetailsLocked(const char* prefix, const MotionEntry* entry);
  799. // Keeping track of ANR timeouts.
  800. enum InputTargetWaitCause {
  801. INPUT_TARGET_WAIT_CAUSE_NONE,
  802. INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY,
  803. INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY,
  804. };
  805. InputTargetWaitCause mInputTargetWaitCause;
  806. nsecs_t mInputTargetWaitStartTime;
  807. nsecs_t mInputTargetWaitTimeoutTime;
  808. bool mInputTargetWaitTimeoutExpired;
  809. sp<InputApplicationHandle> mInputTargetWaitApplicationHandle;
  810. // Contains the last window which received a hover event.
  811. sp<InputWindowHandle> mLastHoverWindowHandle;
  812. // Finding targets for input events.
  813. int32_t handleTargetsNotReadyLocked(nsecs_t currentTime, const EventEntry* entry,
  814. const sp<InputApplicationHandle>& applicationHandle,
  815. const sp<InputWindowHandle>& windowHandle,
  816. nsecs_t* nextWakeupTime, const char* reason);
  817. void resumeAfterTargetsNotReadyTimeoutLocked(nsecs_t newTimeout,
  818. const sp<InputChannel>& inputChannel);
  819. nsecs_t getTimeSpentWaitingForApplicationLocked(nsecs_t currentTime);
  820. void resetANRTimeoutsLocked();
  821. int32_t findFocusedWindowTargetsLocked(nsecs_t currentTime, const EventEntry* entry,
  822. Vector<InputTarget>& inputTargets, nsecs_t* nextWakeupTime);
  823. int32_t findTouchedWindowTargetsLocked(nsecs_t currentTime, const MotionEntry* entry,
  824. Vector<InputTarget>& inputTargets, nsecs_t* nextWakeupTime,
  825. bool* outConflictingPointerActions);
  826. void addWindowTargetLocked(const sp<InputWindowHandle>& windowHandle,
  827. int32_t targetFlags, BitSet32 pointerIds, Vector<InputTarget>& inputTargets);
  828. void addMonitoringTargetsLocked(Vector<InputTarget>& inputTargets);
  829. void pokeUserActivityLocked(const EventEntry* eventEntry);
  830. bool checkInjectionPermission(const sp<InputWindowHandle>& windowHandle,
  831. const InjectionState* injectionState);
  832. bool isWindowObscuredAtPointLocked(const sp<InputWindowHandle>& windowHandle,
  833. int32_t x, int32_t y) const;
  834. bool isWindowReadyForMoreInputLocked(nsecs_t currentTime,
  835. const sp<InputWindowHandle>& windowHandle, const EventEntry* eventEntry);
  836. String8 getApplicationWindowLabelLocked(const sp<InputApplicationHandle>& applicationHandle,
  837. const sp<InputWindowHandle>& windowHandle);
  838. // Manage the dispatch cycle for a single connection.
  839. // These methods are deliberately not Interruptible because doing all of the work
  840. // with the mutex held makes it easier to ensure that connection invariants are maintained.
  841. // If needed, the methods post commands to run later once the critical bits are done.
  842. void prepareDispatchCycleLocked(nsecs_t currentTime, const sp<Connection>& connection,
  843. EventEntry* eventEntry, const InputTarget* inputTarget);
  844. void enqueueDispatchEntriesLocked(nsecs_t currentTime, const sp<Connection>& connection,
  845. EventEntry* eventEntry, const InputTarget* inputTarget);
  846. void enqueueDispatchEntryLocked(const sp<Connection>& connection,
  847. EventEntry* eventEntry, const InputTarget* inputTarget, int32_t dispatchMode);
  848. void startDispatchCycleLocked(nsecs_t currentTime, const sp<Connection>& connection);
  849. void finishDispatchCycleLocked(nsecs_t currentTime, const sp<Connection>& connection,
  850. uint32_t seq, bool handled);
  851. void abortBrokenDispatchCycleLocked(nsecs_t currentTime, const sp<Connection>& connection,
  852. bool notify);
  853. void drainDispatchQueueLocked(Queue<DispatchEntry>* queue);
  854. void releaseDispatchEntryLocked(DispatchEntry* dispatchEntry);
  855. static int handleReceiveCallback(int fd, int events, void* data);
  856. void synthesizeCancelationEventsForAllConnectionsLocked(
  857. const CancelationOptions& options);
  858. void synthesizeCancelationEventsForInputChannelLocked(const sp<InputChannel>& channel,
  859. const CancelationOptions& options);
  860. void synthesizeCancelationEventsForConnectionLocked(const sp<Connection>& connection,
  861. const CancelationOptions& options);
  862. // Splitting motion events across windows.
  863. MotionEntry* splitMotionEvent(const MotionEntry* originalMotionEntry, BitSet32 pointerIds);
  864. // Reset and drop everything the dispatcher is doing.
  865. void resetAndDropEverythingLocked(const char* reason);
  866. // Dump state.
  867. void dumpDispatchStateLocked(String8& dump);
  868. void logDispatchStateLocked();
  869. // Registration.
  870. void removeMonitorChannelLocked(const sp<InputChannel>& inputChannel);
  871. status_t unregisterInputChannelLocked(const sp<InputChannel>& inputChannel, bool notify);
  872. // Add or remove a connection to the mActiveConnections vector.
  873. void activateConnectionLocked(Connection* connection);
  874. void deactivateConnectionLocked(Connection* connection);
  875. // Interesting events that we might like to log or tell the framework about.
  876. void onDispatchCycleFinishedLocked(
  877. nsecs_t currentTime, const sp<Connection>& connection, uint32_t seq, bool handled);
  878. void onDispatchCycleBrokenLocked(
  879. nsecs_t currentTime, const sp<Connection>& connection);
  880. void onANRLocked(
  881. nsecs_t currentTime, const sp<InputApplicationHandle>& applicationHandle,
  882. const sp<InputWindowHandle>& windowHandle,
  883. nsecs_t eventTime, nsecs_t waitStartTime, const char* reason);
  884. // Outbound policy interactions.
  885. void doNotifyConfigurationChangedInterruptible(CommandEntry* commandEntry);
  886. void doNotifyInputChannelBrokenLockedInterruptible(CommandEntry* commandEntry);
  887. void doNotifyANRLockedInterruptible(CommandEntry* commandEntry);
  888. void doInterceptKeyBeforeDispatchingLockedInterruptible(CommandEntry* commandEntry);
  889. void doDispatchCycleFinishedLockedInterruptible(CommandEntry* commandEntry);
  890. bool afterKeyEventLockedInterruptible(const sp<Connection>& connection,
  891. DispatchEntry* dispatchEntry, KeyEntry* keyEntry, bool handled);
  892. bool afterMotionEventLockedInterruptible(const sp<Connection>& connection,
  893. DispatchEntry* dispatchEntry, MotionEntry* motionEntry, bool handled);
  894. void doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry);
  895. void initializeKeyEvent(KeyEvent* event, const KeyEntry* entry);
  896. // Statistics gathering.
  897. void updateDispatchStatisticsLocked(nsecs_t currentTime, const EventEntry* entry,
  898. int32_t injectionResult, nsecs_t timeSpentWaitingForApplication);
  899. void traceInboundQueueLengthLocked();
  900. void traceOutboundQueueLengthLocked(const sp<Connection>& connection);
  901. void traceWaitQueueLengthLocked(const sp<Connection>& connection);
  902. };
  903. /* Enqueues and dispatches input events, endlessly. */
  904. class InputDispatcherThread : public Thread {
  905. public:
  906. explicit InputDispatcherThread(const sp<InputDispatcherInterface>& dispatcher);
  907. ~InputDispatcherThread();
  908. private:
  909. virtual bool threadLoop();
  910. sp<InputDispatcherInterface> mDispatcher;
  911. };
  912. } // namespace android
  913. #endif // _UI_INPUT_DISPATCHER_H