blob: 8f6777d10666bc4e88a02903a917cd9952d51da2 [file] [log] [blame]
Jeff Browne839a582010-04-22 18:58:52 -07001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#ifndef _UI_INPUT_READER_H
18#define _UI_INPUT_READER_H
19
20#include <ui/EventHub.h>
21#include <ui/Input.h>
Jeff Browne839a582010-04-22 18:58:52 -070022#include <ui/InputDispatcher.h>
23#include <utils/KeyedVector.h>
24#include <utils/threads.h>
25#include <utils/Timers.h>
26#include <utils/RefBase.h>
27#include <utils/String8.h>
28#include <utils/BitSet.h>
29
30#include <stddef.h>
31#include <unistd.h>
32
33/* Maximum pointer id value supported.
34 * (This is limited by our use of BitSet32 to track pointer assignments.) */
35#define MAX_POINTER_ID 32
36
Jeff Browne839a582010-04-22 18:58:52 -070037/* Maximum number of historical samples to average. */
38#define AVERAGING_HISTORY_SIZE 5
39
40
41namespace android {
42
43extern int32_t updateMetaState(int32_t keyCode, bool down, int32_t oldMetaState);
44extern int32_t rotateKeyCode(int32_t keyCode, int32_t orientation);
45
46/*
47 * An input device structure tracks the state of a single input device.
48 *
49 * This structure is only used by ReaderThread and is not intended to be shared with
50 * DispatcherThread (because that would require locking). This works out fine because
51 * DispatcherThread is only interested in cooked event data anyways and does not need
52 * any of the low-level data from InputDevice.
53 */
54struct InputDevice {
55 struct AbsoluteAxisInfo {
Jeff Brown4036f7f2010-06-29 16:52:21 -070056 bool valid; // set to true if axis parameters are known, false otherwise
57
Jeff Browne839a582010-04-22 18:58:52 -070058 int32_t minValue; // minimum value
59 int32_t maxValue; // maximum value
60 int32_t range; // range of values, equal to maxValue - minValue
61 int32_t flat; // center flat position, eg. flat == 8 means center is between -8 and 8
62 int32_t fuzz; // error tolerance, eg. fuzz == 4 means value is +/- 4 due to noise
63 };
64
65 struct VirtualKey {
66 int32_t keyCode;
67 int32_t scanCode;
68 uint32_t flags;
69
70 // computed hit box, specified in touch screen coords based on known display size
71 int32_t hitLeft;
72 int32_t hitTop;
73 int32_t hitRight;
74 int32_t hitBottom;
75
76 inline bool isHit(int32_t x, int32_t y) const {
77 return x >= hitLeft && x <= hitRight && y >= hitTop && y <= hitBottom;
78 }
79 };
80
81 struct KeyboardState {
82 struct Current {
83 int32_t metaState;
84 nsecs_t downTime; // time of most recent key down
85 } current;
86
87 void reset();
88 };
89
90 struct TrackballState {
91 struct Accumulator {
92 enum {
93 FIELD_BTN_MOUSE = 1,
94 FIELD_REL_X = 2,
95 FIELD_REL_Y = 4
96 };
97
98 uint32_t fields;
99
100 bool btnMouse;
101 int32_t relX;
102 int32_t relY;
103
104 inline void clear() {
105 fields = 0;
106 }
107
108 inline bool isDirty() {
109 return fields != 0;
110 }
111 } accumulator;
112
113 struct Current {
114 bool down;
115 nsecs_t downTime;
116 } current;
117
118 struct Precalculated {
119 float xScale;
120 float yScale;
121 float xPrecision;
122 float yPrecision;
123 } precalculated;
124
125 void reset();
126 };
127
128 struct SingleTouchScreenState {
129 struct Accumulator {
130 enum {
131 FIELD_BTN_TOUCH = 1,
132 FIELD_ABS_X = 2,
133 FIELD_ABS_Y = 4,
134 FIELD_ABS_PRESSURE = 8,
135 FIELD_ABS_TOOL_WIDTH = 16
136 };
137
138 uint32_t fields;
139
140 bool btnTouch;
141 int32_t absX;
142 int32_t absY;
143 int32_t absPressure;
144 int32_t absToolWidth;
145
146 inline void clear() {
147 fields = 0;
148 }
149
150 inline bool isDirty() {
151 return fields != 0;
152 }
153 } accumulator;
154
155 struct Current {
156 bool down;
157 int32_t x;
158 int32_t y;
159 int32_t pressure;
160 int32_t size;
161 } current;
162
163 void reset();
164 };
165
166 struct MultiTouchScreenState {
167 struct Accumulator {
168 enum {
169 FIELD_ABS_MT_POSITION_X = 1,
170 FIELD_ABS_MT_POSITION_Y = 2,
171 FIELD_ABS_MT_TOUCH_MAJOR = 4,
172 FIELD_ABS_MT_WIDTH_MAJOR = 8,
173 FIELD_ABS_MT_TRACKING_ID = 16
174 };
175
176 uint32_t pointerCount;
177 struct Pointer {
178 uint32_t fields;
179
180 int32_t absMTPositionX;
181 int32_t absMTPositionY;
182 int32_t absMTTouchMajor;
183 int32_t absMTWidthMajor;
184 int32_t absMTTrackingId;
185
186 inline void clear() {
187 fields = 0;
188 }
189 } pointers[MAX_POINTERS + 1]; // + 1 to remove the need for extra range checks
190
191 inline void clear() {
192 pointerCount = 0;
193 pointers[0].clear();
194 }
195
196 inline bool isDirty() {
197 return pointerCount != 0;
198 }
199 } accumulator;
200
201 void reset();
202 };
203
204 struct PointerData {
205 uint32_t id;
206 int32_t x;
207 int32_t y;
208 int32_t pressure;
209 int32_t size;
210 };
211
212 struct TouchData {
213 uint32_t pointerCount;
214 PointerData pointers[MAX_POINTERS];
215 BitSet32 idBits;
216 uint32_t idToIndex[MAX_POINTER_ID];
217
218 void copyFrom(const TouchData& other);
219
220 inline void clear() {
221 pointerCount = 0;
222 idBits.clear();
223 }
224 };
225
226 // common state used for both single-touch and multi-touch screens after the initial
227 // touch decoding has been performed
228 struct TouchScreenState {
229 Vector<VirtualKey> virtualKeys;
230
231 struct Parameters {
232 bool useBadTouchFilter;
233 bool useJumpyTouchFilter;
234 bool useAveragingTouchFilter;
235
236 AbsoluteAxisInfo xAxis;
237 AbsoluteAxisInfo yAxis;
238 AbsoluteAxisInfo pressureAxis;
239 AbsoluteAxisInfo sizeAxis;
240 } parameters;
241
242 // The touch data of the current sample being processed.
243 TouchData currentTouch;
244
245 // The touch data of the previous sample that was processed. This is updated
246 // incrementally while the current sample is being processed.
247 TouchData lastTouch;
248
249 // The time the primary pointer last went down.
250 nsecs_t downTime;
251
252 struct CurrentVirtualKeyState {
253 bool down;
254 nsecs_t downTime;
255 int32_t keyCode;
256 int32_t scanCode;
257 } currentVirtualKey;
258
259 struct AveragingTouchFilterState {
260 // Individual history tracks are stored by pointer id
261 uint32_t historyStart[MAX_POINTERS];
262 uint32_t historyEnd[MAX_POINTERS];
263 struct {
264 struct {
265 int32_t x;
266 int32_t y;
267 int32_t pressure;
268 } pointers[MAX_POINTERS];
269 } historyData[AVERAGING_HISTORY_SIZE];
270 } averagingTouchFilter;
271
272 struct JumpTouchFilterState {
273 int32_t jumpyPointsDropped;
274 } jumpyTouchFilter;
275
276 struct Precalculated {
Jeff Brown4036f7f2010-06-29 16:52:21 -0700277 int32_t xOrigin;
Jeff Browne839a582010-04-22 18:58:52 -0700278 float xScale;
Jeff Brown4036f7f2010-06-29 16:52:21 -0700279
280 int32_t yOrigin;
Jeff Browne839a582010-04-22 18:58:52 -0700281 float yScale;
Jeff Brown4036f7f2010-06-29 16:52:21 -0700282
283 int32_t pressureOrigin;
Jeff Browne839a582010-04-22 18:58:52 -0700284 float pressureScale;
Jeff Brown4036f7f2010-06-29 16:52:21 -0700285
286 int32_t sizeOrigin;
Jeff Browne839a582010-04-22 18:58:52 -0700287 float sizeScale;
288 } precalculated;
289
290 void reset();
291
292 bool applyBadTouchFilter();
293 bool applyJumpyTouchFilter();
294 void applyAveragingTouchFilter();
295 void calculatePointerIds();
296
297 bool isPointInsideDisplay(int32_t x, int32_t y) const;
298 };
299
300 InputDevice(int32_t id, uint32_t classes, String8 name);
301
302 int32_t id;
303 uint32_t classes;
304 String8 name;
305 bool ignored;
306
307 KeyboardState keyboard;
308 TrackballState trackball;
309 TouchScreenState touchScreen;
310 union {
311 SingleTouchScreenState singleTouchScreen;
312 MultiTouchScreenState multiTouchScreen;
313 };
314
315 void reset();
316
317 inline bool isKeyboard() const { return classes & INPUT_DEVICE_CLASS_KEYBOARD; }
318 inline bool isAlphaKey() const { return classes & INPUT_DEVICE_CLASS_ALPHAKEY; }
319 inline bool isTrackball() const { return classes & INPUT_DEVICE_CLASS_TRACKBALL; }
320 inline bool isDPad() const { return classes & INPUT_DEVICE_CLASS_DPAD; }
321 inline bool isSingleTouchScreen() const { return (classes
322 & (INPUT_DEVICE_CLASS_TOUCHSCREEN | INPUT_DEVICE_CLASS_TOUCHSCREEN_MT))
323 == INPUT_DEVICE_CLASS_TOUCHSCREEN; }
324 inline bool isMultiTouchScreen() const { return classes
325 & INPUT_DEVICE_CLASS_TOUCHSCREEN_MT; }
326 inline bool isTouchScreen() const { return classes
327 & (INPUT_DEVICE_CLASS_TOUCHSCREEN | INPUT_DEVICE_CLASS_TOUCHSCREEN_MT); }
328};
329
330
Jeff Brown54bc2812010-06-15 01:31:58 -0700331/*
332 * Input reader policy interface.
333 *
334 * The input reader policy is used by the input reader to interact with the Window Manager
335 * and other system components.
336 *
337 * The actual implementation is partially supported by callbacks into the DVM
338 * via JNI. This interface is also mocked in the unit tests.
339 */
340class InputReaderPolicyInterface : public virtual RefBase {
341protected:
342 InputReaderPolicyInterface() { }
343 virtual ~InputReaderPolicyInterface() { }
344
345public:
346 /* Display orientations. */
347 enum {
348 ROTATION_0 = 0,
349 ROTATION_90 = 1,
350 ROTATION_180 = 2,
351 ROTATION_270 = 3
352 };
353
354 /* Actions returned by interceptXXX methods. */
355 enum {
356 // The input dispatcher should do nothing and discard the input unless other
357 // flags are set.
358 ACTION_NONE = 0,
359
360 // The input dispatcher should dispatch the input to the application.
361 ACTION_DISPATCH = 0x00000001,
362
363 // The input dispatcher should perform special filtering in preparation for
364 // a pending app switch.
365 ACTION_APP_SWITCH_COMING = 0x00000002,
366
367 // The input dispatcher should add POLICY_FLAG_WOKE_HERE to the policy flags it
368 // passes through the dispatch pipeline.
369 ACTION_WOKE_HERE = 0x00000004,
370
371 // The input dispatcher should add POLICY_FLAG_BRIGHT_HERE to the policy flags it
372 // passes through the dispatch pipeline.
Jeff Brown50de30a2010-06-22 01:27:15 -0700373 ACTION_BRIGHT_HERE = 0x00000008,
374
375 // The input dispatcher should add POLICY_FLAG_INTERCEPT_DISPATCH to the policy flags
376 // it passed through the dispatch pipeline.
377 ACTION_INTERCEPT_DISPATCH = 0x00000010
Jeff Brown54bc2812010-06-15 01:31:58 -0700378 };
379
380 /* Describes a virtual key. */
381 struct VirtualKeyDefinition {
382 int32_t scanCode;
383
384 // configured position data, specified in display coords
385 int32_t centerX;
386 int32_t centerY;
387 int32_t width;
388 int32_t height;
389 };
390
391 /* Gets information about the display with the specified id.
392 * Returns true if the display info is available, false otherwise.
393 */
394 virtual bool getDisplayInfo(int32_t displayId,
395 int32_t* width, int32_t* height, int32_t* orientation) = 0;
396
397 /* Provides feedback for a virtual key.
398 */
399 virtual void virtualKeyFeedback(nsecs_t when, int32_t deviceId,
400 int32_t action, int32_t flags, int32_t keyCode,
401 int32_t scanCode, int32_t metaState, nsecs_t downTime) = 0;
402
403 /* Intercepts a key event.
404 * The policy can use this method as an opportunity to perform power management functions
405 * and early event preprocessing.
406 *
407 * Returns a policy action constant such as ACTION_DISPATCH.
408 */
409 virtual int32_t interceptKey(nsecs_t when, int32_t deviceId,
410 bool down, int32_t keyCode, int32_t scanCode, uint32_t policyFlags) = 0;
411
412 /* Intercepts a trackball event.
413 * The policy can use this method as an opportunity to perform power management functions
414 * and early event preprocessing.
415 *
416 * Returns a policy action constant such as ACTION_DISPATCH.
417 */
418 virtual int32_t interceptTrackball(nsecs_t when, bool buttonChanged, bool buttonDown,
419 bool rolled) = 0;
420
421 /* Intercepts a touch event.
422 * The policy can use this method as an opportunity to perform power management functions
423 * and early event preprocessing.
424 *
425 * Returns a policy action constant such as ACTION_DISPATCH.
426 */
427 virtual int32_t interceptTouch(nsecs_t when) = 0;
428
429 /* Intercepts a switch event.
430 * The policy can use this method as an opportunity to perform power management functions
431 * and early event preprocessing.
432 *
433 * Switches are not dispatched to applications so this method should
434 * usually return ACTION_NONE.
435 */
436 virtual int32_t interceptSwitch(nsecs_t when, int32_t switchCode, int32_t switchValue) = 0;
437
438 /* Determines whether to turn on some hacks we have to improve the touch interaction with a
439 * certain device whose screen currently is not all that good.
440 */
441 virtual bool filterTouchEvents() = 0;
442
443 /* Determines whether to turn on some hacks to improve touch interaction with another device
444 * where touch coordinate data can get corrupted.
445 */
446 virtual bool filterJumpyTouchEvents() = 0;
447
448 /* Gets the configured virtual key definitions for an input device. */
449 virtual void getVirtualKeyDefinitions(const String8& deviceName,
450 Vector<VirtualKeyDefinition>& outVirtualKeyDefinitions) = 0;
451
452 /* Gets the excluded device names for the platform. */
453 virtual void getExcludedDeviceNames(Vector<String8>& outExcludedDeviceNames) = 0;
454};
455
456
457/* Processes raw input events and sends cooked event data to an input dispatcher. */
Jeff Browne839a582010-04-22 18:58:52 -0700458class InputReaderInterface : public virtual RefBase {
459protected:
460 InputReaderInterface() { }
461 virtual ~InputReaderInterface() { }
462
463public:
464 /* Runs a single iteration of the processing loop.
465 * Nominally reads and processes one incoming message from the EventHub.
466 *
467 * This method should be called on the input reader thread.
468 */
469 virtual void loopOnce() = 0;
470
471 /* Gets the current virtual key. Returns false if not down.
472 *
473 * This method may be called on any thread (usually by the input manager).
474 */
475 virtual bool getCurrentVirtualKey(int32_t* outKeyCode, int32_t* outScanCode) const = 0;
Jeff Brown54bc2812010-06-15 01:31:58 -0700476
477 /* Gets the current input device configuration.
478 *
479 * This method may be called on any thread (usually by the input manager).
480 */
481 virtual void getCurrentInputConfiguration(InputConfiguration* outConfiguration) const = 0;
482
483 /*
484 * Query current input state.
485 * deviceId may be -1 to search for the device automatically, filtered by class.
486 * deviceClasses may be -1 to ignore device class while searching.
487 */
488 virtual int32_t getCurrentScanCodeState(int32_t deviceId, int32_t deviceClasses,
489 int32_t scanCode) const = 0;
490 virtual int32_t getCurrentKeyCodeState(int32_t deviceId, int32_t deviceClasses,
491 int32_t keyCode) const = 0;
492 virtual int32_t getCurrentSwitchState(int32_t deviceId, int32_t deviceClasses,
493 int32_t sw) const = 0;
494
495 /* Determine whether physical keys exist for the given framework-domain key codes. */
496 virtual bool hasKeys(size_t numCodes, const int32_t* keyCodes, uint8_t* outFlags) const = 0;
Jeff Browne839a582010-04-22 18:58:52 -0700497};
498
Jeff Brown54bc2812010-06-15 01:31:58 -0700499
Jeff Browne839a582010-04-22 18:58:52 -0700500/* The input reader reads raw event data from the event hub and processes it into input events
Jeff Brown54bc2812010-06-15 01:31:58 -0700501 * that it sends to the input dispatcher. Some functions of the input reader, such as early
502 * event filtering in low power states, are controlled by a separate policy object.
503 *
504 * IMPORTANT INVARIANT:
505 * Because the policy can potentially block or cause re-entrance into the input reader,
506 * the input reader never calls into the policy while holding its internal locks.
Jeff Browne839a582010-04-22 18:58:52 -0700507 */
508class InputReader : public InputReaderInterface {
509public:
510 InputReader(const sp<EventHubInterface>& eventHub,
Jeff Brown54bc2812010-06-15 01:31:58 -0700511 const sp<InputReaderPolicyInterface>& policy,
Jeff Browne839a582010-04-22 18:58:52 -0700512 const sp<InputDispatcherInterface>& dispatcher);
513 virtual ~InputReader();
514
515 virtual void loopOnce();
516
517 virtual bool getCurrentVirtualKey(int32_t* outKeyCode, int32_t* outScanCode) const;
518
Jeff Brown54bc2812010-06-15 01:31:58 -0700519 virtual void getCurrentInputConfiguration(InputConfiguration* outConfiguration) const;
520
521 virtual int32_t getCurrentScanCodeState(int32_t deviceId, int32_t deviceClasses,
522 int32_t scanCode) const;
523 virtual int32_t getCurrentKeyCodeState(int32_t deviceId, int32_t deviceClasses,
524 int32_t keyCode) const;
525 virtual int32_t getCurrentSwitchState(int32_t deviceId, int32_t deviceClasses,
526 int32_t sw) const;
527
528 virtual bool hasKeys(size_t numCodes, const int32_t* keyCodes, uint8_t* outFlags) const;
529
Jeff Browne839a582010-04-22 18:58:52 -0700530private:
531 // Lock that must be acquired while manipulating state that may be concurrently accessed
532 // from other threads by input state query methods. It should be held for as short a
533 // time as possible.
534 //
535 // Exported state:
536 // - global virtual key code and scan code
537 // - device list and immutable properties of devices such as id, name, and class
538 // (but not other internal device state)
539 mutable Mutex mExportedStateLock;
540
Jeff Brown54bc2812010-06-15 01:31:58 -0700541 // current virtual key information (lock mExportedStateLock)
542 int32_t mExportedVirtualKeyCode;
543 int32_t mExportedVirtualScanCode;
544
545 // current input configuration (lock mExportedStateLock)
546 InputConfiguration mExportedInputConfiguration;
Jeff Browne839a582010-04-22 18:58:52 -0700547
548 // combined key meta state
549 int32_t mGlobalMetaState;
550
551 sp<EventHubInterface> mEventHub;
Jeff Brown54bc2812010-06-15 01:31:58 -0700552 sp<InputReaderPolicyInterface> mPolicy;
Jeff Browne839a582010-04-22 18:58:52 -0700553 sp<InputDispatcherInterface> mDispatcher;
554
555 KeyedVector<int32_t, InputDevice*> mDevices;
556
557 // display properties needed to translate touch screen coordinates into display coordinates
558 int32_t mDisplayOrientation;
559 int32_t mDisplayWidth;
560 int32_t mDisplayHeight;
561
562 // low-level input event decoding
563 void process(const RawEvent* rawEvent);
564 void handleDeviceAdded(const RawEvent* rawEvent);
565 void handleDeviceRemoved(const RawEvent* rawEvent);
566 void handleSync(const RawEvent* rawEvent);
567 void handleKey(const RawEvent* rawEvent);
568 void handleRelativeMotion(const RawEvent* rawEvent);
569 void handleAbsoluteMotion(const RawEvent* rawEvent);
570 void handleSwitch(const RawEvent* rawEvent);
571
572 // input policy processing and dispatch
573 void onKey(nsecs_t when, InputDevice* device, bool down,
574 int32_t keyCode, int32_t scanCode, uint32_t policyFlags);
Jeff Brown54bc2812010-06-15 01:31:58 -0700575 void onSwitch(nsecs_t when, InputDevice* device, int32_t switchCode, int32_t switchValue);
Jeff Browne839a582010-04-22 18:58:52 -0700576 void onSingleTouchScreenStateChanged(nsecs_t when, InputDevice* device);
577 void onMultiTouchScreenStateChanged(nsecs_t when, InputDevice* device);
578 void onTouchScreenChanged(nsecs_t when, InputDevice* device, bool havePointerIds);
579 void onTrackballStateChanged(nsecs_t when, InputDevice* device);
580 void onConfigurationChanged(nsecs_t when);
581
582 bool applyStandardInputDispatchPolicyActions(nsecs_t when,
583 int32_t policyActions, uint32_t* policyFlags);
584
585 bool consumeVirtualKeyTouches(nsecs_t when, InputDevice* device, uint32_t policyFlags);
586 void dispatchVirtualKey(nsecs_t when, InputDevice* device, uint32_t policyFlags,
587 int32_t keyEventAction, int32_t keyEventFlags);
588 void dispatchTouches(nsecs_t when, InputDevice* device, uint32_t policyFlags);
589 void dispatchTouch(nsecs_t when, InputDevice* device, uint32_t policyFlags,
590 InputDevice::TouchData* touch, BitSet32 idBits, int32_t motionEventAction);
591
592 // display
593 void resetDisplayProperties();
594 bool refreshDisplayProperties();
595
596 // device management
597 InputDevice* getDevice(int32_t deviceId);
598 InputDevice* getNonIgnoredDevice(int32_t deviceId);
599 void addDevice(nsecs_t when, int32_t deviceId);
600 void removeDevice(nsecs_t when, InputDevice* device);
601 void configureDevice(InputDevice* device);
602 void configureDeviceForCurrentDisplaySize(InputDevice* device);
603 void configureVirtualKeys(InputDevice* device);
604 void configureAbsoluteAxisInfo(InputDevice* device, int axis, const char* name,
605 InputDevice::AbsoluteAxisInfo* out);
Jeff Brown54bc2812010-06-15 01:31:58 -0700606 void configureExcludedDevices();
Jeff Browne839a582010-04-22 18:58:52 -0700607
608 // global meta state management for all devices
609 void resetGlobalMetaState();
610 int32_t globalMetaState();
611
612 // virtual key management
Jeff Brown54bc2812010-06-15 01:31:58 -0700613 void updateExportedVirtualKeyState();
614
615 // input configuration management
616 void updateExportedInputConfiguration();
Jeff Browne839a582010-04-22 18:58:52 -0700617};
618
619
620/* Reads raw events from the event hub and processes them, endlessly. */
621class InputReaderThread : public Thread {
622public:
623 InputReaderThread(const sp<InputReaderInterface>& reader);
624 virtual ~InputReaderThread();
625
626private:
627 sp<InputReaderInterface> mReader;
628
629 virtual bool threadLoop();
630};
631
632} // namespace android
633
634#endif // _UI_INPUT_READER_H