blob: 781da356a07fab677d427c23fadf55829c6cb7b6 [file] [log] [blame]
Jeff Brown46b9ac0a2010-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 Brown46b9ac0a2010-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 Brown46b9ac0a2010-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 Brown0b72e822010-06-29 16:52:21 -070056 bool valid; // set to true if axis parameters are known, false otherwise
57
Jeff Brown46b9ac0a2010-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 Brown0b72e822010-06-29 16:52:21 -0700277 int32_t xOrigin;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700278 float xScale;
Jeff Brown0b72e822010-06-29 16:52:21 -0700279
280 int32_t yOrigin;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700281 float yScale;
Jeff Brown0b72e822010-06-29 16:52:21 -0700282
283 int32_t pressureOrigin;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700284 float pressureScale;
Jeff Brown0b72e822010-06-29 16:52:21 -0700285
286 int32_t sizeOrigin;
Jeff Brown46b9ac0a2010-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 Brown9c3cda02010-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 Brown349703e2010-06-22 01:27:15 -0700373 ACTION_BRIGHT_HERE = 0x00000008,
Jeff Brown9c3cda02010-06-15 01:31:58 -0700374 };
375
376 /* Describes a virtual key. */
377 struct VirtualKeyDefinition {
378 int32_t scanCode;
379
380 // configured position data, specified in display coords
381 int32_t centerX;
382 int32_t centerY;
383 int32_t width;
384 int32_t height;
385 };
386
387 /* Gets information about the display with the specified id.
388 * Returns true if the display info is available, false otherwise.
389 */
390 virtual bool getDisplayInfo(int32_t displayId,
391 int32_t* width, int32_t* height, int32_t* orientation) = 0;
392
393 /* Provides feedback for a virtual key.
394 */
395 virtual void virtualKeyFeedback(nsecs_t when, int32_t deviceId,
396 int32_t action, int32_t flags, int32_t keyCode,
397 int32_t scanCode, int32_t metaState, nsecs_t downTime) = 0;
398
399 /* Intercepts a key event.
400 * The policy can use this method as an opportunity to perform power management functions
401 * and early event preprocessing.
402 *
403 * Returns a policy action constant such as ACTION_DISPATCH.
404 */
405 virtual int32_t interceptKey(nsecs_t when, int32_t deviceId,
406 bool down, int32_t keyCode, int32_t scanCode, uint32_t policyFlags) = 0;
407
408 /* Intercepts a trackball event.
409 * The policy can use this method as an opportunity to perform power management functions
410 * and early event preprocessing.
411 *
412 * Returns a policy action constant such as ACTION_DISPATCH.
413 */
414 virtual int32_t interceptTrackball(nsecs_t when, bool buttonChanged, bool buttonDown,
415 bool rolled) = 0;
416
417 /* Intercepts a touch event.
418 * The policy can use this method as an opportunity to perform power management functions
419 * and early event preprocessing.
420 *
421 * Returns a policy action constant such as ACTION_DISPATCH.
422 */
423 virtual int32_t interceptTouch(nsecs_t when) = 0;
424
425 /* Intercepts a switch event.
426 * The policy can use this method as an opportunity to perform power management functions
427 * and early event preprocessing.
428 *
429 * Switches are not dispatched to applications so this method should
430 * usually return ACTION_NONE.
431 */
432 virtual int32_t interceptSwitch(nsecs_t when, int32_t switchCode, int32_t switchValue) = 0;
433
434 /* Determines whether to turn on some hacks we have to improve the touch interaction with a
435 * certain device whose screen currently is not all that good.
436 */
437 virtual bool filterTouchEvents() = 0;
438
439 /* Determines whether to turn on some hacks to improve touch interaction with another device
440 * where touch coordinate data can get corrupted.
441 */
442 virtual bool filterJumpyTouchEvents() = 0;
443
444 /* Gets the configured virtual key definitions for an input device. */
445 virtual void getVirtualKeyDefinitions(const String8& deviceName,
446 Vector<VirtualKeyDefinition>& outVirtualKeyDefinitions) = 0;
447
448 /* Gets the excluded device names for the platform. */
449 virtual void getExcludedDeviceNames(Vector<String8>& outExcludedDeviceNames) = 0;
450};
451
452
453/* Processes raw input events and sends cooked event data to an input dispatcher. */
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700454class InputReaderInterface : public virtual RefBase {
455protected:
456 InputReaderInterface() { }
457 virtual ~InputReaderInterface() { }
458
459public:
460 /* Runs a single iteration of the processing loop.
461 * Nominally reads and processes one incoming message from the EventHub.
462 *
463 * This method should be called on the input reader thread.
464 */
465 virtual void loopOnce() = 0;
466
467 /* Gets the current virtual key. Returns false if not down.
468 *
469 * This method may be called on any thread (usually by the input manager).
470 */
471 virtual bool getCurrentVirtualKey(int32_t* outKeyCode, int32_t* outScanCode) const = 0;
Jeff Brown9c3cda02010-06-15 01:31:58 -0700472
473 /* Gets the current input device configuration.
474 *
475 * This method may be called on any thread (usually by the input manager).
476 */
477 virtual void getCurrentInputConfiguration(InputConfiguration* outConfiguration) const = 0;
478
479 /*
480 * Query current input state.
481 * deviceId may be -1 to search for the device automatically, filtered by class.
482 * deviceClasses may be -1 to ignore device class while searching.
483 */
484 virtual int32_t getCurrentScanCodeState(int32_t deviceId, int32_t deviceClasses,
485 int32_t scanCode) const = 0;
486 virtual int32_t getCurrentKeyCodeState(int32_t deviceId, int32_t deviceClasses,
487 int32_t keyCode) const = 0;
488 virtual int32_t getCurrentSwitchState(int32_t deviceId, int32_t deviceClasses,
489 int32_t sw) const = 0;
490
491 /* Determine whether physical keys exist for the given framework-domain key codes. */
492 virtual bool hasKeys(size_t numCodes, const int32_t* keyCodes, uint8_t* outFlags) const = 0;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700493};
494
Jeff Brown9c3cda02010-06-15 01:31:58 -0700495
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700496/* The input reader reads raw event data from the event hub and processes it into input events
Jeff Brown9c3cda02010-06-15 01:31:58 -0700497 * that it sends to the input dispatcher. Some functions of the input reader, such as early
498 * event filtering in low power states, are controlled by a separate policy object.
499 *
500 * IMPORTANT INVARIANT:
501 * Because the policy can potentially block or cause re-entrance into the input reader,
502 * the input reader never calls into the policy while holding its internal locks.
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700503 */
504class InputReader : public InputReaderInterface {
505public:
506 InputReader(const sp<EventHubInterface>& eventHub,
Jeff Brown9c3cda02010-06-15 01:31:58 -0700507 const sp<InputReaderPolicyInterface>& policy,
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700508 const sp<InputDispatcherInterface>& dispatcher);
509 virtual ~InputReader();
510
511 virtual void loopOnce();
512
513 virtual bool getCurrentVirtualKey(int32_t* outKeyCode, int32_t* outScanCode) const;
514
Jeff Brown9c3cda02010-06-15 01:31:58 -0700515 virtual void getCurrentInputConfiguration(InputConfiguration* outConfiguration) const;
516
517 virtual int32_t getCurrentScanCodeState(int32_t deviceId, int32_t deviceClasses,
518 int32_t scanCode) const;
519 virtual int32_t getCurrentKeyCodeState(int32_t deviceId, int32_t deviceClasses,
520 int32_t keyCode) const;
521 virtual int32_t getCurrentSwitchState(int32_t deviceId, int32_t deviceClasses,
522 int32_t sw) const;
523
524 virtual bool hasKeys(size_t numCodes, const int32_t* keyCodes, uint8_t* outFlags) const;
525
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700526private:
527 // Lock that must be acquired while manipulating state that may be concurrently accessed
528 // from other threads by input state query methods. It should be held for as short a
529 // time as possible.
530 //
531 // Exported state:
532 // - global virtual key code and scan code
533 // - device list and immutable properties of devices such as id, name, and class
534 // (but not other internal device state)
535 mutable Mutex mExportedStateLock;
536
Jeff Brown9c3cda02010-06-15 01:31:58 -0700537 // current virtual key information (lock mExportedStateLock)
538 int32_t mExportedVirtualKeyCode;
539 int32_t mExportedVirtualScanCode;
540
541 // current input configuration (lock mExportedStateLock)
542 InputConfiguration mExportedInputConfiguration;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700543
544 // combined key meta state
545 int32_t mGlobalMetaState;
546
547 sp<EventHubInterface> mEventHub;
Jeff Brown9c3cda02010-06-15 01:31:58 -0700548 sp<InputReaderPolicyInterface> mPolicy;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700549 sp<InputDispatcherInterface> mDispatcher;
550
551 KeyedVector<int32_t, InputDevice*> mDevices;
552
553 // display properties needed to translate touch screen coordinates into display coordinates
554 int32_t mDisplayOrientation;
555 int32_t mDisplayWidth;
556 int32_t mDisplayHeight;
557
558 // low-level input event decoding
559 void process(const RawEvent* rawEvent);
560 void handleDeviceAdded(const RawEvent* rawEvent);
561 void handleDeviceRemoved(const RawEvent* rawEvent);
562 void handleSync(const RawEvent* rawEvent);
563 void handleKey(const RawEvent* rawEvent);
564 void handleRelativeMotion(const RawEvent* rawEvent);
565 void handleAbsoluteMotion(const RawEvent* rawEvent);
566 void handleSwitch(const RawEvent* rawEvent);
567
568 // input policy processing and dispatch
569 void onKey(nsecs_t when, InputDevice* device, bool down,
570 int32_t keyCode, int32_t scanCode, uint32_t policyFlags);
Jeff Brown9c3cda02010-06-15 01:31:58 -0700571 void onSwitch(nsecs_t when, InputDevice* device, int32_t switchCode, int32_t switchValue);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700572 void onSingleTouchScreenStateChanged(nsecs_t when, InputDevice* device);
573 void onMultiTouchScreenStateChanged(nsecs_t when, InputDevice* device);
574 void onTouchScreenChanged(nsecs_t when, InputDevice* device, bool havePointerIds);
575 void onTrackballStateChanged(nsecs_t when, InputDevice* device);
576 void onConfigurationChanged(nsecs_t when);
577
578 bool applyStandardInputDispatchPolicyActions(nsecs_t when,
579 int32_t policyActions, uint32_t* policyFlags);
580
581 bool consumeVirtualKeyTouches(nsecs_t when, InputDevice* device, uint32_t policyFlags);
582 void dispatchVirtualKey(nsecs_t when, InputDevice* device, uint32_t policyFlags,
583 int32_t keyEventAction, int32_t keyEventFlags);
584 void dispatchTouches(nsecs_t when, InputDevice* device, uint32_t policyFlags);
585 void dispatchTouch(nsecs_t when, InputDevice* device, uint32_t policyFlags,
586 InputDevice::TouchData* touch, BitSet32 idBits, int32_t motionEventAction);
587
588 // display
589 void resetDisplayProperties();
590 bool refreshDisplayProperties();
591
592 // device management
593 InputDevice* getDevice(int32_t deviceId);
594 InputDevice* getNonIgnoredDevice(int32_t deviceId);
595 void addDevice(nsecs_t when, int32_t deviceId);
596 void removeDevice(nsecs_t when, InputDevice* device);
597 void configureDevice(InputDevice* device);
598 void configureDeviceForCurrentDisplaySize(InputDevice* device);
599 void configureVirtualKeys(InputDevice* device);
600 void configureAbsoluteAxisInfo(InputDevice* device, int axis, const char* name,
601 InputDevice::AbsoluteAxisInfo* out);
Jeff Brown9c3cda02010-06-15 01:31:58 -0700602 void configureExcludedDevices();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700603
604 // global meta state management for all devices
605 void resetGlobalMetaState();
606 int32_t globalMetaState();
607
608 // virtual key management
Jeff Brown9c3cda02010-06-15 01:31:58 -0700609 void updateExportedVirtualKeyState();
610
611 // input configuration management
612 void updateExportedInputConfiguration();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700613};
614
615
616/* Reads raw events from the event hub and processes them, endlessly. */
617class InputReaderThread : public Thread {
618public:
619 InputReaderThread(const sp<InputReaderInterface>& reader);
620 virtual ~InputReaderThread();
621
622private:
623 sp<InputReaderInterface> mReader;
624
625 virtual bool threadLoop();
626};
627
628} // namespace android
629
630#endif // _UI_INPUT_READER_H