OSDN Git Service

Support old single-touch touchscreens with BTN_LEFT
[android-x86/frameworks-native.git] / services / inputflinger / InputReader.cpp
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 #define LOG_TAG "InputReader"
18
19 //#define LOG_NDEBUG 0
20
21 // Log debug messages for each raw event received from the EventHub.
22 #define DEBUG_RAW_EVENTS 0
23
24 // Log debug messages about touch screen filtering hacks.
25 #define DEBUG_HACKS 0
26
27 // Log debug messages about virtual key processing.
28 #define DEBUG_VIRTUAL_KEYS 0
29
30 // Log debug messages about pointers.
31 #define DEBUG_POINTERS 0
32
33 // Log debug messages about pointer assignment calculations.
34 #define DEBUG_POINTER_ASSIGNMENT 0
35
36 // Log debug messages about gesture detection.
37 #define DEBUG_GESTURES 0
38
39 // Log debug messages about the vibrator.
40 #define DEBUG_VIBRATOR 0
41
42 #include "InputReader.h"
43
44 #include <cutils/log.h>
45 #include <input/Keyboard.h>
46 #include <input/VirtualKeyMap.h>
47
48 #include <stddef.h>
49 #include <stdlib.h>
50 #include <unistd.h>
51 #include <errno.h>
52 #include <limits.h>
53 #include <math.h>
54
55 #define INDENT "  "
56 #define INDENT2 "    "
57 #define INDENT3 "      "
58 #define INDENT4 "        "
59 #define INDENT5 "          "
60
61 namespace android {
62
63 // --- Constants ---
64
65 // Maximum number of slots supported when using the slot-based Multitouch Protocol B.
66 static const size_t MAX_SLOTS = 32;
67
68 // --- Static Functions ---
69
70 template<typename T>
71 inline static T abs(const T& value) {
72     return value < 0 ? - value : value;
73 }
74
75 template<typename T>
76 inline static T min(const T& a, const T& b) {
77     return a < b ? a : b;
78 }
79
80 template<typename T>
81 inline static void swap(T& a, T& b) {
82     T temp = a;
83     a = b;
84     b = temp;
85 }
86
87 inline static float avg(float x, float y) {
88     return (x + y) / 2;
89 }
90
91 inline static float distance(float x1, float y1, float x2, float y2) {
92     return hypotf(x1 - x2, y1 - y2);
93 }
94
95 inline static int32_t signExtendNybble(int32_t value) {
96     return value >= 8 ? value - 16 : value;
97 }
98
99 static inline const char* toString(bool value) {
100     return value ? "true" : "false";
101 }
102
103 static int32_t rotateValueUsingRotationMap(int32_t value, int32_t orientation,
104         const int32_t map[][4], size_t mapSize) {
105     if (orientation != DISPLAY_ORIENTATION_0) {
106         for (size_t i = 0; i < mapSize; i++) {
107             if (value == map[i][0]) {
108                 return map[i][orientation];
109             }
110         }
111     }
112     return value;
113 }
114
115 static const int32_t keyCodeRotationMap[][4] = {
116         // key codes enumerated counter-clockwise with the original (unrotated) key first
117         // no rotation,        90 degree rotation,  180 degree rotation, 270 degree rotation
118         { AKEYCODE_DPAD_DOWN,   AKEYCODE_DPAD_RIGHT,  AKEYCODE_DPAD_UP,     AKEYCODE_DPAD_LEFT },
119         { AKEYCODE_DPAD_RIGHT,  AKEYCODE_DPAD_UP,     AKEYCODE_DPAD_LEFT,   AKEYCODE_DPAD_DOWN },
120         { AKEYCODE_DPAD_UP,     AKEYCODE_DPAD_LEFT,   AKEYCODE_DPAD_DOWN,   AKEYCODE_DPAD_RIGHT },
121         { AKEYCODE_DPAD_LEFT,   AKEYCODE_DPAD_DOWN,   AKEYCODE_DPAD_RIGHT,  AKEYCODE_DPAD_UP },
122 };
123 static const size_t keyCodeRotationMapSize =
124         sizeof(keyCodeRotationMap) / sizeof(keyCodeRotationMap[0]);
125
126 static int32_t rotateKeyCode(int32_t keyCode, int32_t orientation) {
127     return rotateValueUsingRotationMap(keyCode, orientation,
128             keyCodeRotationMap, keyCodeRotationMapSize);
129 }
130
131 static void rotateDelta(int32_t orientation, float* deltaX, float* deltaY) {
132     float temp;
133     switch (orientation) {
134     case DISPLAY_ORIENTATION_90:
135         temp = *deltaX;
136         *deltaX = *deltaY;
137         *deltaY = -temp;
138         break;
139
140     case DISPLAY_ORIENTATION_180:
141         *deltaX = -*deltaX;
142         *deltaY = -*deltaY;
143         break;
144
145     case DISPLAY_ORIENTATION_270:
146         temp = *deltaX;
147         *deltaX = -*deltaY;
148         *deltaY = temp;
149         break;
150     }
151 }
152
153 static inline bool sourcesMatchMask(uint32_t sources, uint32_t sourceMask) {
154     return (sources & sourceMask & ~ AINPUT_SOURCE_CLASS_MASK) != 0;
155 }
156
157 // Returns true if the pointer should be reported as being down given the specified
158 // button states.  This determines whether the event is reported as a touch event.
159 static bool isPointerDown(int32_t buttonState) {
160     return buttonState &
161             (AMOTION_EVENT_BUTTON_PRIMARY | AMOTION_EVENT_BUTTON_SECONDARY
162                     | AMOTION_EVENT_BUTTON_TERTIARY);
163 }
164
165 static float calculateCommonVector(float a, float b) {
166     if (a > 0 && b > 0) {
167         return a < b ? a : b;
168     } else if (a < 0 && b < 0) {
169         return a > b ? a : b;
170     } else {
171         return 0;
172     }
173 }
174
175 static void synthesizeButtonKey(InputReaderContext* context, int32_t action,
176         nsecs_t when, int32_t deviceId, uint32_t source,
177         uint32_t policyFlags, int32_t lastButtonState, int32_t currentButtonState,
178         int32_t buttonState, int32_t keyCode) {
179     if (
180             (action == AKEY_EVENT_ACTION_DOWN
181                     && !(lastButtonState & buttonState)
182                     && (currentButtonState & buttonState))
183             || (action == AKEY_EVENT_ACTION_UP
184                     && (lastButtonState & buttonState)
185                     && !(currentButtonState & buttonState))) {
186         NotifyKeyArgs args(when, deviceId, source, policyFlags,
187                 action, 0, keyCode, 0, context->getGlobalMetaState(), when);
188         context->getListener()->notifyKey(&args);
189     }
190 }
191
192 static void synthesizeButtonKeys(InputReaderContext* context, int32_t action,
193         nsecs_t when, int32_t deviceId, uint32_t source,
194         uint32_t policyFlags, int32_t lastButtonState, int32_t currentButtonState) {
195     synthesizeButtonKey(context, action, when, deviceId, source, policyFlags,
196             lastButtonState, currentButtonState,
197             AMOTION_EVENT_BUTTON_BACK, AKEYCODE_BACK);
198     synthesizeButtonKey(context, action, when, deviceId, source, policyFlags,
199             lastButtonState, currentButtonState,
200             AMOTION_EVENT_BUTTON_FORWARD, AKEYCODE_FORWARD);
201 }
202
203
204 // --- InputReaderConfiguration ---
205
206 bool InputReaderConfiguration::getDisplayInfo(bool external, DisplayViewport* outViewport) const {
207     const DisplayViewport& viewport = external ? mExternalDisplay : mInternalDisplay;
208     if (viewport.displayId >= 0) {
209         *outViewport = viewport;
210         return true;
211     }
212     return false;
213 }
214
215 void InputReaderConfiguration::setDisplayInfo(bool external, const DisplayViewport& viewport) {
216     DisplayViewport& v = external ? mExternalDisplay : mInternalDisplay;
217     v = viewport;
218 }
219
220
221 // -- TouchAffineTransformation --
222 void TouchAffineTransformation::applyTo(float& x, float& y) const {
223     float newX, newY;
224     newX = x * x_scale + y * x_ymix + x_offset;
225     newY = x * y_xmix + y * y_scale + y_offset;
226
227     x = newX;
228     y = newY;
229 }
230
231
232 // --- InputReader ---
233
234 InputReader::InputReader(const sp<EventHubInterface>& eventHub,
235         const sp<InputReaderPolicyInterface>& policy,
236         const sp<InputListenerInterface>& listener) :
237         mContext(this), mEventHub(eventHub), mPolicy(policy),
238         mGlobalMetaState(0), mGeneration(1),
239         mDisableVirtualKeysTimeout(LLONG_MIN), mNextTimeout(LLONG_MAX),
240         mConfigurationChangesToRefresh(0) {
241     mQueuedListener = new QueuedInputListener(listener);
242
243     { // acquire lock
244         AutoMutex _l(mLock);
245
246         refreshConfigurationLocked(0);
247         updateGlobalMetaStateLocked();
248     } // release lock
249 }
250
251 InputReader::~InputReader() {
252     for (size_t i = 0; i < mDevices.size(); i++) {
253         delete mDevices.valueAt(i);
254     }
255 }
256
257 void InputReader::loopOnce() {
258     int32_t oldGeneration;
259     int32_t timeoutMillis;
260     bool inputDevicesChanged = false;
261     Vector<InputDeviceInfo> inputDevices;
262     { // acquire lock
263         AutoMutex _l(mLock);
264
265         oldGeneration = mGeneration;
266         timeoutMillis = -1;
267
268         uint32_t changes = mConfigurationChangesToRefresh;
269         if (changes) {
270             mConfigurationChangesToRefresh = 0;
271             timeoutMillis = 0;
272             refreshConfigurationLocked(changes);
273         } else if (mNextTimeout != LLONG_MAX) {
274             nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
275             timeoutMillis = toMillisecondTimeoutDelay(now, mNextTimeout);
276         }
277     } // release lock
278
279     size_t count = mEventHub->getEvents(timeoutMillis, mEventBuffer, EVENT_BUFFER_SIZE);
280
281     { // acquire lock
282         AutoMutex _l(mLock);
283         mReaderIsAliveCondition.broadcast();
284
285         if (count) {
286             processEventsLocked(mEventBuffer, count);
287         }
288
289         if (mNextTimeout != LLONG_MAX) {
290             nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
291             if (now >= mNextTimeout) {
292 #if DEBUG_RAW_EVENTS
293                 ALOGD("Timeout expired, latency=%0.3fms", (now - mNextTimeout) * 0.000001f);
294 #endif
295                 mNextTimeout = LLONG_MAX;
296                 timeoutExpiredLocked(now);
297             }
298         }
299
300         if (oldGeneration != mGeneration) {
301             inputDevicesChanged = true;
302             getInputDevicesLocked(inputDevices);
303         }
304     } // release lock
305
306     // Send out a message that the describes the changed input devices.
307     if (inputDevicesChanged) {
308         mPolicy->notifyInputDevicesChanged(inputDevices);
309     }
310
311     // Flush queued events out to the listener.
312     // This must happen outside of the lock because the listener could potentially call
313     // back into the InputReader's methods, such as getScanCodeState, or become blocked
314     // on another thread similarly waiting to acquire the InputReader lock thereby
315     // resulting in a deadlock.  This situation is actually quite plausible because the
316     // listener is actually the input dispatcher, which calls into the window manager,
317     // which occasionally calls into the input reader.
318     mQueuedListener->flush();
319 }
320
321 void InputReader::processEventsLocked(const RawEvent* rawEvents, size_t count) {
322     for (const RawEvent* rawEvent = rawEvents; count;) {
323         int32_t type = rawEvent->type;
324         size_t batchSize = 1;
325         if (type < EventHubInterface::FIRST_SYNTHETIC_EVENT) {
326             int32_t deviceId = rawEvent->deviceId;
327             while (batchSize < count) {
328                 if (rawEvent[batchSize].type >= EventHubInterface::FIRST_SYNTHETIC_EVENT
329                         || rawEvent[batchSize].deviceId != deviceId) {
330                     break;
331                 }
332                 batchSize += 1;
333             }
334 #if DEBUG_RAW_EVENTS
335             ALOGD("BatchSize: %d Count: %d", batchSize, count);
336 #endif
337             processEventsForDeviceLocked(deviceId, rawEvent, batchSize);
338         } else {
339             switch (rawEvent->type) {
340             case EventHubInterface::DEVICE_ADDED:
341                 addDeviceLocked(rawEvent->when, rawEvent->deviceId);
342                 break;
343             case EventHubInterface::DEVICE_REMOVED:
344                 removeDeviceLocked(rawEvent->when, rawEvent->deviceId);
345                 break;
346             case EventHubInterface::FINISHED_DEVICE_SCAN:
347                 handleConfigurationChangedLocked(rawEvent->when);
348                 break;
349             default:
350                 ALOG_ASSERT(false); // can't happen
351                 break;
352             }
353         }
354         count -= batchSize;
355         rawEvent += batchSize;
356     }
357 }
358
359 void InputReader::addDeviceLocked(nsecs_t when, int32_t deviceId) {
360     ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
361     if (deviceIndex >= 0) {
362         ALOGW("Ignoring spurious device added event for deviceId %d.", deviceId);
363         return;
364     }
365
366     InputDeviceIdentifier identifier = mEventHub->getDeviceIdentifier(deviceId);
367     uint32_t classes = mEventHub->getDeviceClasses(deviceId);
368     int32_t controllerNumber = mEventHub->getDeviceControllerNumber(deviceId);
369
370     InputDevice* device = createDeviceLocked(deviceId, controllerNumber, identifier, classes);
371     device->configure(when, &mConfig, 0);
372     device->reset(when);
373
374     if (device->isIgnored()) {
375         ALOGI("Device added: id=%d, name='%s' (ignored non-input device)", deviceId,
376                 identifier.name.string());
377     } else {
378         ALOGI("Device added: id=%d, name='%s', sources=0x%08x", deviceId,
379                 identifier.name.string(), device->getSources());
380     }
381
382     mDevices.add(deviceId, device);
383     bumpGenerationLocked();
384 }
385
386 void InputReader::removeDeviceLocked(nsecs_t when, int32_t deviceId) {
387     InputDevice* device = NULL;
388     ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
389     if (deviceIndex < 0) {
390         ALOGW("Ignoring spurious device removed event for deviceId %d.", deviceId);
391         return;
392     }
393
394     device = mDevices.valueAt(deviceIndex);
395     mDevices.removeItemsAt(deviceIndex, 1);
396     bumpGenerationLocked();
397
398     if (device->isIgnored()) {
399         ALOGI("Device removed: id=%d, name='%s' (ignored non-input device)",
400                 device->getId(), device->getName().string());
401     } else {
402         ALOGI("Device removed: id=%d, name='%s', sources=0x%08x",
403                 device->getId(), device->getName().string(), device->getSources());
404     }
405
406     device->reset(when);
407     delete device;
408 }
409
410 InputDevice* InputReader::createDeviceLocked(int32_t deviceId, int32_t controllerNumber,
411         const InputDeviceIdentifier& identifier, uint32_t classes) {
412     InputDevice* device = new InputDevice(&mContext, deviceId, bumpGenerationLocked(),
413             controllerNumber, identifier, classes);
414
415     // External devices.
416     if (classes & INPUT_DEVICE_CLASS_EXTERNAL) {
417         device->setExternal(true);
418     }
419
420     // Switch-like devices.
421     if (classes & INPUT_DEVICE_CLASS_SWITCH) {
422         device->addMapper(new SwitchInputMapper(device));
423     }
424
425     // Vibrator-like devices.
426     if (classes & INPUT_DEVICE_CLASS_VIBRATOR) {
427         device->addMapper(new VibratorInputMapper(device));
428     }
429
430     // Keyboard-like devices.
431     uint32_t keyboardSource = 0;
432     int32_t keyboardType = AINPUT_KEYBOARD_TYPE_NON_ALPHABETIC;
433     if (classes & INPUT_DEVICE_CLASS_KEYBOARD) {
434         keyboardSource |= AINPUT_SOURCE_KEYBOARD;
435     }
436     if (classes & INPUT_DEVICE_CLASS_ALPHAKEY) {
437         keyboardType = AINPUT_KEYBOARD_TYPE_ALPHABETIC;
438     }
439     if (classes & INPUT_DEVICE_CLASS_DPAD) {
440         keyboardSource |= AINPUT_SOURCE_DPAD;
441     }
442     if (classes & INPUT_DEVICE_CLASS_GAMEPAD) {
443         keyboardSource |= AINPUT_SOURCE_GAMEPAD;
444     }
445
446     if (keyboardSource != 0) {
447         device->addMapper(new KeyboardInputMapper(device, keyboardSource, keyboardType));
448     }
449
450     // Cursor-like devices.
451     if (classes & INPUT_DEVICE_CLASS_CURSOR) {
452         device->addMapper(new CursorInputMapper(device));
453     }
454
455     // Touchscreens and touchpad devices.
456     if (classes & INPUT_DEVICE_CLASS_TOUCH_MT) {
457         device->addMapper(new MultiTouchInputMapper(device));
458     } else if (classes & INPUT_DEVICE_CLASS_TOUCH) {
459         device->addMapper(new SingleTouchInputMapper(device));
460     }
461
462     // Joystick-like devices.
463     if (classes & INPUT_DEVICE_CLASS_JOYSTICK) {
464         device->addMapper(new JoystickInputMapper(device));
465     }
466
467     return device;
468 }
469
470 void InputReader::processEventsForDeviceLocked(int32_t deviceId,
471         const RawEvent* rawEvents, size_t count) {
472     ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
473     if (deviceIndex < 0) {
474         ALOGW("Discarding event for unknown deviceId %d.", deviceId);
475         return;
476     }
477
478     InputDevice* device = mDevices.valueAt(deviceIndex);
479     if (device->isIgnored()) {
480         //ALOGD("Discarding event for ignored deviceId %d.", deviceId);
481         return;
482     }
483
484     device->process(rawEvents, count);
485 }
486
487 void InputReader::timeoutExpiredLocked(nsecs_t when) {
488     for (size_t i = 0; i < mDevices.size(); i++) {
489         InputDevice* device = mDevices.valueAt(i);
490         if (!device->isIgnored()) {
491             device->timeoutExpired(when);
492         }
493     }
494 }
495
496 void InputReader::handleConfigurationChangedLocked(nsecs_t when) {
497     // Reset global meta state because it depends on the list of all configured devices.
498     updateGlobalMetaStateLocked();
499
500     // Enqueue configuration changed.
501     NotifyConfigurationChangedArgs args(when);
502     mQueuedListener->notifyConfigurationChanged(&args);
503 }
504
505 void InputReader::refreshConfigurationLocked(uint32_t changes) {
506     mPolicy->getReaderConfiguration(&mConfig);
507     mEventHub->setExcludedDevices(mConfig.excludedDeviceNames);
508
509     if (changes) {
510         ALOGI("Reconfiguring input devices.  changes=0x%08x", changes);
511         nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
512
513         if (changes & InputReaderConfiguration::CHANGE_MUST_REOPEN) {
514             mEventHub->requestReopenDevices();
515         } else {
516             for (size_t i = 0; i < mDevices.size(); i++) {
517                 InputDevice* device = mDevices.valueAt(i);
518                 device->configure(now, &mConfig, changes);
519             }
520         }
521     }
522 }
523
524 void InputReader::updateGlobalMetaStateLocked() {
525     mGlobalMetaState = 0;
526
527     for (size_t i = 0; i < mDevices.size(); i++) {
528         InputDevice* device = mDevices.valueAt(i);
529         mGlobalMetaState |= device->getMetaState();
530     }
531 }
532
533 int32_t InputReader::getGlobalMetaStateLocked() {
534     return mGlobalMetaState;
535 }
536
537 void InputReader::disableVirtualKeysUntilLocked(nsecs_t time) {
538     mDisableVirtualKeysTimeout = time;
539 }
540
541 bool InputReader::shouldDropVirtualKeyLocked(nsecs_t now,
542         InputDevice* device, int32_t keyCode, int32_t scanCode) {
543     if (now < mDisableVirtualKeysTimeout) {
544         ALOGI("Dropping virtual key from device %s because virtual keys are "
545                 "temporarily disabled for the next %0.3fms.  keyCode=%d, scanCode=%d",
546                 device->getName().string(),
547                 (mDisableVirtualKeysTimeout - now) * 0.000001,
548                 keyCode, scanCode);
549         return true;
550     } else {
551         return false;
552     }
553 }
554
555 void InputReader::fadePointerLocked() {
556     for (size_t i = 0; i < mDevices.size(); i++) {
557         InputDevice* device = mDevices.valueAt(i);
558         device->fadePointer();
559     }
560 }
561
562 void InputReader::requestTimeoutAtTimeLocked(nsecs_t when) {
563     if (when < mNextTimeout) {
564         mNextTimeout = when;
565         mEventHub->wake();
566     }
567 }
568
569 int32_t InputReader::bumpGenerationLocked() {
570     return ++mGeneration;
571 }
572
573 void InputReader::getInputDevices(Vector<InputDeviceInfo>& outInputDevices) {
574     AutoMutex _l(mLock);
575     getInputDevicesLocked(outInputDevices);
576 }
577
578 void InputReader::getInputDevicesLocked(Vector<InputDeviceInfo>& outInputDevices) {
579     outInputDevices.clear();
580
581     size_t numDevices = mDevices.size();
582     for (size_t i = 0; i < numDevices; i++) {
583         InputDevice* device = mDevices.valueAt(i);
584         if (!device->isIgnored()) {
585             outInputDevices.push();
586             device->getDeviceInfo(&outInputDevices.editTop());
587         }
588     }
589 }
590
591 int32_t InputReader::getKeyCodeState(int32_t deviceId, uint32_t sourceMask,
592         int32_t keyCode) {
593     AutoMutex _l(mLock);
594
595     return getStateLocked(deviceId, sourceMask, keyCode, &InputDevice::getKeyCodeState);
596 }
597
598 int32_t InputReader::getScanCodeState(int32_t deviceId, uint32_t sourceMask,
599         int32_t scanCode) {
600     AutoMutex _l(mLock);
601
602     return getStateLocked(deviceId, sourceMask, scanCode, &InputDevice::getScanCodeState);
603 }
604
605 int32_t InputReader::getSwitchState(int32_t deviceId, uint32_t sourceMask, int32_t switchCode) {
606     AutoMutex _l(mLock);
607
608     return getStateLocked(deviceId, sourceMask, switchCode, &InputDevice::getSwitchState);
609 }
610
611 int32_t InputReader::getStateLocked(int32_t deviceId, uint32_t sourceMask, int32_t code,
612         GetStateFunc getStateFunc) {
613     int32_t result = AKEY_STATE_UNKNOWN;
614     if (deviceId >= 0) {
615         ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
616         if (deviceIndex >= 0) {
617             InputDevice* device = mDevices.valueAt(deviceIndex);
618             if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
619                 result = (device->*getStateFunc)(sourceMask, code);
620             }
621         }
622     } else {
623         size_t numDevices = mDevices.size();
624         for (size_t i = 0; i < numDevices; i++) {
625             InputDevice* device = mDevices.valueAt(i);
626             if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
627                 // If any device reports AKEY_STATE_DOWN or AKEY_STATE_VIRTUAL, return that
628                 // value.  Otherwise, return AKEY_STATE_UP as long as one device reports it.
629                 int32_t currentResult = (device->*getStateFunc)(sourceMask, code);
630                 if (currentResult >= AKEY_STATE_DOWN) {
631                     return currentResult;
632                 } else if (currentResult == AKEY_STATE_UP) {
633                     result = currentResult;
634                 }
635             }
636         }
637     }
638     return result;
639 }
640
641 bool InputReader::hasKeys(int32_t deviceId, uint32_t sourceMask,
642         size_t numCodes, const int32_t* keyCodes, uint8_t* outFlags) {
643     AutoMutex _l(mLock);
644
645     memset(outFlags, 0, numCodes);
646     return markSupportedKeyCodesLocked(deviceId, sourceMask, numCodes, keyCodes, outFlags);
647 }
648
649 bool InputReader::markSupportedKeyCodesLocked(int32_t deviceId, uint32_t sourceMask,
650         size_t numCodes, const int32_t* keyCodes, uint8_t* outFlags) {
651     bool result = false;
652     if (deviceId >= 0) {
653         ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
654         if (deviceIndex >= 0) {
655             InputDevice* device = mDevices.valueAt(deviceIndex);
656             if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
657                 result = device->markSupportedKeyCodes(sourceMask,
658                         numCodes, keyCodes, outFlags);
659             }
660         }
661     } else {
662         size_t numDevices = mDevices.size();
663         for (size_t i = 0; i < numDevices; i++) {
664             InputDevice* device = mDevices.valueAt(i);
665             if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
666                 result |= device->markSupportedKeyCodes(sourceMask,
667                         numCodes, keyCodes, outFlags);
668             }
669         }
670     }
671     return result;
672 }
673
674 void InputReader::requestRefreshConfiguration(uint32_t changes) {
675     AutoMutex _l(mLock);
676
677     if (changes) {
678         bool needWake = !mConfigurationChangesToRefresh;
679         mConfigurationChangesToRefresh |= changes;
680
681         if (needWake) {
682             mEventHub->wake();
683         }
684     }
685 }
686
687 void InputReader::vibrate(int32_t deviceId, const nsecs_t* pattern, size_t patternSize,
688         ssize_t repeat, int32_t token) {
689     AutoMutex _l(mLock);
690
691     ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
692     if (deviceIndex >= 0) {
693         InputDevice* device = mDevices.valueAt(deviceIndex);
694         device->vibrate(pattern, patternSize, repeat, token);
695     }
696 }
697
698 void InputReader::cancelVibrate(int32_t deviceId, int32_t token) {
699     AutoMutex _l(mLock);
700
701     ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
702     if (deviceIndex >= 0) {
703         InputDevice* device = mDevices.valueAt(deviceIndex);
704         device->cancelVibrate(token);
705     }
706 }
707
708 void InputReader::dump(String8& dump) {
709     AutoMutex _l(mLock);
710
711     mEventHub->dump(dump);
712     dump.append("\n");
713
714     dump.append("Input Reader State:\n");
715
716     for (size_t i = 0; i < mDevices.size(); i++) {
717         mDevices.valueAt(i)->dump(dump);
718     }
719
720     dump.append(INDENT "Configuration:\n");
721     dump.append(INDENT2 "ExcludedDeviceNames: [");
722     for (size_t i = 0; i < mConfig.excludedDeviceNames.size(); i++) {
723         if (i != 0) {
724             dump.append(", ");
725         }
726         dump.append(mConfig.excludedDeviceNames.itemAt(i).string());
727     }
728     dump.append("]\n");
729     dump.appendFormat(INDENT2 "VirtualKeyQuietTime: %0.1fms\n",
730             mConfig.virtualKeyQuietTime * 0.000001f);
731
732     dump.appendFormat(INDENT2 "PointerVelocityControlParameters: "
733             "scale=%0.3f, lowThreshold=%0.3f, highThreshold=%0.3f, acceleration=%0.3f\n",
734             mConfig.pointerVelocityControlParameters.scale,
735             mConfig.pointerVelocityControlParameters.lowThreshold,
736             mConfig.pointerVelocityControlParameters.highThreshold,
737             mConfig.pointerVelocityControlParameters.acceleration);
738
739     dump.appendFormat(INDENT2 "WheelVelocityControlParameters: "
740             "scale=%0.3f, lowThreshold=%0.3f, highThreshold=%0.3f, acceleration=%0.3f\n",
741             mConfig.wheelVelocityControlParameters.scale,
742             mConfig.wheelVelocityControlParameters.lowThreshold,
743             mConfig.wheelVelocityControlParameters.highThreshold,
744             mConfig.wheelVelocityControlParameters.acceleration);
745
746     dump.appendFormat(INDENT2 "PointerGesture:\n");
747     dump.appendFormat(INDENT3 "Enabled: %s\n",
748             toString(mConfig.pointerGesturesEnabled));
749     dump.appendFormat(INDENT3 "QuietInterval: %0.1fms\n",
750             mConfig.pointerGestureQuietInterval * 0.000001f);
751     dump.appendFormat(INDENT3 "DragMinSwitchSpeed: %0.1fpx/s\n",
752             mConfig.pointerGestureDragMinSwitchSpeed);
753     dump.appendFormat(INDENT3 "TapInterval: %0.1fms\n",
754             mConfig.pointerGestureTapInterval * 0.000001f);
755     dump.appendFormat(INDENT3 "TapDragInterval: %0.1fms\n",
756             mConfig.pointerGestureTapDragInterval * 0.000001f);
757     dump.appendFormat(INDENT3 "TapSlop: %0.1fpx\n",
758             mConfig.pointerGestureTapSlop);
759     dump.appendFormat(INDENT3 "MultitouchSettleInterval: %0.1fms\n",
760             mConfig.pointerGestureMultitouchSettleInterval * 0.000001f);
761     dump.appendFormat(INDENT3 "MultitouchMinDistance: %0.1fpx\n",
762             mConfig.pointerGestureMultitouchMinDistance);
763     dump.appendFormat(INDENT3 "SwipeTransitionAngleCosine: %0.1f\n",
764             mConfig.pointerGestureSwipeTransitionAngleCosine);
765     dump.appendFormat(INDENT3 "SwipeMaxWidthRatio: %0.1f\n",
766             mConfig.pointerGestureSwipeMaxWidthRatio);
767     dump.appendFormat(INDENT3 "MovementSpeedRatio: %0.1f\n",
768             mConfig.pointerGestureMovementSpeedRatio);
769     dump.appendFormat(INDENT3 "ZoomSpeedRatio: %0.1f\n",
770             mConfig.pointerGestureZoomSpeedRatio);
771 }
772
773 void InputReader::monitor() {
774     // Acquire and release the lock to ensure that the reader has not deadlocked.
775     mLock.lock();
776     mEventHub->wake();
777     mReaderIsAliveCondition.wait(mLock);
778     mLock.unlock();
779
780     // Check the EventHub
781     mEventHub->monitor();
782 }
783
784
785 // --- InputReader::ContextImpl ---
786
787 InputReader::ContextImpl::ContextImpl(InputReader* reader) :
788         mReader(reader) {
789 }
790
791 void InputReader::ContextImpl::updateGlobalMetaState() {
792     // lock is already held by the input loop
793     mReader->updateGlobalMetaStateLocked();
794 }
795
796 int32_t InputReader::ContextImpl::getGlobalMetaState() {
797     // lock is already held by the input loop
798     return mReader->getGlobalMetaStateLocked();
799 }
800
801 void InputReader::ContextImpl::disableVirtualKeysUntil(nsecs_t time) {
802     // lock is already held by the input loop
803     mReader->disableVirtualKeysUntilLocked(time);
804 }
805
806 bool InputReader::ContextImpl::shouldDropVirtualKey(nsecs_t now,
807         InputDevice* device, int32_t keyCode, int32_t scanCode) {
808     // lock is already held by the input loop
809     return mReader->shouldDropVirtualKeyLocked(now, device, keyCode, scanCode);
810 }
811
812 void InputReader::ContextImpl::fadePointer() {
813     // lock is already held by the input loop
814     mReader->fadePointerLocked();
815 }
816
817 void InputReader::ContextImpl::requestTimeoutAtTime(nsecs_t when) {
818     // lock is already held by the input loop
819     mReader->requestTimeoutAtTimeLocked(when);
820 }
821
822 int32_t InputReader::ContextImpl::bumpGeneration() {
823     // lock is already held by the input loop
824     return mReader->bumpGenerationLocked();
825 }
826
827 InputReaderPolicyInterface* InputReader::ContextImpl::getPolicy() {
828     return mReader->mPolicy.get();
829 }
830
831 InputListenerInterface* InputReader::ContextImpl::getListener() {
832     return mReader->mQueuedListener.get();
833 }
834
835 EventHubInterface* InputReader::ContextImpl::getEventHub() {
836     return mReader->mEventHub.get();
837 }
838
839
840 // --- InputReaderThread ---
841
842 InputReaderThread::InputReaderThread(const sp<InputReaderInterface>& reader) :
843         Thread(/*canCallJava*/ true), mReader(reader) {
844 }
845
846 InputReaderThread::~InputReaderThread() {
847 }
848
849 bool InputReaderThread::threadLoop() {
850     mReader->loopOnce();
851     return true;
852 }
853
854
855 // --- InputDevice ---
856
857 InputDevice::InputDevice(InputReaderContext* context, int32_t id, int32_t generation,
858         int32_t controllerNumber, const InputDeviceIdentifier& identifier, uint32_t classes) :
859         mContext(context), mId(id), mGeneration(generation), mControllerNumber(controllerNumber),
860         mIdentifier(identifier), mClasses(classes),
861         mSources(0), mIsExternal(false), mDropUntilNextSync(false) {
862 }
863
864 InputDevice::~InputDevice() {
865     size_t numMappers = mMappers.size();
866     for (size_t i = 0; i < numMappers; i++) {
867         delete mMappers[i];
868     }
869     mMappers.clear();
870 }
871
872 void InputDevice::dump(String8& dump) {
873     InputDeviceInfo deviceInfo;
874     getDeviceInfo(& deviceInfo);
875
876     dump.appendFormat(INDENT "Device %d: %s\n", deviceInfo.getId(),
877             deviceInfo.getDisplayName().string());
878     dump.appendFormat(INDENT2 "Generation: %d\n", mGeneration);
879     dump.appendFormat(INDENT2 "IsExternal: %s\n", toString(mIsExternal));
880     dump.appendFormat(INDENT2 "Sources: 0x%08x\n", deviceInfo.getSources());
881     dump.appendFormat(INDENT2 "KeyboardType: %d\n", deviceInfo.getKeyboardType());
882
883     const Vector<InputDeviceInfo::MotionRange>& ranges = deviceInfo.getMotionRanges();
884     if (!ranges.isEmpty()) {
885         dump.append(INDENT2 "Motion Ranges:\n");
886         for (size_t i = 0; i < ranges.size(); i++) {
887             const InputDeviceInfo::MotionRange& range = ranges.itemAt(i);
888             const char* label = getAxisLabel(range.axis);
889             char name[32];
890             if (label) {
891                 strncpy(name, label, sizeof(name));
892                 name[sizeof(name) - 1] = '\0';
893             } else {
894                 snprintf(name, sizeof(name), "%d", range.axis);
895             }
896             dump.appendFormat(INDENT3 "%s: source=0x%08x, "
897                     "min=%0.3f, max=%0.3f, flat=%0.3f, fuzz=%0.3f, resolution=%0.3f\n",
898                     name, range.source, range.min, range.max, range.flat, range.fuzz,
899                     range.resolution);
900         }
901     }
902
903     size_t numMappers = mMappers.size();
904     for (size_t i = 0; i < numMappers; i++) {
905         InputMapper* mapper = mMappers[i];
906         mapper->dump(dump);
907     }
908 }
909
910 void InputDevice::addMapper(InputMapper* mapper) {
911     mMappers.add(mapper);
912 }
913
914 void InputDevice::configure(nsecs_t when, const InputReaderConfiguration* config, uint32_t changes) {
915     mSources = 0;
916
917     if (!isIgnored()) {
918         if (!changes) { // first time only
919             mContext->getEventHub()->getConfiguration(mId, &mConfiguration);
920         }
921
922         if (!changes || (changes & InputReaderConfiguration::CHANGE_KEYBOARD_LAYOUTS)) {
923             if (!(mClasses & INPUT_DEVICE_CLASS_VIRTUAL)) {
924                 sp<KeyCharacterMap> keyboardLayout =
925                         mContext->getPolicy()->getKeyboardLayoutOverlay(mIdentifier);
926                 if (mContext->getEventHub()->setKeyboardLayoutOverlay(mId, keyboardLayout)) {
927                     bumpGeneration();
928                 }
929             }
930         }
931
932         if (!changes || (changes & InputReaderConfiguration::CHANGE_DEVICE_ALIAS)) {
933             if (!(mClasses & INPUT_DEVICE_CLASS_VIRTUAL)) {
934                 String8 alias = mContext->getPolicy()->getDeviceAlias(mIdentifier);
935                 if (mAlias != alias) {
936                     mAlias = alias;
937                     bumpGeneration();
938                 }
939             }
940         }
941
942         size_t numMappers = mMappers.size();
943         for (size_t i = 0; i < numMappers; i++) {
944             InputMapper* mapper = mMappers[i];
945             mapper->configure(when, config, changes);
946             mSources |= mapper->getSources();
947         }
948     }
949 }
950
951 void InputDevice::reset(nsecs_t when) {
952     size_t numMappers = mMappers.size();
953     for (size_t i = 0; i < numMappers; i++) {
954         InputMapper* mapper = mMappers[i];
955         mapper->reset(when);
956     }
957
958     mContext->updateGlobalMetaState();
959
960     notifyReset(when);
961 }
962
963 void InputDevice::process(const RawEvent* rawEvents, size_t count) {
964     // Process all of the events in order for each mapper.
965     // We cannot simply ask each mapper to process them in bulk because mappers may
966     // have side-effects that must be interleaved.  For example, joystick movement events and
967     // gamepad button presses are handled by different mappers but they should be dispatched
968     // in the order received.
969     size_t numMappers = mMappers.size();
970     for (const RawEvent* rawEvent = rawEvents; count--; rawEvent++) {
971 #if DEBUG_RAW_EVENTS
972         ALOGD("Input event: device=%d type=0x%04x code=0x%04x value=0x%08x when=%lld",
973                 rawEvent->deviceId, rawEvent->type, rawEvent->code, rawEvent->value,
974                 rawEvent->when);
975 #endif
976
977         if (mDropUntilNextSync) {
978             if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
979                 mDropUntilNextSync = false;
980 #if DEBUG_RAW_EVENTS
981                 ALOGD("Recovered from input event buffer overrun.");
982 #endif
983             } else {
984 #if DEBUG_RAW_EVENTS
985                 ALOGD("Dropped input event while waiting for next input sync.");
986 #endif
987             }
988         } else if (rawEvent->type == EV_SYN && rawEvent->code == SYN_DROPPED) {
989             ALOGI("Detected input event buffer overrun for device %s.", getName().string());
990             mDropUntilNextSync = true;
991             reset(rawEvent->when);
992         } else {
993             for (size_t i = 0; i < numMappers; i++) {
994                 InputMapper* mapper = mMappers[i];
995                 mapper->process(rawEvent);
996             }
997         }
998     }
999 }
1000
1001 void InputDevice::timeoutExpired(nsecs_t when) {
1002     size_t numMappers = mMappers.size();
1003     for (size_t i = 0; i < numMappers; i++) {
1004         InputMapper* mapper = mMappers[i];
1005         mapper->timeoutExpired(when);
1006     }
1007 }
1008
1009 void InputDevice::getDeviceInfo(InputDeviceInfo* outDeviceInfo) {
1010     outDeviceInfo->initialize(mId, mGeneration, mControllerNumber, mIdentifier, mAlias,
1011             mIsExternal);
1012
1013     size_t numMappers = mMappers.size();
1014     for (size_t i = 0; i < numMappers; i++) {
1015         InputMapper* mapper = mMappers[i];
1016         mapper->populateDeviceInfo(outDeviceInfo);
1017     }
1018 }
1019
1020 int32_t InputDevice::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
1021     return getState(sourceMask, keyCode, & InputMapper::getKeyCodeState);
1022 }
1023
1024 int32_t InputDevice::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
1025     return getState(sourceMask, scanCode, & InputMapper::getScanCodeState);
1026 }
1027
1028 int32_t InputDevice::getSwitchState(uint32_t sourceMask, int32_t switchCode) {
1029     return getState(sourceMask, switchCode, & InputMapper::getSwitchState);
1030 }
1031
1032 int32_t InputDevice::getState(uint32_t sourceMask, int32_t code, GetStateFunc getStateFunc) {
1033     int32_t result = AKEY_STATE_UNKNOWN;
1034     size_t numMappers = mMappers.size();
1035     for (size_t i = 0; i < numMappers; i++) {
1036         InputMapper* mapper = mMappers[i];
1037         if (sourcesMatchMask(mapper->getSources(), sourceMask)) {
1038             // If any mapper reports AKEY_STATE_DOWN or AKEY_STATE_VIRTUAL, return that
1039             // value.  Otherwise, return AKEY_STATE_UP as long as one mapper reports it.
1040             int32_t currentResult = (mapper->*getStateFunc)(sourceMask, code);
1041             if (currentResult >= AKEY_STATE_DOWN) {
1042                 return currentResult;
1043             } else if (currentResult == AKEY_STATE_UP) {
1044                 result = currentResult;
1045             }
1046         }
1047     }
1048     return result;
1049 }
1050
1051 bool InputDevice::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
1052         const int32_t* keyCodes, uint8_t* outFlags) {
1053     bool result = false;
1054     size_t numMappers = mMappers.size();
1055     for (size_t i = 0; i < numMappers; i++) {
1056         InputMapper* mapper = mMappers[i];
1057         if (sourcesMatchMask(mapper->getSources(), sourceMask)) {
1058             result |= mapper->markSupportedKeyCodes(sourceMask, numCodes, keyCodes, outFlags);
1059         }
1060     }
1061     return result;
1062 }
1063
1064 void InputDevice::vibrate(const nsecs_t* pattern, size_t patternSize, ssize_t repeat,
1065         int32_t token) {
1066     size_t numMappers = mMappers.size();
1067     for (size_t i = 0; i < numMappers; i++) {
1068         InputMapper* mapper = mMappers[i];
1069         mapper->vibrate(pattern, patternSize, repeat, token);
1070     }
1071 }
1072
1073 void InputDevice::cancelVibrate(int32_t token) {
1074     size_t numMappers = mMappers.size();
1075     for (size_t i = 0; i < numMappers; i++) {
1076         InputMapper* mapper = mMappers[i];
1077         mapper->cancelVibrate(token);
1078     }
1079 }
1080
1081 int32_t InputDevice::getMetaState() {
1082     int32_t result = 0;
1083     size_t numMappers = mMappers.size();
1084     for (size_t i = 0; i < numMappers; i++) {
1085         InputMapper* mapper = mMappers[i];
1086         result |= mapper->getMetaState();
1087     }
1088     return result;
1089 }
1090
1091 void InputDevice::fadePointer() {
1092     size_t numMappers = mMappers.size();
1093     for (size_t i = 0; i < numMappers; i++) {
1094         InputMapper* mapper = mMappers[i];
1095         mapper->fadePointer();
1096     }
1097 }
1098
1099 void InputDevice::bumpGeneration() {
1100     mGeneration = mContext->bumpGeneration();
1101 }
1102
1103 void InputDevice::notifyReset(nsecs_t when) {
1104     NotifyDeviceResetArgs args(when, mId);
1105     mContext->getListener()->notifyDeviceReset(&args);
1106 }
1107
1108
1109 // --- CursorButtonAccumulator ---
1110
1111 CursorButtonAccumulator::CursorButtonAccumulator() {
1112     clearButtons();
1113 }
1114
1115 void CursorButtonAccumulator::reset(InputDevice* device) {
1116     mBtnLeft = device->isKeyPressed(BTN_LEFT);
1117     mBtnRight = device->isKeyPressed(BTN_RIGHT);
1118     mBtnMiddle = device->isKeyPressed(BTN_MIDDLE);
1119     mBtnBack = device->isKeyPressed(BTN_BACK);
1120     mBtnSide = device->isKeyPressed(BTN_SIDE);
1121     mBtnForward = device->isKeyPressed(BTN_FORWARD);
1122     mBtnExtra = device->isKeyPressed(BTN_EXTRA);
1123     mBtnTask = device->isKeyPressed(BTN_TASK);
1124 }
1125
1126 void CursorButtonAccumulator::clearButtons() {
1127     mBtnLeft = 0;
1128     mBtnRight = 0;
1129     mBtnMiddle = 0;
1130     mBtnBack = 0;
1131     mBtnSide = 0;
1132     mBtnForward = 0;
1133     mBtnExtra = 0;
1134     mBtnTask = 0;
1135 }
1136
1137 void CursorButtonAccumulator::process(const RawEvent* rawEvent) {
1138     if (rawEvent->type == EV_KEY) {
1139         switch (rawEvent->code) {
1140         case BTN_LEFT:
1141             mBtnLeft = rawEvent->value;
1142             break;
1143         case BTN_RIGHT:
1144             mBtnRight = rawEvent->value;
1145             break;
1146         case BTN_MIDDLE:
1147             mBtnMiddle = rawEvent->value;
1148             break;
1149         case BTN_BACK:
1150             mBtnBack = rawEvent->value;
1151             break;
1152         case BTN_SIDE:
1153             mBtnSide = rawEvent->value;
1154             break;
1155         case BTN_FORWARD:
1156             mBtnForward = rawEvent->value;
1157             break;
1158         case BTN_EXTRA:
1159             mBtnExtra = rawEvent->value;
1160             break;
1161         case BTN_TASK:
1162             mBtnTask = rawEvent->value;
1163             break;
1164         }
1165     }
1166 }
1167
1168 uint32_t CursorButtonAccumulator::getButtonState() const {
1169     uint32_t result = 0;
1170     if (mBtnLeft) {
1171         result |= AMOTION_EVENT_BUTTON_PRIMARY;
1172     }
1173     if (mBtnRight) {
1174         result |= AMOTION_EVENT_BUTTON_SECONDARY;
1175     }
1176     if (mBtnMiddle) {
1177         result |= AMOTION_EVENT_BUTTON_TERTIARY;
1178     }
1179     if (mBtnBack || mBtnSide) {
1180         result |= AMOTION_EVENT_BUTTON_BACK;
1181     }
1182     if (mBtnForward || mBtnExtra) {
1183         result |= AMOTION_EVENT_BUTTON_FORWARD;
1184     }
1185     return result;
1186 }
1187
1188
1189 // --- CursorMotionAccumulator ---
1190
1191 CursorMotionAccumulator::CursorMotionAccumulator() {
1192     clearRelativeAxes();
1193 }
1194
1195 void CursorMotionAccumulator::reset(InputDevice* device) {
1196     clearRelativeAxes();
1197 }
1198
1199 void CursorMotionAccumulator::clearRelativeAxes() {
1200     mRelX = 0;
1201     mRelY = 0;
1202 }
1203
1204 void CursorMotionAccumulator::process(const RawEvent* rawEvent) {
1205     if (rawEvent->type == EV_REL) {
1206         switch (rawEvent->code) {
1207         case REL_X:
1208             mRelX = rawEvent->value;
1209             break;
1210         case REL_Y:
1211             mRelY = rawEvent->value;
1212             break;
1213         }
1214     }
1215 }
1216
1217 void CursorMotionAccumulator::finishSync() {
1218     clearRelativeAxes();
1219 }
1220
1221
1222 // --- CursorScrollAccumulator ---
1223
1224 CursorScrollAccumulator::CursorScrollAccumulator() :
1225         mHaveRelWheel(false), mHaveRelHWheel(false) {
1226     clearRelativeAxes();
1227 }
1228
1229 void CursorScrollAccumulator::configure(InputDevice* device) {
1230     mHaveRelWheel = device->getEventHub()->hasRelativeAxis(device->getId(), REL_WHEEL);
1231     mHaveRelHWheel = device->getEventHub()->hasRelativeAxis(device->getId(), REL_HWHEEL);
1232 }
1233
1234 void CursorScrollAccumulator::reset(InputDevice* device) {
1235     clearRelativeAxes();
1236 }
1237
1238 void CursorScrollAccumulator::clearRelativeAxes() {
1239     mRelWheel = 0;
1240     mRelHWheel = 0;
1241 }
1242
1243 void CursorScrollAccumulator::process(const RawEvent* rawEvent) {
1244     if (rawEvent->type == EV_REL) {
1245         switch (rawEvent->code) {
1246         case REL_WHEEL:
1247             mRelWheel = rawEvent->value;
1248             break;
1249         case REL_HWHEEL:
1250             mRelHWheel = rawEvent->value;
1251             break;
1252         }
1253     }
1254 }
1255
1256 void CursorScrollAccumulator::finishSync() {
1257     clearRelativeAxes();
1258 }
1259
1260
1261 // --- TouchButtonAccumulator ---
1262
1263 TouchButtonAccumulator::TouchButtonAccumulator() :
1264         mHaveBtnTouch(false), mHaveStylus(false) {
1265     clearButtons();
1266 }
1267
1268 void TouchButtonAccumulator::configure(InputDevice* device) {
1269     mHaveBtnTouch = device->hasKey(BTN_TOUCH) || device->hasKey(BTN_LEFT);
1270     mHaveStylus = device->hasKey(BTN_TOOL_PEN)
1271             || device->hasKey(BTN_TOOL_RUBBER)
1272             || device->hasKey(BTN_TOOL_BRUSH)
1273             || device->hasKey(BTN_TOOL_PENCIL)
1274             || device->hasKey(BTN_TOOL_AIRBRUSH);
1275 }
1276
1277 void TouchButtonAccumulator::reset(InputDevice* device) {
1278     mBtnTouch = device->isKeyPressed(BTN_TOUCH) || device->isKeyPressed(BTN_LEFT);
1279     mBtnStylus = device->isKeyPressed(BTN_STYLUS);
1280     mBtnStylus2 = device->isKeyPressed(BTN_STYLUS);
1281     mBtnToolFinger = device->isKeyPressed(BTN_TOOL_FINGER);
1282     mBtnToolPen = device->isKeyPressed(BTN_TOOL_PEN);
1283     mBtnToolRubber = device->isKeyPressed(BTN_TOOL_RUBBER);
1284     mBtnToolBrush = device->isKeyPressed(BTN_TOOL_BRUSH);
1285     mBtnToolPencil = device->isKeyPressed(BTN_TOOL_PENCIL);
1286     mBtnToolAirbrush = device->isKeyPressed(BTN_TOOL_AIRBRUSH);
1287     mBtnToolMouse = device->isKeyPressed(BTN_TOOL_MOUSE);
1288     mBtnToolLens = device->isKeyPressed(BTN_TOOL_LENS);
1289     mBtnToolDoubleTap = device->isKeyPressed(BTN_TOOL_DOUBLETAP);
1290     mBtnToolTripleTap = device->isKeyPressed(BTN_TOOL_TRIPLETAP);
1291     mBtnToolQuadTap = device->isKeyPressed(BTN_TOOL_QUADTAP);
1292 }
1293
1294 void TouchButtonAccumulator::clearButtons() {
1295     mBtnTouch = 0;
1296     mBtnStylus = 0;
1297     mBtnStylus2 = 0;
1298     mBtnToolFinger = 0;
1299     mBtnToolPen = 0;
1300     mBtnToolRubber = 0;
1301     mBtnToolBrush = 0;
1302     mBtnToolPencil = 0;
1303     mBtnToolAirbrush = 0;
1304     mBtnToolMouse = 0;
1305     mBtnToolLens = 0;
1306     mBtnToolDoubleTap = 0;
1307     mBtnToolTripleTap = 0;
1308     mBtnToolQuadTap = 0;
1309 }
1310
1311 void TouchButtonAccumulator::process(const RawEvent* rawEvent) {
1312     if (rawEvent->type == EV_KEY) {
1313         switch (rawEvent->code) {
1314         case BTN_TOUCH:
1315         case BTN_LEFT:
1316             mBtnTouch = rawEvent->value;
1317             break;
1318         case BTN_STYLUS:
1319             mBtnStylus = rawEvent->value;
1320             break;
1321         case BTN_STYLUS2:
1322             mBtnStylus2 = rawEvent->value;
1323             break;
1324         case BTN_TOOL_FINGER:
1325             mBtnToolFinger = rawEvent->value;
1326             break;
1327         case BTN_TOOL_PEN:
1328             mBtnToolPen = rawEvent->value;
1329             break;
1330         case BTN_TOOL_RUBBER:
1331             mBtnToolRubber = rawEvent->value;
1332             break;
1333         case BTN_TOOL_BRUSH:
1334             mBtnToolBrush = rawEvent->value;
1335             break;
1336         case BTN_TOOL_PENCIL:
1337             mBtnToolPencil = rawEvent->value;
1338             break;
1339         case BTN_TOOL_AIRBRUSH:
1340             mBtnToolAirbrush = rawEvent->value;
1341             break;
1342         case BTN_TOOL_MOUSE:
1343             mBtnToolMouse = rawEvent->value;
1344             break;
1345         case BTN_TOOL_LENS:
1346             mBtnToolLens = rawEvent->value;
1347             break;
1348         case BTN_TOOL_DOUBLETAP:
1349             mBtnToolDoubleTap = rawEvent->value;
1350             break;
1351         case BTN_TOOL_TRIPLETAP:
1352             mBtnToolTripleTap = rawEvent->value;
1353             break;
1354         case BTN_TOOL_QUADTAP:
1355             mBtnToolQuadTap = rawEvent->value;
1356             break;
1357         }
1358     }
1359 }
1360
1361 uint32_t TouchButtonAccumulator::getButtonState() const {
1362     uint32_t result = 0;
1363     if (mBtnStylus) {
1364         result |= AMOTION_EVENT_BUTTON_SECONDARY;
1365     }
1366     if (mBtnStylus2) {
1367         result |= AMOTION_EVENT_BUTTON_TERTIARY;
1368     }
1369     return result;
1370 }
1371
1372 int32_t TouchButtonAccumulator::getToolType() const {
1373     if (mBtnToolMouse || mBtnToolLens) {
1374         return AMOTION_EVENT_TOOL_TYPE_MOUSE;
1375     }
1376     if (mBtnToolRubber) {
1377         return AMOTION_EVENT_TOOL_TYPE_ERASER;
1378     }
1379     if (mBtnToolPen || mBtnToolBrush || mBtnToolPencil || mBtnToolAirbrush) {
1380         return AMOTION_EVENT_TOOL_TYPE_STYLUS;
1381     }
1382     if (mBtnToolFinger || mBtnToolDoubleTap || mBtnToolTripleTap || mBtnToolQuadTap) {
1383         return AMOTION_EVENT_TOOL_TYPE_FINGER;
1384     }
1385     return AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
1386 }
1387
1388 bool TouchButtonAccumulator::isToolActive() const {
1389     return mBtnTouch || mBtnToolFinger || mBtnToolPen || mBtnToolRubber
1390             || mBtnToolBrush || mBtnToolPencil || mBtnToolAirbrush
1391             || mBtnToolMouse || mBtnToolLens
1392             || mBtnToolDoubleTap || mBtnToolTripleTap || mBtnToolQuadTap;
1393 }
1394
1395 bool TouchButtonAccumulator::isHovering() const {
1396     return mHaveBtnTouch && !mBtnTouch;
1397 }
1398
1399 bool TouchButtonAccumulator::hasStylus() const {
1400     return mHaveStylus;
1401 }
1402
1403
1404 // --- RawPointerAxes ---
1405
1406 RawPointerAxes::RawPointerAxes() {
1407     clear();
1408 }
1409
1410 void RawPointerAxes::clear() {
1411     x.clear();
1412     y.clear();
1413     pressure.clear();
1414     touchMajor.clear();
1415     touchMinor.clear();
1416     toolMajor.clear();
1417     toolMinor.clear();
1418     orientation.clear();
1419     distance.clear();
1420     tiltX.clear();
1421     tiltY.clear();
1422     trackingId.clear();
1423     slot.clear();
1424 }
1425
1426
1427 // --- RawPointerData ---
1428
1429 RawPointerData::RawPointerData() {
1430     clear();
1431 }
1432
1433 void RawPointerData::clear() {
1434     pointerCount = 0;
1435     clearIdBits();
1436 }
1437
1438 void RawPointerData::copyFrom(const RawPointerData& other) {
1439     pointerCount = other.pointerCount;
1440     hoveringIdBits = other.hoveringIdBits;
1441     touchingIdBits = other.touchingIdBits;
1442
1443     for (uint32_t i = 0; i < pointerCount; i++) {
1444         pointers[i] = other.pointers[i];
1445
1446         int id = pointers[i].id;
1447         idToIndex[id] = other.idToIndex[id];
1448     }
1449 }
1450
1451 void RawPointerData::getCentroidOfTouchingPointers(float* outX, float* outY) const {
1452     float x = 0, y = 0;
1453     uint32_t count = touchingIdBits.count();
1454     if (count) {
1455         for (BitSet32 idBits(touchingIdBits); !idBits.isEmpty(); ) {
1456             uint32_t id = idBits.clearFirstMarkedBit();
1457             const Pointer& pointer = pointerForId(id);
1458             x += pointer.x;
1459             y += pointer.y;
1460         }
1461         x /= count;
1462         y /= count;
1463     }
1464     *outX = x;
1465     *outY = y;
1466 }
1467
1468
1469 // --- CookedPointerData ---
1470
1471 CookedPointerData::CookedPointerData() {
1472     clear();
1473 }
1474
1475 void CookedPointerData::clear() {
1476     pointerCount = 0;
1477     hoveringIdBits.clear();
1478     touchingIdBits.clear();
1479 }
1480
1481 void CookedPointerData::copyFrom(const CookedPointerData& other) {
1482     pointerCount = other.pointerCount;
1483     hoveringIdBits = other.hoveringIdBits;
1484     touchingIdBits = other.touchingIdBits;
1485
1486     for (uint32_t i = 0; i < pointerCount; i++) {
1487         pointerProperties[i].copyFrom(other.pointerProperties[i]);
1488         pointerCoords[i].copyFrom(other.pointerCoords[i]);
1489
1490         int id = pointerProperties[i].id;
1491         idToIndex[id] = other.idToIndex[id];
1492     }
1493 }
1494
1495
1496 // --- SingleTouchMotionAccumulator ---
1497
1498 SingleTouchMotionAccumulator::SingleTouchMotionAccumulator() {
1499     clearAbsoluteAxes();
1500 }
1501
1502 void SingleTouchMotionAccumulator::reset(InputDevice* device) {
1503     mAbsX = device->getAbsoluteAxisValue(ABS_X);
1504     mAbsY = device->getAbsoluteAxisValue(ABS_Y);
1505     mAbsPressure = device->getAbsoluteAxisValue(ABS_PRESSURE);
1506     mAbsToolWidth = device->getAbsoluteAxisValue(ABS_TOOL_WIDTH);
1507     mAbsDistance = device->getAbsoluteAxisValue(ABS_DISTANCE);
1508     mAbsTiltX = device->getAbsoluteAxisValue(ABS_TILT_X);
1509     mAbsTiltY = device->getAbsoluteAxisValue(ABS_TILT_Y);
1510 }
1511
1512 void SingleTouchMotionAccumulator::clearAbsoluteAxes() {
1513     mAbsX = 0;
1514     mAbsY = 0;
1515     mAbsPressure = 0;
1516     mAbsToolWidth = 0;
1517     mAbsDistance = 0;
1518     mAbsTiltX = 0;
1519     mAbsTiltY = 0;
1520 }
1521
1522 void SingleTouchMotionAccumulator::process(const RawEvent* rawEvent) {
1523     if (rawEvent->type == EV_ABS) {
1524         switch (rawEvent->code) {
1525         case ABS_X:
1526             mAbsX = rawEvent->value;
1527             break;
1528         case ABS_Y:
1529             mAbsY = rawEvent->value;
1530             break;
1531         case ABS_PRESSURE:
1532             mAbsPressure = rawEvent->value;
1533             break;
1534         case ABS_TOOL_WIDTH:
1535             mAbsToolWidth = rawEvent->value;
1536             break;
1537         case ABS_DISTANCE:
1538             mAbsDistance = rawEvent->value;
1539             break;
1540         case ABS_TILT_X:
1541             mAbsTiltX = rawEvent->value;
1542             break;
1543         case ABS_TILT_Y:
1544             mAbsTiltY = rawEvent->value;
1545             break;
1546         }
1547     }
1548 }
1549
1550
1551 // --- MultiTouchMotionAccumulator ---
1552
1553 MultiTouchMotionAccumulator::MultiTouchMotionAccumulator() :
1554         mCurrentSlot(-1), mSlots(NULL), mSlotCount(0), mUsingSlotsProtocol(false),
1555         mHaveStylus(false) {
1556 }
1557
1558 MultiTouchMotionAccumulator::~MultiTouchMotionAccumulator() {
1559     delete[] mSlots;
1560 }
1561
1562 void MultiTouchMotionAccumulator::configure(InputDevice* device,
1563         size_t slotCount, bool usingSlotsProtocol) {
1564     mSlotCount = slotCount;
1565     mUsingSlotsProtocol = usingSlotsProtocol;
1566     mHaveStylus = device->hasAbsoluteAxis(ABS_MT_TOOL_TYPE);
1567
1568     delete[] mSlots;
1569     mSlots = new Slot[slotCount];
1570 }
1571
1572 void MultiTouchMotionAccumulator::reset(InputDevice* device) {
1573     // Unfortunately there is no way to read the initial contents of the slots.
1574     // So when we reset the accumulator, we must assume they are all zeroes.
1575     if (mUsingSlotsProtocol) {
1576         // Query the driver for the current slot index and use it as the initial slot
1577         // before we start reading events from the device.  It is possible that the
1578         // current slot index will not be the same as it was when the first event was
1579         // written into the evdev buffer, which means the input mapper could start
1580         // out of sync with the initial state of the events in the evdev buffer.
1581         // In the extremely unlikely case that this happens, the data from
1582         // two slots will be confused until the next ABS_MT_SLOT event is received.
1583         // This can cause the touch point to "jump", but at least there will be
1584         // no stuck touches.
1585         int32_t initialSlot;
1586         status_t status = device->getEventHub()->getAbsoluteAxisValue(device->getId(),
1587                 ABS_MT_SLOT, &initialSlot);
1588         if (status) {
1589             ALOGD("Could not retrieve current multitouch slot index.  status=%d", status);
1590             initialSlot = -1;
1591         }
1592         clearSlots(initialSlot);
1593     } else {
1594         clearSlots(-1);
1595     }
1596 }
1597
1598 void MultiTouchMotionAccumulator::clearSlots(int32_t initialSlot) {
1599     if (mSlots) {
1600         for (size_t i = 0; i < mSlotCount; i++) {
1601             mSlots[i].clear();
1602         }
1603     }
1604     mCurrentSlot = initialSlot;
1605 }
1606
1607 void MultiTouchMotionAccumulator::process(const RawEvent* rawEvent) {
1608     if (rawEvent->type == EV_ABS) {
1609         bool newSlot = false;
1610         if (mUsingSlotsProtocol) {
1611             if (rawEvent->code == ABS_MT_SLOT) {
1612                 mCurrentSlot = rawEvent->value;
1613                 newSlot = true;
1614             }
1615         } else if (mCurrentSlot < 0) {
1616             mCurrentSlot = 0;
1617         }
1618
1619         if (mCurrentSlot < 0 || size_t(mCurrentSlot) >= mSlotCount) {
1620 #if DEBUG_POINTERS
1621             if (newSlot) {
1622                 ALOGW("MultiTouch device emitted invalid slot index %d but it "
1623                         "should be between 0 and %d; ignoring this slot.",
1624                         mCurrentSlot, mSlotCount - 1);
1625             }
1626 #endif
1627         } else {
1628             Slot* slot = &mSlots[mCurrentSlot];
1629
1630             switch (rawEvent->code) {
1631             case ABS_MT_POSITION_X:
1632                 slot->mInUse = true;
1633                 slot->mAbsMTPositionX = rawEvent->value;
1634                 break;
1635             case ABS_MT_POSITION_Y:
1636                 slot->mInUse = true;
1637                 slot->mAbsMTPositionY = rawEvent->value;
1638                 break;
1639             case ABS_MT_TOUCH_MAJOR:
1640                 slot->mInUse = true;
1641                 slot->mAbsMTTouchMajor = rawEvent->value;
1642                 break;
1643             case ABS_MT_TOUCH_MINOR:
1644                 slot->mInUse = true;
1645                 slot->mAbsMTTouchMinor = rawEvent->value;
1646                 slot->mHaveAbsMTTouchMinor = true;
1647                 break;
1648             case ABS_MT_WIDTH_MAJOR:
1649                 slot->mInUse = true;
1650                 slot->mAbsMTWidthMajor = rawEvent->value;
1651                 break;
1652             case ABS_MT_WIDTH_MINOR:
1653                 slot->mInUse = true;
1654                 slot->mAbsMTWidthMinor = rawEvent->value;
1655                 slot->mHaveAbsMTWidthMinor = true;
1656                 break;
1657             case ABS_MT_ORIENTATION:
1658                 slot->mInUse = true;
1659                 slot->mAbsMTOrientation = rawEvent->value;
1660                 break;
1661             case ABS_MT_TRACKING_ID:
1662                 if (mUsingSlotsProtocol && rawEvent->value < 0) {
1663                     // The slot is no longer in use but it retains its previous contents,
1664                     // which may be reused for subsequent touches.
1665                     slot->mInUse = false;
1666                 } else {
1667                     slot->mInUse = true;
1668                     slot->mAbsMTTrackingId = rawEvent->value;
1669                 }
1670                 break;
1671             case ABS_MT_PRESSURE:
1672                 slot->mInUse = true;
1673                 slot->mAbsMTPressure = rawEvent->value;
1674                 break;
1675             case ABS_MT_DISTANCE:
1676                 slot->mInUse = true;
1677                 slot->mAbsMTDistance = rawEvent->value;
1678                 break;
1679             case ABS_MT_TOOL_TYPE:
1680                 slot->mInUse = true;
1681                 slot->mAbsMTToolType = rawEvent->value;
1682                 slot->mHaveAbsMTToolType = true;
1683                 break;
1684             }
1685         }
1686     } else if (rawEvent->type == EV_SYN && rawEvent->code == SYN_MT_REPORT) {
1687         // MultiTouch Sync: The driver has returned all data for *one* of the pointers.
1688         mCurrentSlot += 1;
1689     }
1690 }
1691
1692 void MultiTouchMotionAccumulator::finishSync() {
1693     if (!mUsingSlotsProtocol) {
1694         clearSlots(-1);
1695     }
1696 }
1697
1698 bool MultiTouchMotionAccumulator::hasStylus() const {
1699     return mHaveStylus;
1700 }
1701
1702
1703 // --- MultiTouchMotionAccumulator::Slot ---
1704
1705 MultiTouchMotionAccumulator::Slot::Slot() {
1706     clear();
1707 }
1708
1709 void MultiTouchMotionAccumulator::Slot::clear() {
1710     mInUse = false;
1711     mHaveAbsMTTouchMinor = false;
1712     mHaveAbsMTWidthMinor = false;
1713     mHaveAbsMTToolType = false;
1714     mAbsMTPositionX = 0;
1715     mAbsMTPositionY = 0;
1716     mAbsMTTouchMajor = 0;
1717     mAbsMTTouchMinor = 0;
1718     mAbsMTWidthMajor = 0;
1719     mAbsMTWidthMinor = 0;
1720     mAbsMTOrientation = 0;
1721     mAbsMTTrackingId = -1;
1722     mAbsMTPressure = 0;
1723     mAbsMTDistance = 0;
1724     mAbsMTToolType = 0;
1725 }
1726
1727 int32_t MultiTouchMotionAccumulator::Slot::getToolType() const {
1728     if (mHaveAbsMTToolType) {
1729         switch (mAbsMTToolType) {
1730         case MT_TOOL_FINGER:
1731             return AMOTION_EVENT_TOOL_TYPE_FINGER;
1732         case MT_TOOL_PEN:
1733             return AMOTION_EVENT_TOOL_TYPE_STYLUS;
1734         }
1735     }
1736     return AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
1737 }
1738
1739
1740 // --- InputMapper ---
1741
1742 InputMapper::InputMapper(InputDevice* device) :
1743         mDevice(device), mContext(device->getContext()) {
1744 }
1745
1746 InputMapper::~InputMapper() {
1747 }
1748
1749 void InputMapper::populateDeviceInfo(InputDeviceInfo* info) {
1750     info->addSource(getSources());
1751 }
1752
1753 void InputMapper::dump(String8& dump) {
1754 }
1755
1756 void InputMapper::configure(nsecs_t when,
1757         const InputReaderConfiguration* config, uint32_t changes) {
1758 }
1759
1760 void InputMapper::reset(nsecs_t when) {
1761 }
1762
1763 void InputMapper::timeoutExpired(nsecs_t when) {
1764 }
1765
1766 int32_t InputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
1767     return AKEY_STATE_UNKNOWN;
1768 }
1769
1770 int32_t InputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
1771     return AKEY_STATE_UNKNOWN;
1772 }
1773
1774 int32_t InputMapper::getSwitchState(uint32_t sourceMask, int32_t switchCode) {
1775     return AKEY_STATE_UNKNOWN;
1776 }
1777
1778 bool InputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
1779         const int32_t* keyCodes, uint8_t* outFlags) {
1780     return false;
1781 }
1782
1783 void InputMapper::vibrate(const nsecs_t* pattern, size_t patternSize, ssize_t repeat,
1784         int32_t token) {
1785 }
1786
1787 void InputMapper::cancelVibrate(int32_t token) {
1788 }
1789
1790 int32_t InputMapper::getMetaState() {
1791     return 0;
1792 }
1793
1794 void InputMapper::fadePointer() {
1795 }
1796
1797 status_t InputMapper::getAbsoluteAxisInfo(int32_t axis, RawAbsoluteAxisInfo* axisInfo) {
1798     return getEventHub()->getAbsoluteAxisInfo(getDeviceId(), axis, axisInfo);
1799 }
1800
1801 void InputMapper::bumpGeneration() {
1802     mDevice->bumpGeneration();
1803 }
1804
1805 void InputMapper::dumpRawAbsoluteAxisInfo(String8& dump,
1806         const RawAbsoluteAxisInfo& axis, const char* name) {
1807     if (axis.valid) {
1808         dump.appendFormat(INDENT4 "%s: min=%d, max=%d, flat=%d, fuzz=%d, resolution=%d\n",
1809                 name, axis.minValue, axis.maxValue, axis.flat, axis.fuzz, axis.resolution);
1810     } else {
1811         dump.appendFormat(INDENT4 "%s: unknown range\n", name);
1812     }
1813 }
1814
1815
1816 // --- SwitchInputMapper ---
1817
1818 SwitchInputMapper::SwitchInputMapper(InputDevice* device) :
1819         InputMapper(device), mSwitchValues(0), mUpdatedSwitchMask(0) {
1820 }
1821
1822 SwitchInputMapper::~SwitchInputMapper() {
1823 }
1824
1825 uint32_t SwitchInputMapper::getSources() {
1826     return AINPUT_SOURCE_SWITCH;
1827 }
1828
1829 void SwitchInputMapper::process(const RawEvent* rawEvent) {
1830     switch (rawEvent->type) {
1831     case EV_SW:
1832         processSwitch(rawEvent->code, rawEvent->value);
1833         break;
1834
1835     case EV_SYN:
1836         if (rawEvent->code == SYN_REPORT) {
1837             sync(rawEvent->when);
1838         }
1839     }
1840 }
1841
1842 void SwitchInputMapper::processSwitch(int32_t switchCode, int32_t switchValue) {
1843     if (switchCode >= 0 && switchCode < 32) {
1844         if (switchValue) {
1845             mSwitchValues |= 1 << switchCode;
1846         } else {
1847             mSwitchValues &= ~(1 << switchCode);
1848         }
1849         mUpdatedSwitchMask |= 1 << switchCode;
1850     }
1851 }
1852
1853 void SwitchInputMapper::sync(nsecs_t when) {
1854     if (mUpdatedSwitchMask) {
1855         uint32_t updatedSwitchValues = mSwitchValues & mUpdatedSwitchMask;
1856         NotifySwitchArgs args(when, 0, updatedSwitchValues, mUpdatedSwitchMask);
1857         getListener()->notifySwitch(&args);
1858
1859         mUpdatedSwitchMask = 0;
1860     }
1861 }
1862
1863 int32_t SwitchInputMapper::getSwitchState(uint32_t sourceMask, int32_t switchCode) {
1864     return getEventHub()->getSwitchState(getDeviceId(), switchCode);
1865 }
1866
1867 void SwitchInputMapper::dump(String8& dump) {
1868     dump.append(INDENT2 "Switch Input Mapper:\n");
1869     dump.appendFormat(INDENT3 "SwitchValues: %x\n", mSwitchValues);
1870 }
1871
1872 // --- VibratorInputMapper ---
1873
1874 VibratorInputMapper::VibratorInputMapper(InputDevice* device) :
1875         InputMapper(device), mVibrating(false) {
1876 }
1877
1878 VibratorInputMapper::~VibratorInputMapper() {
1879 }
1880
1881 uint32_t VibratorInputMapper::getSources() {
1882     return 0;
1883 }
1884
1885 void VibratorInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
1886     InputMapper::populateDeviceInfo(info);
1887
1888     info->setVibrator(true);
1889 }
1890
1891 void VibratorInputMapper::process(const RawEvent* rawEvent) {
1892     // TODO: Handle FF_STATUS, although it does not seem to be widely supported.
1893 }
1894
1895 void VibratorInputMapper::vibrate(const nsecs_t* pattern, size_t patternSize, ssize_t repeat,
1896         int32_t token) {
1897 #if DEBUG_VIBRATOR
1898     String8 patternStr;
1899     for (size_t i = 0; i < patternSize; i++) {
1900         if (i != 0) {
1901             patternStr.append(", ");
1902         }
1903         patternStr.appendFormat("%lld", pattern[i]);
1904     }
1905     ALOGD("vibrate: deviceId=%d, pattern=[%s], repeat=%ld, token=%d",
1906             getDeviceId(), patternStr.string(), repeat, token);
1907 #endif
1908
1909     mVibrating = true;
1910     memcpy(mPattern, pattern, patternSize * sizeof(nsecs_t));
1911     mPatternSize = patternSize;
1912     mRepeat = repeat;
1913     mToken = token;
1914     mIndex = -1;
1915
1916     nextStep();
1917 }
1918
1919 void VibratorInputMapper::cancelVibrate(int32_t token) {
1920 #if DEBUG_VIBRATOR
1921     ALOGD("cancelVibrate: deviceId=%d, token=%d", getDeviceId(), token);
1922 #endif
1923
1924     if (mVibrating && mToken == token) {
1925         stopVibrating();
1926     }
1927 }
1928
1929 void VibratorInputMapper::timeoutExpired(nsecs_t when) {
1930     if (mVibrating) {
1931         if (when >= mNextStepTime) {
1932             nextStep();
1933         } else {
1934             getContext()->requestTimeoutAtTime(mNextStepTime);
1935         }
1936     }
1937 }
1938
1939 void VibratorInputMapper::nextStep() {
1940     mIndex += 1;
1941     if (size_t(mIndex) >= mPatternSize) {
1942         if (mRepeat < 0) {
1943             // We are done.
1944             stopVibrating();
1945             return;
1946         }
1947         mIndex = mRepeat;
1948     }
1949
1950     bool vibratorOn = mIndex & 1;
1951     nsecs_t duration = mPattern[mIndex];
1952     if (vibratorOn) {
1953 #if DEBUG_VIBRATOR
1954         ALOGD("nextStep: sending vibrate deviceId=%d, duration=%lld",
1955                 getDeviceId(), duration);
1956 #endif
1957         getEventHub()->vibrate(getDeviceId(), duration);
1958     } else {
1959 #if DEBUG_VIBRATOR
1960         ALOGD("nextStep: sending cancel vibrate deviceId=%d", getDeviceId());
1961 #endif
1962         getEventHub()->cancelVibrate(getDeviceId());
1963     }
1964     nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
1965     mNextStepTime = now + duration;
1966     getContext()->requestTimeoutAtTime(mNextStepTime);
1967 #if DEBUG_VIBRATOR
1968     ALOGD("nextStep: scheduled timeout in %0.3fms", duration * 0.000001f);
1969 #endif
1970 }
1971
1972 void VibratorInputMapper::stopVibrating() {
1973     mVibrating = false;
1974 #if DEBUG_VIBRATOR
1975     ALOGD("stopVibrating: sending cancel vibrate deviceId=%d", getDeviceId());
1976 #endif
1977     getEventHub()->cancelVibrate(getDeviceId());
1978 }
1979
1980 void VibratorInputMapper::dump(String8& dump) {
1981     dump.append(INDENT2 "Vibrator Input Mapper:\n");
1982     dump.appendFormat(INDENT3 "Vibrating: %s\n", toString(mVibrating));
1983 }
1984
1985
1986 // --- KeyboardInputMapper ---
1987
1988 KeyboardInputMapper::KeyboardInputMapper(InputDevice* device,
1989         uint32_t source, int32_t keyboardType) :
1990         InputMapper(device), mSource(source),
1991         mKeyboardType(keyboardType) {
1992 }
1993
1994 KeyboardInputMapper::~KeyboardInputMapper() {
1995 }
1996
1997 uint32_t KeyboardInputMapper::getSources() {
1998     return mSource;
1999 }
2000
2001 void KeyboardInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
2002     InputMapper::populateDeviceInfo(info);
2003
2004     info->setKeyboardType(mKeyboardType);
2005     info->setKeyCharacterMap(getEventHub()->getKeyCharacterMap(getDeviceId()));
2006 }
2007
2008 void KeyboardInputMapper::dump(String8& dump) {
2009     dump.append(INDENT2 "Keyboard Input Mapper:\n");
2010     dumpParameters(dump);
2011     dump.appendFormat(INDENT3 "KeyboardType: %d\n", mKeyboardType);
2012     dump.appendFormat(INDENT3 "Orientation: %d\n", mOrientation);
2013     dump.appendFormat(INDENT3 "KeyDowns: %zu keys currently down\n", mKeyDowns.size());
2014     dump.appendFormat(INDENT3 "MetaState: 0x%0x\n", mMetaState);
2015     dump.appendFormat(INDENT3 "DownTime: %lld\n", (long long)mDownTime);
2016 }
2017
2018
2019 void KeyboardInputMapper::configure(nsecs_t when,
2020         const InputReaderConfiguration* config, uint32_t changes) {
2021     InputMapper::configure(when, config, changes);
2022
2023     if (!changes) { // first time only
2024         // Configure basic parameters.
2025         configureParameters();
2026     }
2027
2028     if (!changes || (changes & InputReaderConfiguration::CHANGE_DISPLAY_INFO)) {
2029         if (mParameters.orientationAware && mParameters.hasAssociatedDisplay) {
2030             DisplayViewport v;
2031             if (config->getDisplayInfo(false /*external*/, &v)) {
2032                 mOrientation = v.orientation;
2033             } else {
2034                 mOrientation = DISPLAY_ORIENTATION_0;
2035             }
2036         } else {
2037             mOrientation = DISPLAY_ORIENTATION_0;
2038         }
2039     }
2040 }
2041
2042 void KeyboardInputMapper::configureParameters() {
2043     mParameters.orientationAware = false;
2044     getDevice()->getConfiguration().tryGetProperty(String8("keyboard.orientationAware"),
2045             mParameters.orientationAware);
2046
2047     mParameters.hasAssociatedDisplay = false;
2048     if (mParameters.orientationAware) {
2049         mParameters.hasAssociatedDisplay = true;
2050     }
2051
2052     mParameters.handlesKeyRepeat = false;
2053     getDevice()->getConfiguration().tryGetProperty(String8("keyboard.handlesKeyRepeat"),
2054             mParameters.handlesKeyRepeat);
2055 }
2056
2057 void KeyboardInputMapper::dumpParameters(String8& dump) {
2058     dump.append(INDENT3 "Parameters:\n");
2059     dump.appendFormat(INDENT4 "HasAssociatedDisplay: %s\n",
2060             toString(mParameters.hasAssociatedDisplay));
2061     dump.appendFormat(INDENT4 "OrientationAware: %s\n",
2062             toString(mParameters.orientationAware));
2063     dump.appendFormat(INDENT4 "HandlesKeyRepeat: %s\n",
2064             toString(mParameters.handlesKeyRepeat));
2065 }
2066
2067 void KeyboardInputMapper::reset(nsecs_t when) {
2068     mMetaState = AMETA_NONE;
2069     mDownTime = 0;
2070     mKeyDowns.clear();
2071     mCurrentHidUsage = 0;
2072
2073     resetLedState();
2074
2075     InputMapper::reset(when);
2076 }
2077
2078 void KeyboardInputMapper::process(const RawEvent* rawEvent) {
2079     switch (rawEvent->type) {
2080     case EV_KEY: {
2081         int32_t scanCode = rawEvent->code;
2082         int32_t usageCode = mCurrentHidUsage;
2083         mCurrentHidUsage = 0;
2084
2085         if (isKeyboardOrGamepadKey(scanCode)) {
2086             int32_t keyCode;
2087             uint32_t flags;
2088             if (getEventHub()->mapKey(getDeviceId(), scanCode, usageCode, &keyCode, &flags)) {
2089                 keyCode = AKEYCODE_UNKNOWN;
2090                 flags = 0;
2091             }
2092             processKey(rawEvent->when, rawEvent->value != 0, keyCode, scanCode, flags);
2093         }
2094         break;
2095     }
2096     case EV_MSC: {
2097         if (rawEvent->code == MSC_SCAN) {
2098             mCurrentHidUsage = rawEvent->value;
2099         }
2100         break;
2101     }
2102     case EV_SYN: {
2103         if (rawEvent->code == SYN_REPORT) {
2104             mCurrentHidUsage = 0;
2105         }
2106     }
2107     }
2108 }
2109
2110 bool KeyboardInputMapper::isKeyboardOrGamepadKey(int32_t scanCode) {
2111     return scanCode < BTN_MOUSE
2112         || scanCode >= KEY_OK
2113         || (scanCode >= BTN_MISC && scanCode < BTN_MOUSE)
2114         || (scanCode >= BTN_JOYSTICK && scanCode < BTN_DIGI);
2115 }
2116
2117 void KeyboardInputMapper::processKey(nsecs_t when, bool down, int32_t keyCode,
2118         int32_t scanCode, uint32_t policyFlags) {
2119
2120     if (down) {
2121         // Rotate key codes according to orientation if needed.
2122         if (mParameters.orientationAware && mParameters.hasAssociatedDisplay) {
2123             keyCode = rotateKeyCode(keyCode, mOrientation);
2124         }
2125
2126         // Add key down.
2127         ssize_t keyDownIndex = findKeyDown(scanCode);
2128         if (keyDownIndex >= 0) {
2129             // key repeat, be sure to use same keycode as before in case of rotation
2130             keyCode = mKeyDowns.itemAt(keyDownIndex).keyCode;
2131         } else {
2132             // key down
2133             if ((policyFlags & POLICY_FLAG_VIRTUAL)
2134                     && mContext->shouldDropVirtualKey(when,
2135                             getDevice(), keyCode, scanCode)) {
2136                 return;
2137             }
2138
2139             mKeyDowns.push();
2140             KeyDown& keyDown = mKeyDowns.editTop();
2141             keyDown.keyCode = keyCode;
2142             keyDown.scanCode = scanCode;
2143         }
2144
2145         mDownTime = when;
2146     } else {
2147         // Remove key down.
2148         ssize_t keyDownIndex = findKeyDown(scanCode);
2149         if (keyDownIndex >= 0) {
2150             // key up, be sure to use same keycode as before in case of rotation
2151             keyCode = mKeyDowns.itemAt(keyDownIndex).keyCode;
2152             mKeyDowns.removeAt(size_t(keyDownIndex));
2153         } else {
2154             // key was not actually down
2155             ALOGI("Dropping key up from device %s because the key was not down.  "
2156                     "keyCode=%d, scanCode=%d",
2157                     getDeviceName().string(), keyCode, scanCode);
2158             return;
2159         }
2160     }
2161
2162     int32_t oldMetaState = mMetaState;
2163     int32_t newMetaState = updateMetaState(keyCode, down, oldMetaState);
2164     bool metaStateChanged = oldMetaState != newMetaState;
2165     if (metaStateChanged) {
2166         mMetaState = newMetaState;
2167         updateLedState(false);
2168     }
2169
2170     nsecs_t downTime = mDownTime;
2171
2172     // Key down on external an keyboard should wake the device.
2173     // We don't do this for internal keyboards to prevent them from waking up in your pocket.
2174     // For internal keyboards, the key layout file should specify the policy flags for
2175     // each wake key individually.
2176     // TODO: Use the input device configuration to control this behavior more finely.
2177     if (down && getDevice()->isExternal()) {
2178         policyFlags |= POLICY_FLAG_WAKE;
2179     }
2180
2181     if (mParameters.handlesKeyRepeat) {
2182         policyFlags |= POLICY_FLAG_DISABLE_KEY_REPEAT;
2183     }
2184
2185     if (metaStateChanged) {
2186         getContext()->updateGlobalMetaState();
2187     }
2188
2189     if (down && !isMetaKey(keyCode)) {
2190         getContext()->fadePointer();
2191     }
2192
2193     NotifyKeyArgs args(when, getDeviceId(), mSource, policyFlags,
2194             down ? AKEY_EVENT_ACTION_DOWN : AKEY_EVENT_ACTION_UP,
2195             AKEY_EVENT_FLAG_FROM_SYSTEM, keyCode, scanCode, newMetaState, downTime);
2196     getListener()->notifyKey(&args);
2197 }
2198
2199 ssize_t KeyboardInputMapper::findKeyDown(int32_t scanCode) {
2200     size_t n = mKeyDowns.size();
2201     for (size_t i = 0; i < n; i++) {
2202         if (mKeyDowns[i].scanCode == scanCode) {
2203             return i;
2204         }
2205     }
2206     return -1;
2207 }
2208
2209 int32_t KeyboardInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
2210     return getEventHub()->getKeyCodeState(getDeviceId(), keyCode);
2211 }
2212
2213 int32_t KeyboardInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
2214     return getEventHub()->getScanCodeState(getDeviceId(), scanCode);
2215 }
2216
2217 bool KeyboardInputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
2218         const int32_t* keyCodes, uint8_t* outFlags) {
2219     return getEventHub()->markSupportedKeyCodes(getDeviceId(), numCodes, keyCodes, outFlags);
2220 }
2221
2222 int32_t KeyboardInputMapper::getMetaState() {
2223     return mMetaState;
2224 }
2225
2226 void KeyboardInputMapper::resetLedState() {
2227     initializeLedState(mCapsLockLedState, ALED_CAPS_LOCK);
2228     initializeLedState(mNumLockLedState, ALED_NUM_LOCK);
2229     initializeLedState(mScrollLockLedState, ALED_SCROLL_LOCK);
2230
2231     updateLedState(true);
2232 }
2233
2234 void KeyboardInputMapper::initializeLedState(LedState& ledState, int32_t led) {
2235     ledState.avail = getEventHub()->hasLed(getDeviceId(), led);
2236     ledState.on = false;
2237 }
2238
2239 void KeyboardInputMapper::updateLedState(bool reset) {
2240     updateLedStateForModifier(mCapsLockLedState, ALED_CAPS_LOCK,
2241             AMETA_CAPS_LOCK_ON, reset);
2242     updateLedStateForModifier(mNumLockLedState, ALED_NUM_LOCK,
2243             AMETA_NUM_LOCK_ON, reset);
2244     updateLedStateForModifier(mScrollLockLedState, ALED_SCROLL_LOCK,
2245             AMETA_SCROLL_LOCK_ON, reset);
2246 }
2247
2248 void KeyboardInputMapper::updateLedStateForModifier(LedState& ledState,
2249         int32_t led, int32_t modifier, bool reset) {
2250     if (ledState.avail) {
2251         bool desiredState = (mMetaState & modifier) != 0;
2252         if (reset || ledState.on != desiredState) {
2253             getEventHub()->setLedState(getDeviceId(), led, desiredState);
2254             ledState.on = desiredState;
2255         }
2256     }
2257 }
2258
2259
2260 // --- CursorInputMapper ---
2261
2262 CursorInputMapper::CursorInputMapper(InputDevice* device) :
2263         InputMapper(device) {
2264 }
2265
2266 CursorInputMapper::~CursorInputMapper() {
2267 }
2268
2269 uint32_t CursorInputMapper::getSources() {
2270     return mSource;
2271 }
2272
2273 void CursorInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
2274     InputMapper::populateDeviceInfo(info);
2275
2276     if (mParameters.mode == Parameters::MODE_POINTER) {
2277         float minX, minY, maxX, maxY;
2278         if (mPointerController->getBounds(&minX, &minY, &maxX, &maxY)) {
2279             info->addMotionRange(AMOTION_EVENT_AXIS_X, mSource, minX, maxX, 0.0f, 0.0f, 0.0f);
2280             info->addMotionRange(AMOTION_EVENT_AXIS_Y, mSource, minY, maxY, 0.0f, 0.0f, 0.0f);
2281         }
2282     } else {
2283         info->addMotionRange(AMOTION_EVENT_AXIS_X, mSource, -1.0f, 1.0f, 0.0f, mXScale, 0.0f);
2284         info->addMotionRange(AMOTION_EVENT_AXIS_Y, mSource, -1.0f, 1.0f, 0.0f, mYScale, 0.0f);
2285     }
2286     info->addMotionRange(AMOTION_EVENT_AXIS_PRESSURE, mSource, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f);
2287
2288     if (mCursorScrollAccumulator.haveRelativeVWheel()) {
2289         info->addMotionRange(AMOTION_EVENT_AXIS_VSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f);
2290     }
2291     if (mCursorScrollAccumulator.haveRelativeHWheel()) {
2292         info->addMotionRange(AMOTION_EVENT_AXIS_HSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f);
2293     }
2294 }
2295
2296 void CursorInputMapper::dump(String8& dump) {
2297     dump.append(INDENT2 "Cursor Input Mapper:\n");
2298     dumpParameters(dump);
2299     dump.appendFormat(INDENT3 "XScale: %0.3f\n", mXScale);
2300     dump.appendFormat(INDENT3 "YScale: %0.3f\n", mYScale);
2301     dump.appendFormat(INDENT3 "XPrecision: %0.3f\n", mXPrecision);
2302     dump.appendFormat(INDENT3 "YPrecision: %0.3f\n", mYPrecision);
2303     dump.appendFormat(INDENT3 "HaveVWheel: %s\n",
2304             toString(mCursorScrollAccumulator.haveRelativeVWheel()));
2305     dump.appendFormat(INDENT3 "HaveHWheel: %s\n",
2306             toString(mCursorScrollAccumulator.haveRelativeHWheel()));
2307     dump.appendFormat(INDENT3 "VWheelScale: %0.3f\n", mVWheelScale);
2308     dump.appendFormat(INDENT3 "HWheelScale: %0.3f\n", mHWheelScale);
2309     dump.appendFormat(INDENT3 "Orientation: %d\n", mOrientation);
2310     dump.appendFormat(INDENT3 "ButtonState: 0x%08x\n", mButtonState);
2311     dump.appendFormat(INDENT3 "Down: %s\n", toString(isPointerDown(mButtonState)));
2312     dump.appendFormat(INDENT3 "DownTime: %lld\n", (long long)mDownTime);
2313 }
2314
2315 void CursorInputMapper::configure(nsecs_t when,
2316         const InputReaderConfiguration* config, uint32_t changes) {
2317     InputMapper::configure(when, config, changes);
2318
2319     if (!changes) { // first time only
2320         mCursorScrollAccumulator.configure(getDevice());
2321
2322         // Configure basic parameters.
2323         configureParameters();
2324
2325         // Configure device mode.
2326         switch (mParameters.mode) {
2327         case Parameters::MODE_POINTER:
2328             mSource = AINPUT_SOURCE_MOUSE;
2329             mXPrecision = 1.0f;
2330             mYPrecision = 1.0f;
2331             mXScale = 1.0f;
2332             mYScale = 1.0f;
2333             mPointerController = getPolicy()->obtainPointerController(getDeviceId());
2334             break;
2335         case Parameters::MODE_NAVIGATION:
2336             mSource = AINPUT_SOURCE_TRACKBALL;
2337             mXPrecision = TRACKBALL_MOVEMENT_THRESHOLD;
2338             mYPrecision = TRACKBALL_MOVEMENT_THRESHOLD;
2339             mXScale = 1.0f / TRACKBALL_MOVEMENT_THRESHOLD;
2340             mYScale = 1.0f / TRACKBALL_MOVEMENT_THRESHOLD;
2341             break;
2342         }
2343
2344         mVWheelScale = 1.0f;
2345         mHWheelScale = 1.0f;
2346     }
2347
2348     if (!changes || (changes & InputReaderConfiguration::CHANGE_POINTER_SPEED)) {
2349         mPointerVelocityControl.setParameters(config->pointerVelocityControlParameters);
2350         mWheelXVelocityControl.setParameters(config->wheelVelocityControlParameters);
2351         mWheelYVelocityControl.setParameters(config->wheelVelocityControlParameters);
2352     }
2353
2354     if (!changes || (changes & InputReaderConfiguration::CHANGE_DISPLAY_INFO)) {
2355         if (mParameters.orientationAware && mParameters.hasAssociatedDisplay) {
2356             DisplayViewport v;
2357             if (config->getDisplayInfo(false /*external*/, &v)) {
2358                 mOrientation = v.orientation;
2359             } else {
2360                 mOrientation = DISPLAY_ORIENTATION_0;
2361             }
2362         } else {
2363             mOrientation = DISPLAY_ORIENTATION_0;
2364         }
2365         bumpGeneration();
2366     }
2367 }
2368
2369 void CursorInputMapper::configureParameters() {
2370     mParameters.mode = Parameters::MODE_POINTER;
2371     String8 cursorModeString;
2372     if (getDevice()->getConfiguration().tryGetProperty(String8("cursor.mode"), cursorModeString)) {
2373         if (cursorModeString == "navigation") {
2374             mParameters.mode = Parameters::MODE_NAVIGATION;
2375         } else if (cursorModeString != "pointer" && cursorModeString != "default") {
2376             ALOGW("Invalid value for cursor.mode: '%s'", cursorModeString.string());
2377         }
2378     }
2379
2380     mParameters.orientationAware = false;
2381     getDevice()->getConfiguration().tryGetProperty(String8("cursor.orientationAware"),
2382             mParameters.orientationAware);
2383
2384     mParameters.hasAssociatedDisplay = false;
2385     if (mParameters.mode == Parameters::MODE_POINTER || mParameters.orientationAware) {
2386         mParameters.hasAssociatedDisplay = true;
2387     }
2388 }
2389
2390 void CursorInputMapper::dumpParameters(String8& dump) {
2391     dump.append(INDENT3 "Parameters:\n");
2392     dump.appendFormat(INDENT4 "HasAssociatedDisplay: %s\n",
2393             toString(mParameters.hasAssociatedDisplay));
2394
2395     switch (mParameters.mode) {
2396     case Parameters::MODE_POINTER:
2397         dump.append(INDENT4 "Mode: pointer\n");
2398         break;
2399     case Parameters::MODE_NAVIGATION:
2400         dump.append(INDENT4 "Mode: navigation\n");
2401         break;
2402     default:
2403         ALOG_ASSERT(false);
2404     }
2405
2406     dump.appendFormat(INDENT4 "OrientationAware: %s\n",
2407             toString(mParameters.orientationAware));
2408 }
2409
2410 void CursorInputMapper::reset(nsecs_t when) {
2411     mButtonState = 0;
2412     mDownTime = 0;
2413
2414     mPointerVelocityControl.reset();
2415     mWheelXVelocityControl.reset();
2416     mWheelYVelocityControl.reset();
2417
2418     mCursorButtonAccumulator.reset(getDevice());
2419     mCursorMotionAccumulator.reset(getDevice());
2420     mCursorScrollAccumulator.reset(getDevice());
2421
2422     InputMapper::reset(when);
2423 }
2424
2425 void CursorInputMapper::process(const RawEvent* rawEvent) {
2426     mCursorButtonAccumulator.process(rawEvent);
2427     mCursorMotionAccumulator.process(rawEvent);
2428     mCursorScrollAccumulator.process(rawEvent);
2429
2430     if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
2431         sync(rawEvent->when);
2432     }
2433 }
2434
2435 void CursorInputMapper::sync(nsecs_t when) {
2436     int32_t lastButtonState = mButtonState;
2437     int32_t currentButtonState = mCursorButtonAccumulator.getButtonState();
2438     mButtonState = currentButtonState;
2439
2440     bool wasDown = isPointerDown(lastButtonState);
2441     bool down = isPointerDown(currentButtonState);
2442     bool downChanged;
2443     if (!wasDown && down) {
2444         mDownTime = when;
2445         downChanged = true;
2446     } else if (wasDown && !down) {
2447         downChanged = true;
2448     } else {
2449         downChanged = false;
2450     }
2451     nsecs_t downTime = mDownTime;
2452     bool buttonsChanged = currentButtonState != lastButtonState;
2453     bool buttonsPressed = currentButtonState & ~lastButtonState;
2454
2455     float deltaX = mCursorMotionAccumulator.getRelativeX() * mXScale;
2456     float deltaY = mCursorMotionAccumulator.getRelativeY() * mYScale;
2457     bool moved = deltaX != 0 || deltaY != 0;
2458
2459     // Rotate delta according to orientation if needed.
2460     if (mParameters.orientationAware && mParameters.hasAssociatedDisplay
2461             && (deltaX != 0.0f || deltaY != 0.0f)) {
2462         rotateDelta(mOrientation, &deltaX, &deltaY);
2463     }
2464
2465     // Move the pointer.
2466     PointerProperties pointerProperties;
2467     pointerProperties.clear();
2468     pointerProperties.id = 0;
2469     pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_MOUSE;
2470
2471     PointerCoords pointerCoords;
2472     pointerCoords.clear();
2473
2474     float vscroll = mCursorScrollAccumulator.getRelativeVWheel();
2475     float hscroll = mCursorScrollAccumulator.getRelativeHWheel();
2476     bool scrolled = vscroll != 0 || hscroll != 0;
2477
2478     mWheelYVelocityControl.move(when, NULL, &vscroll);
2479     mWheelXVelocityControl.move(when, &hscroll, NULL);
2480
2481     mPointerVelocityControl.move(when, &deltaX, &deltaY);
2482
2483     int32_t displayId;
2484     if (mPointerController != NULL) {
2485         if (moved || scrolled || buttonsChanged) {
2486             mPointerController->setPresentation(
2487                     PointerControllerInterface::PRESENTATION_POINTER);
2488
2489             if (moved) {
2490                 mPointerController->move(deltaX, deltaY);
2491             }
2492
2493             if (buttonsChanged) {
2494                 mPointerController->setButtonState(currentButtonState);
2495             }
2496
2497             mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
2498         }
2499
2500         float x, y;
2501         mPointerController->getPosition(&x, &y);
2502         pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
2503         pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2504         displayId = ADISPLAY_ID_DEFAULT;
2505     } else {
2506         pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, deltaX);
2507         pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, deltaY);
2508         displayId = ADISPLAY_ID_NONE;
2509     }
2510
2511     pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, down ? 1.0f : 0.0f);
2512
2513     // Moving an external trackball or mouse should wake the device.
2514     // We don't do this for internal cursor devices to prevent them from waking up
2515     // the device in your pocket.
2516     // TODO: Use the input device configuration to control this behavior more finely.
2517     uint32_t policyFlags = 0;
2518     if ((buttonsPressed || moved || scrolled) && getDevice()->isExternal()) {
2519         policyFlags |= POLICY_FLAG_WAKE;
2520     }
2521
2522     // Synthesize key down from buttons if needed.
2523     synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, getDeviceId(), mSource,
2524             policyFlags, lastButtonState, currentButtonState);
2525
2526     // Send motion event.
2527     if (downChanged || moved || scrolled || buttonsChanged) {
2528         int32_t metaState = mContext->getGlobalMetaState();
2529         int32_t motionEventAction;
2530         if (downChanged) {
2531             motionEventAction = down ? AMOTION_EVENT_ACTION_DOWN : AMOTION_EVENT_ACTION_UP;
2532         } else if (down || mPointerController == NULL) {
2533             motionEventAction = AMOTION_EVENT_ACTION_MOVE;
2534         } else {
2535             motionEventAction = AMOTION_EVENT_ACTION_HOVER_MOVE;
2536         }
2537
2538         NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
2539                 motionEventAction, 0, metaState, currentButtonState, 0,
2540                 displayId, 1, &pointerProperties, &pointerCoords,
2541                 mXPrecision, mYPrecision, downTime);
2542         getListener()->notifyMotion(&args);
2543
2544         // Send hover move after UP to tell the application that the mouse is hovering now.
2545         if (motionEventAction == AMOTION_EVENT_ACTION_UP
2546                 && mPointerController != NULL) {
2547             NotifyMotionArgs hoverArgs(when, getDeviceId(), mSource, policyFlags,
2548                     AMOTION_EVENT_ACTION_HOVER_MOVE, 0,
2549                     metaState, currentButtonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2550                     displayId, 1, &pointerProperties, &pointerCoords,
2551                     mXPrecision, mYPrecision, downTime);
2552             getListener()->notifyMotion(&hoverArgs);
2553         }
2554
2555         // Send scroll events.
2556         if (scrolled) {
2557             pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
2558             pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
2559
2560             NotifyMotionArgs scrollArgs(when, getDeviceId(), mSource, policyFlags,
2561                     AMOTION_EVENT_ACTION_SCROLL, 0, metaState, currentButtonState,
2562                     AMOTION_EVENT_EDGE_FLAG_NONE,
2563                     displayId, 1, &pointerProperties, &pointerCoords,
2564                     mXPrecision, mYPrecision, downTime);
2565             getListener()->notifyMotion(&scrollArgs);
2566         }
2567     }
2568
2569     // Synthesize key up from buttons if needed.
2570     synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, getDeviceId(), mSource,
2571             policyFlags, lastButtonState, currentButtonState);
2572
2573     mCursorMotionAccumulator.finishSync();
2574     mCursorScrollAccumulator.finishSync();
2575 }
2576
2577 int32_t CursorInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
2578     if (scanCode >= BTN_MOUSE && scanCode < BTN_JOYSTICK) {
2579         return getEventHub()->getScanCodeState(getDeviceId(), scanCode);
2580     } else {
2581         return AKEY_STATE_UNKNOWN;
2582     }
2583 }
2584
2585 void CursorInputMapper::fadePointer() {
2586     if (mPointerController != NULL) {
2587         mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
2588     }
2589 }
2590
2591
2592 // --- TouchInputMapper ---
2593
2594 TouchInputMapper::TouchInputMapper(InputDevice* device) :
2595         InputMapper(device),
2596         mSource(0), mDeviceMode(DEVICE_MODE_DISABLED),
2597         mSurfaceWidth(-1), mSurfaceHeight(-1), mSurfaceLeft(0), mSurfaceTop(0),
2598         mSurfaceOrientation(DISPLAY_ORIENTATION_0) {
2599 }
2600
2601 TouchInputMapper::~TouchInputMapper() {
2602 }
2603
2604 uint32_t TouchInputMapper::getSources() {
2605     return mSource;
2606 }
2607
2608 void TouchInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
2609     InputMapper::populateDeviceInfo(info);
2610
2611     if (mDeviceMode != DEVICE_MODE_DISABLED) {
2612         info->addMotionRange(mOrientedRanges.x);
2613         info->addMotionRange(mOrientedRanges.y);
2614         info->addMotionRange(mOrientedRanges.pressure);
2615
2616         if (mOrientedRanges.haveSize) {
2617             info->addMotionRange(mOrientedRanges.size);
2618         }
2619
2620         if (mOrientedRanges.haveTouchSize) {
2621             info->addMotionRange(mOrientedRanges.touchMajor);
2622             info->addMotionRange(mOrientedRanges.touchMinor);
2623         }
2624
2625         if (mOrientedRanges.haveToolSize) {
2626             info->addMotionRange(mOrientedRanges.toolMajor);
2627             info->addMotionRange(mOrientedRanges.toolMinor);
2628         }
2629
2630         if (mOrientedRanges.haveOrientation) {
2631             info->addMotionRange(mOrientedRanges.orientation);
2632         }
2633
2634         if (mOrientedRanges.haveDistance) {
2635             info->addMotionRange(mOrientedRanges.distance);
2636         }
2637
2638         if (mOrientedRanges.haveTilt) {
2639             info->addMotionRange(mOrientedRanges.tilt);
2640         }
2641
2642         if (mCursorScrollAccumulator.haveRelativeVWheel()) {
2643             info->addMotionRange(AMOTION_EVENT_AXIS_VSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
2644                     0.0f);
2645         }
2646         if (mCursorScrollAccumulator.haveRelativeHWheel()) {
2647             info->addMotionRange(AMOTION_EVENT_AXIS_HSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
2648                     0.0f);
2649         }
2650         if (mCalibration.coverageCalibration == Calibration::COVERAGE_CALIBRATION_BOX) {
2651             const InputDeviceInfo::MotionRange& x = mOrientedRanges.x;
2652             const InputDeviceInfo::MotionRange& y = mOrientedRanges.y;
2653             info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_1, mSource, x.min, x.max, x.flat,
2654                     x.fuzz, x.resolution);
2655             info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_2, mSource, y.min, y.max, y.flat,
2656                     y.fuzz, y.resolution);
2657             info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_3, mSource, x.min, x.max, x.flat,
2658                     x.fuzz, x.resolution);
2659             info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_4, mSource, y.min, y.max, y.flat,
2660                     y.fuzz, y.resolution);
2661         }
2662         info->setButtonUnderPad(mParameters.hasButtonUnderPad);
2663     }
2664 }
2665
2666 void TouchInputMapper::dump(String8& dump) {
2667     dump.append(INDENT2 "Touch Input Mapper:\n");
2668     dumpParameters(dump);
2669     dumpVirtualKeys(dump);
2670     dumpRawPointerAxes(dump);
2671     dumpCalibration(dump);
2672     dumpAffineTransformation(dump);
2673     dumpSurface(dump);
2674
2675     dump.appendFormat(INDENT3 "Translation and Scaling Factors:\n");
2676     dump.appendFormat(INDENT4 "XTranslate: %0.3f\n", mXTranslate);
2677     dump.appendFormat(INDENT4 "YTranslate: %0.3f\n", mYTranslate);
2678     dump.appendFormat(INDENT4 "XScale: %0.3f\n", mXScale);
2679     dump.appendFormat(INDENT4 "YScale: %0.3f\n", mYScale);
2680     dump.appendFormat(INDENT4 "XPrecision: %0.3f\n", mXPrecision);
2681     dump.appendFormat(INDENT4 "YPrecision: %0.3f\n", mYPrecision);
2682     dump.appendFormat(INDENT4 "GeometricScale: %0.3f\n", mGeometricScale);
2683     dump.appendFormat(INDENT4 "PressureScale: %0.3f\n", mPressureScale);
2684     dump.appendFormat(INDENT4 "SizeScale: %0.3f\n", mSizeScale);
2685     dump.appendFormat(INDENT4 "OrientationScale: %0.3f\n", mOrientationScale);
2686     dump.appendFormat(INDENT4 "DistanceScale: %0.3f\n", mDistanceScale);
2687     dump.appendFormat(INDENT4 "HaveTilt: %s\n", toString(mHaveTilt));
2688     dump.appendFormat(INDENT4 "TiltXCenter: %0.3f\n", mTiltXCenter);
2689     dump.appendFormat(INDENT4 "TiltXScale: %0.3f\n", mTiltXScale);
2690     dump.appendFormat(INDENT4 "TiltYCenter: %0.3f\n", mTiltYCenter);
2691     dump.appendFormat(INDENT4 "TiltYScale: %0.3f\n", mTiltYScale);
2692
2693     dump.appendFormat(INDENT3 "Last Button State: 0x%08x\n", mLastButtonState);
2694
2695     dump.appendFormat(INDENT3 "Last Raw Touch: pointerCount=%d\n",
2696             mLastRawPointerData.pointerCount);
2697     for (uint32_t i = 0; i < mLastRawPointerData.pointerCount; i++) {
2698         const RawPointerData::Pointer& pointer = mLastRawPointerData.pointers[i];
2699         dump.appendFormat(INDENT4 "[%d]: id=%d, x=%d, y=%d, pressure=%d, "
2700                 "touchMajor=%d, touchMinor=%d, toolMajor=%d, toolMinor=%d, "
2701                 "orientation=%d, tiltX=%d, tiltY=%d, distance=%d, "
2702                 "toolType=%d, isHovering=%s\n", i,
2703                 pointer.id, pointer.x, pointer.y, pointer.pressure,
2704                 pointer.touchMajor, pointer.touchMinor,
2705                 pointer.toolMajor, pointer.toolMinor,
2706                 pointer.orientation, pointer.tiltX, pointer.tiltY, pointer.distance,
2707                 pointer.toolType, toString(pointer.isHovering));
2708     }
2709
2710     dump.appendFormat(INDENT3 "Last Cooked Touch: pointerCount=%d\n",
2711             mLastCookedPointerData.pointerCount);
2712     for (uint32_t i = 0; i < mLastCookedPointerData.pointerCount; i++) {
2713         const PointerProperties& pointerProperties = mLastCookedPointerData.pointerProperties[i];
2714         const PointerCoords& pointerCoords = mLastCookedPointerData.pointerCoords[i];
2715         dump.appendFormat(INDENT4 "[%d]: id=%d, x=%0.3f, y=%0.3f, pressure=%0.3f, "
2716                 "touchMajor=%0.3f, touchMinor=%0.3f, toolMajor=%0.3f, toolMinor=%0.3f, "
2717                 "orientation=%0.3f, tilt=%0.3f, distance=%0.3f, "
2718                 "toolType=%d, isHovering=%s\n", i,
2719                 pointerProperties.id,
2720                 pointerCoords.getX(),
2721                 pointerCoords.getY(),
2722                 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
2723                 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
2724                 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
2725                 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
2726                 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
2727                 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION),
2728                 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TILT),
2729                 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_DISTANCE),
2730                 pointerProperties.toolType,
2731                 toString(mLastCookedPointerData.isHovering(i)));
2732     }
2733
2734     if (mDeviceMode == DEVICE_MODE_POINTER) {
2735         dump.appendFormat(INDENT3 "Pointer Gesture Detector:\n");
2736         dump.appendFormat(INDENT4 "XMovementScale: %0.3f\n",
2737                 mPointerXMovementScale);
2738         dump.appendFormat(INDENT4 "YMovementScale: %0.3f\n",
2739                 mPointerYMovementScale);
2740         dump.appendFormat(INDENT4 "XZoomScale: %0.3f\n",
2741                 mPointerXZoomScale);
2742         dump.appendFormat(INDENT4 "YZoomScale: %0.3f\n",
2743                 mPointerYZoomScale);
2744         dump.appendFormat(INDENT4 "MaxSwipeWidth: %f\n",
2745                 mPointerGestureMaxSwipeWidth);
2746     }
2747 }
2748
2749 void TouchInputMapper::configure(nsecs_t when,
2750         const InputReaderConfiguration* config, uint32_t changes) {
2751     InputMapper::configure(when, config, changes);
2752
2753     mConfig = *config;
2754
2755     if (!changes) { // first time only
2756         // Configure basic parameters.
2757         configureParameters();
2758
2759         // Configure common accumulators.
2760         mCursorScrollAccumulator.configure(getDevice());
2761         mTouchButtonAccumulator.configure(getDevice());
2762
2763         // Configure absolute axis information.
2764         configureRawPointerAxes();
2765
2766         // Prepare input device calibration.
2767         parseCalibration();
2768         resolveCalibration();
2769     }
2770
2771     if (!changes || (changes & InputReaderConfiguration::TOUCH_AFFINE_TRANSFORMATION)) {
2772         // Update location calibration to reflect current settings
2773         updateAffineTransformation();
2774     }
2775
2776     if (!changes || (changes & InputReaderConfiguration::CHANGE_POINTER_SPEED)) {
2777         // Update pointer speed.
2778         mPointerVelocityControl.setParameters(mConfig.pointerVelocityControlParameters);
2779         mWheelXVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
2780         mWheelYVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
2781     }
2782
2783     bool resetNeeded = false;
2784     if (!changes || (changes & (InputReaderConfiguration::CHANGE_DISPLAY_INFO
2785             | InputReaderConfiguration::CHANGE_POINTER_GESTURE_ENABLEMENT
2786             | InputReaderConfiguration::CHANGE_SHOW_TOUCHES))) {
2787         // Configure device sources, surface dimensions, orientation and
2788         // scaling factors.
2789         configureSurface(when, &resetNeeded);
2790     }
2791
2792     if (changes && resetNeeded) {
2793         // Send reset, unless this is the first time the device has been configured,
2794         // in which case the reader will call reset itself after all mappers are ready.
2795         getDevice()->notifyReset(when);
2796     }
2797 }
2798
2799 void TouchInputMapper::configureParameters() {
2800     // Use the pointer presentation mode for devices that do not support distinct
2801     // multitouch.  The spot-based presentation relies on being able to accurately
2802     // locate two or more fingers on the touch pad.
2803     mParameters.gestureMode = getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_SEMI_MT)
2804             ? Parameters::GESTURE_MODE_POINTER : Parameters::GESTURE_MODE_SPOTS;
2805
2806     String8 gestureModeString;
2807     if (getDevice()->getConfiguration().tryGetProperty(String8("touch.gestureMode"),
2808             gestureModeString)) {
2809         if (gestureModeString == "pointer") {
2810             mParameters.gestureMode = Parameters::GESTURE_MODE_POINTER;
2811         } else if (gestureModeString == "spots") {
2812             mParameters.gestureMode = Parameters::GESTURE_MODE_SPOTS;
2813         } else if (gestureModeString != "default") {
2814             ALOGW("Invalid value for touch.gestureMode: '%s'", gestureModeString.string());
2815         }
2816     }
2817
2818     if (getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_DIRECT)) {
2819         // The device is a touch screen.
2820         mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_SCREEN;
2821     } else if (getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_POINTER)) {
2822         // The device is a pointing device like a track pad.
2823         mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
2824     } else if (getEventHub()->hasRelativeAxis(getDeviceId(), REL_X)
2825             || getEventHub()->hasRelativeAxis(getDeviceId(), REL_Y)) {
2826         // The device is a cursor device with a touch pad attached.
2827         // By default don't use the touch pad to move the pointer.
2828         mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_PAD;
2829     } else {
2830         // The device is a touch pad of unknown purpose.
2831         mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
2832     }
2833
2834     mParameters.hasButtonUnderPad=
2835             getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_BUTTONPAD);
2836
2837     String8 deviceTypeString;
2838     if (getDevice()->getConfiguration().tryGetProperty(String8("touch.deviceType"),
2839             deviceTypeString)) {
2840         if (deviceTypeString == "touchScreen") {
2841             mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_SCREEN;
2842         } else if (deviceTypeString == "touchPad") {
2843             mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_PAD;
2844         } else if (deviceTypeString == "touchNavigation") {
2845             mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_NAVIGATION;
2846         } else if (deviceTypeString == "pointer") {
2847             mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
2848         } else if (deviceTypeString != "default") {
2849             ALOGW("Invalid value for touch.deviceType: '%s'", deviceTypeString.string());
2850         }
2851     }
2852
2853     mParameters.orientationAware = mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN;
2854     getDevice()->getConfiguration().tryGetProperty(String8("touch.orientationAware"),
2855             mParameters.orientationAware);
2856
2857     mParameters.hasAssociatedDisplay = false;
2858     mParameters.associatedDisplayIsExternal = false;
2859     if (mParameters.orientationAware
2860             || mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN
2861             || mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER) {
2862         mParameters.hasAssociatedDisplay = true;
2863         mParameters.associatedDisplayIsExternal =
2864                 mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN
2865                         && getDevice()->isExternal();
2866     }
2867
2868     // Initial downs on external touch devices should wake the device.
2869     // Normally we don't do this for internal touch screens to prevent them from waking
2870     // up in your pocket but you can enable it using the input device configuration.
2871     mParameters.wake = getDevice()->isExternal();
2872     getDevice()->getConfiguration().tryGetProperty(String8("touch.wake"),
2873             mParameters.wake);
2874 }
2875
2876 void TouchInputMapper::dumpParameters(String8& dump) {
2877     dump.append(INDENT3 "Parameters:\n");
2878
2879     switch (mParameters.gestureMode) {
2880     case Parameters::GESTURE_MODE_POINTER:
2881         dump.append(INDENT4 "GestureMode: pointer\n");
2882         break;
2883     case Parameters::GESTURE_MODE_SPOTS:
2884         dump.append(INDENT4 "GestureMode: spots\n");
2885         break;
2886     default:
2887         assert(false);
2888     }
2889
2890     switch (mParameters.deviceType) {
2891     case Parameters::DEVICE_TYPE_TOUCH_SCREEN:
2892         dump.append(INDENT4 "DeviceType: touchScreen\n");
2893         break;
2894     case Parameters::DEVICE_TYPE_TOUCH_PAD:
2895         dump.append(INDENT4 "DeviceType: touchPad\n");
2896         break;
2897     case Parameters::DEVICE_TYPE_TOUCH_NAVIGATION:
2898         dump.append(INDENT4 "DeviceType: touchNavigation\n");
2899         break;
2900     case Parameters::DEVICE_TYPE_POINTER:
2901         dump.append(INDENT4 "DeviceType: pointer\n");
2902         break;
2903     default:
2904         ALOG_ASSERT(false);
2905     }
2906
2907     dump.appendFormat(INDENT4 "AssociatedDisplay: hasAssociatedDisplay=%s, isExternal=%s\n",
2908             toString(mParameters.hasAssociatedDisplay),
2909             toString(mParameters.associatedDisplayIsExternal));
2910     dump.appendFormat(INDENT4 "OrientationAware: %s\n",
2911             toString(mParameters.orientationAware));
2912 }
2913
2914 void TouchInputMapper::configureRawPointerAxes() {
2915     mRawPointerAxes.clear();
2916 }
2917
2918 void TouchInputMapper::dumpRawPointerAxes(String8& dump) {
2919     dump.append(INDENT3 "Raw Touch Axes:\n");
2920     dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.x, "X");
2921     dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.y, "Y");
2922     dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.pressure, "Pressure");
2923     dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMajor, "TouchMajor");
2924     dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMinor, "TouchMinor");
2925     dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMajor, "ToolMajor");
2926     dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMinor, "ToolMinor");
2927     dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.orientation, "Orientation");
2928     dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.distance, "Distance");
2929     dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltX, "TiltX");
2930     dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltY, "TiltY");
2931     dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.trackingId, "TrackingId");
2932     dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.slot, "Slot");
2933 }
2934
2935 void TouchInputMapper::configureSurface(nsecs_t when, bool* outResetNeeded) {
2936     int32_t oldDeviceMode = mDeviceMode;
2937
2938     // Determine device mode.
2939     if (mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER
2940             && mConfig.pointerGesturesEnabled) {
2941         mSource = AINPUT_SOURCE_MOUSE;
2942         mDeviceMode = DEVICE_MODE_POINTER;
2943         if (hasStylus()) {
2944             mSource |= AINPUT_SOURCE_STYLUS;
2945         }
2946     } else if (mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN
2947             && mParameters.hasAssociatedDisplay) {
2948         mSource = AINPUT_SOURCE_TOUCHSCREEN;
2949         mDeviceMode = DEVICE_MODE_DIRECT;
2950         if (hasStylus()) {
2951             mSource |= AINPUT_SOURCE_STYLUS;
2952         }
2953     } else if (mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_NAVIGATION) {
2954         mSource = AINPUT_SOURCE_TOUCH_NAVIGATION;
2955         mDeviceMode = DEVICE_MODE_NAVIGATION;
2956     } else {
2957         mSource = AINPUT_SOURCE_TOUCHPAD;
2958         mDeviceMode = DEVICE_MODE_UNSCALED;
2959     }
2960
2961     // Ensure we have valid X and Y axes.
2962     if (!mRawPointerAxes.x.valid || !mRawPointerAxes.y.valid) {
2963         ALOGW(INDENT "Touch device '%s' did not report support for X or Y axis!  "
2964                 "The device will be inoperable.", getDeviceName().string());
2965         mDeviceMode = DEVICE_MODE_DISABLED;
2966         return;
2967     }
2968
2969     // Raw width and height in the natural orientation.
2970     int32_t rawWidth = mRawPointerAxes.x.maxValue - mRawPointerAxes.x.minValue + 1;
2971     int32_t rawHeight = mRawPointerAxes.y.maxValue - mRawPointerAxes.y.minValue + 1;
2972
2973     // Get associated display dimensions.
2974     DisplayViewport newViewport;
2975     if (mParameters.hasAssociatedDisplay) {
2976         if (!mConfig.getDisplayInfo(mParameters.associatedDisplayIsExternal, &newViewport)) {
2977             ALOGI(INDENT "Touch device '%s' could not query the properties of its associated "
2978                     "display.  The device will be inoperable until the display size "
2979                     "becomes available.",
2980                     getDeviceName().string());
2981             mDeviceMode = DEVICE_MODE_DISABLED;
2982             return;
2983         }
2984     } else {
2985         newViewport.setNonDisplayViewport(rawWidth, rawHeight);
2986     }
2987     bool viewportChanged = mViewport != newViewport;
2988     if (viewportChanged) {
2989         mViewport = newViewport;
2990
2991         if (mDeviceMode == DEVICE_MODE_DIRECT || mDeviceMode == DEVICE_MODE_POINTER) {
2992             // Convert rotated viewport to natural surface coordinates.
2993             int32_t naturalLogicalWidth, naturalLogicalHeight;
2994             int32_t naturalPhysicalWidth, naturalPhysicalHeight;
2995             int32_t naturalPhysicalLeft, naturalPhysicalTop;
2996             int32_t naturalDeviceWidth, naturalDeviceHeight;
2997             switch (mViewport.orientation) {
2998             case DISPLAY_ORIENTATION_90:
2999                 naturalLogicalWidth = mViewport.logicalBottom - mViewport.logicalTop;
3000                 naturalLogicalHeight = mViewport.logicalRight - mViewport.logicalLeft;
3001                 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
3002                 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
3003                 naturalPhysicalLeft = mViewport.deviceHeight - mViewport.physicalBottom;
3004                 naturalPhysicalTop = mViewport.physicalLeft;
3005                 naturalDeviceWidth = mViewport.deviceHeight;
3006                 naturalDeviceHeight = mViewport.deviceWidth;
3007                 break;
3008             case DISPLAY_ORIENTATION_180:
3009                 naturalLogicalWidth = mViewport.logicalRight - mViewport.logicalLeft;
3010                 naturalLogicalHeight = mViewport.logicalBottom - mViewport.logicalTop;
3011                 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
3012                 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
3013                 naturalPhysicalLeft = mViewport.deviceWidth - mViewport.physicalRight;
3014                 naturalPhysicalTop = mViewport.deviceHeight - mViewport.physicalBottom;
3015                 naturalDeviceWidth = mViewport.deviceWidth;
3016                 naturalDeviceHeight = mViewport.deviceHeight;
3017                 break;
3018             case DISPLAY_ORIENTATION_270:
3019                 naturalLogicalWidth = mViewport.logicalBottom - mViewport.logicalTop;
3020                 naturalLogicalHeight = mViewport.logicalRight - mViewport.logicalLeft;
3021                 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
3022                 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
3023                 naturalPhysicalLeft = mViewport.physicalTop;
3024                 naturalPhysicalTop = mViewport.deviceWidth - mViewport.physicalRight;
3025                 naturalDeviceWidth = mViewport.deviceHeight;
3026                 naturalDeviceHeight = mViewport.deviceWidth;
3027                 break;
3028             case DISPLAY_ORIENTATION_0:
3029             default:
3030                 naturalLogicalWidth = mViewport.logicalRight - mViewport.logicalLeft;
3031                 naturalLogicalHeight = mViewport.logicalBottom - mViewport.logicalTop;
3032                 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
3033                 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
3034                 naturalPhysicalLeft = mViewport.physicalLeft;
3035                 naturalPhysicalTop = mViewport.physicalTop;
3036                 naturalDeviceWidth = mViewport.deviceWidth;
3037                 naturalDeviceHeight = mViewport.deviceHeight;
3038                 break;
3039             }
3040
3041             mSurfaceWidth = naturalLogicalWidth * naturalDeviceWidth / naturalPhysicalWidth;
3042             mSurfaceHeight = naturalLogicalHeight * naturalDeviceHeight / naturalPhysicalHeight;
3043             mSurfaceLeft = naturalPhysicalLeft * naturalLogicalWidth / naturalPhysicalWidth;
3044             mSurfaceTop = naturalPhysicalTop * naturalLogicalHeight / naturalPhysicalHeight;
3045
3046             mSurfaceOrientation = mParameters.orientationAware ?
3047                     mViewport.orientation : DISPLAY_ORIENTATION_0;
3048         } else {
3049             mSurfaceWidth = rawWidth;
3050             mSurfaceHeight = rawHeight;
3051             mSurfaceLeft = 0;
3052             mSurfaceTop = 0;
3053             mSurfaceOrientation = DISPLAY_ORIENTATION_0;
3054         }
3055     }
3056
3057     // If moving between pointer modes, need to reset some state.
3058     bool deviceModeChanged = mDeviceMode != oldDeviceMode;
3059     if (deviceModeChanged) {
3060         mOrientedRanges.clear();
3061     }
3062
3063     // Create pointer controller if needed.
3064     if (mDeviceMode == DEVICE_MODE_POINTER ||
3065             (mDeviceMode == DEVICE_MODE_DIRECT && mConfig.showTouches)) {
3066         if (mPointerController == NULL) {
3067             mPointerController = getPolicy()->obtainPointerController(getDeviceId());
3068         }
3069     } else {
3070         mPointerController.clear();
3071     }
3072
3073     if (viewportChanged || deviceModeChanged) {
3074         ALOGI("Device reconfigured: id=%d, name='%s', size %dx%d, orientation %d, mode %d, "
3075                 "display id %d",
3076                 getDeviceId(), getDeviceName().string(), mSurfaceWidth, mSurfaceHeight,
3077                 mSurfaceOrientation, mDeviceMode, mViewport.displayId);
3078
3079         // Configure X and Y factors.
3080         mXScale = float(mSurfaceWidth) / rawWidth;
3081         mYScale = float(mSurfaceHeight) / rawHeight;
3082         mXTranslate = -mSurfaceLeft;
3083         mYTranslate = -mSurfaceTop;
3084         mXPrecision = 1.0f / mXScale;
3085         mYPrecision = 1.0f / mYScale;
3086
3087         mOrientedRanges.x.axis = AMOTION_EVENT_AXIS_X;
3088         mOrientedRanges.x.source = mSource;
3089         mOrientedRanges.y.axis = AMOTION_EVENT_AXIS_Y;
3090         mOrientedRanges.y.source = mSource;
3091
3092         configureVirtualKeys();
3093
3094         // Scale factor for terms that are not oriented in a particular axis.
3095         // If the pixels are square then xScale == yScale otherwise we fake it
3096         // by choosing an average.
3097         mGeometricScale = avg(mXScale, mYScale);
3098
3099         // Size of diagonal axis.
3100         float diagonalSize = hypotf(mSurfaceWidth, mSurfaceHeight);
3101
3102         // Size factors.
3103         if (mCalibration.sizeCalibration != Calibration::SIZE_CALIBRATION_NONE) {
3104             if (mRawPointerAxes.touchMajor.valid
3105                     && mRawPointerAxes.touchMajor.maxValue != 0) {
3106                 mSizeScale = 1.0f / mRawPointerAxes.touchMajor.maxValue;
3107             } else if (mRawPointerAxes.toolMajor.valid
3108                     && mRawPointerAxes.toolMajor.maxValue != 0) {
3109                 mSizeScale = 1.0f / mRawPointerAxes.toolMajor.maxValue;
3110             } else {
3111                 mSizeScale = 0.0f;
3112             }
3113
3114             mOrientedRanges.haveTouchSize = true;
3115             mOrientedRanges.haveToolSize = true;
3116             mOrientedRanges.haveSize = true;
3117
3118             mOrientedRanges.touchMajor.axis = AMOTION_EVENT_AXIS_TOUCH_MAJOR;
3119             mOrientedRanges.touchMajor.source = mSource;
3120             mOrientedRanges.touchMajor.min = 0;
3121             mOrientedRanges.touchMajor.max = diagonalSize;
3122             mOrientedRanges.touchMajor.flat = 0;
3123             mOrientedRanges.touchMajor.fuzz = 0;
3124             mOrientedRanges.touchMajor.resolution = 0;
3125
3126             mOrientedRanges.touchMinor = mOrientedRanges.touchMajor;
3127             mOrientedRanges.touchMinor.axis = AMOTION_EVENT_AXIS_TOUCH_MINOR;
3128
3129             mOrientedRanges.toolMajor.axis = AMOTION_EVENT_AXIS_TOOL_MAJOR;
3130             mOrientedRanges.toolMajor.source = mSource;
3131             mOrientedRanges.toolMajor.min = 0;
3132             mOrientedRanges.toolMajor.max = diagonalSize;
3133             mOrientedRanges.toolMajor.flat = 0;
3134             mOrientedRanges.toolMajor.fuzz = 0;
3135             mOrientedRanges.toolMajor.resolution = 0;
3136
3137             mOrientedRanges.toolMinor = mOrientedRanges.toolMajor;
3138             mOrientedRanges.toolMinor.axis = AMOTION_EVENT_AXIS_TOOL_MINOR;
3139
3140             mOrientedRanges.size.axis = AMOTION_EVENT_AXIS_SIZE;
3141             mOrientedRanges.size.source = mSource;
3142             mOrientedRanges.size.min = 0;
3143             mOrientedRanges.size.max = 1.0;
3144             mOrientedRanges.size.flat = 0;
3145             mOrientedRanges.size.fuzz = 0;
3146             mOrientedRanges.size.resolution = 0;
3147         } else {
3148             mSizeScale = 0.0f;
3149         }
3150
3151         // Pressure factors.
3152         mPressureScale = 0;
3153         if (mCalibration.pressureCalibration == Calibration::PRESSURE_CALIBRATION_PHYSICAL
3154                 || mCalibration.pressureCalibration
3155                         == Calibration::PRESSURE_CALIBRATION_AMPLITUDE) {
3156             if (mCalibration.havePressureScale) {
3157                 mPressureScale = mCalibration.pressureScale;
3158             } else if (mRawPointerAxes.pressure.valid
3159                     && mRawPointerAxes.pressure.maxValue != 0) {
3160                 mPressureScale = 1.0f / mRawPointerAxes.pressure.maxValue;
3161             }
3162         }
3163
3164         mOrientedRanges.pressure.axis = AMOTION_EVENT_AXIS_PRESSURE;
3165         mOrientedRanges.pressure.source = mSource;
3166         mOrientedRanges.pressure.min = 0;
3167         mOrientedRanges.pressure.max = 1.0;
3168         mOrientedRanges.pressure.flat = 0;
3169         mOrientedRanges.pressure.fuzz = 0;
3170         mOrientedRanges.pressure.resolution = 0;
3171
3172         // Tilt
3173         mTiltXCenter = 0;
3174         mTiltXScale = 0;
3175         mTiltYCenter = 0;
3176         mTiltYScale = 0;
3177         mHaveTilt = mRawPointerAxes.tiltX.valid && mRawPointerAxes.tiltY.valid;
3178         if (mHaveTilt) {
3179             mTiltXCenter = avg(mRawPointerAxes.tiltX.minValue,
3180                     mRawPointerAxes.tiltX.maxValue);
3181             mTiltYCenter = avg(mRawPointerAxes.tiltY.minValue,
3182                     mRawPointerAxes.tiltY.maxValue);
3183             mTiltXScale = M_PI / 180;
3184             mTiltYScale = M_PI / 180;
3185
3186             mOrientedRanges.haveTilt = true;
3187
3188             mOrientedRanges.tilt.axis = AMOTION_EVENT_AXIS_TILT;
3189             mOrientedRanges.tilt.source = mSource;
3190             mOrientedRanges.tilt.min = 0;
3191             mOrientedRanges.tilt.max = M_PI_2;
3192             mOrientedRanges.tilt.flat = 0;
3193             mOrientedRanges.tilt.fuzz = 0;
3194             mOrientedRanges.tilt.resolution = 0;
3195         }
3196
3197         // Orientation
3198         mOrientationScale = 0;
3199         if (mHaveTilt) {
3200             mOrientedRanges.haveOrientation = true;
3201
3202             mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
3203             mOrientedRanges.orientation.source = mSource;
3204             mOrientedRanges.orientation.min = -M_PI;
3205             mOrientedRanges.orientation.max = M_PI;
3206             mOrientedRanges.orientation.flat = 0;
3207             mOrientedRanges.orientation.fuzz = 0;
3208             mOrientedRanges.orientation.resolution = 0;
3209         } else if (mCalibration.orientationCalibration !=
3210                 Calibration::ORIENTATION_CALIBRATION_NONE) {
3211             if (mCalibration.orientationCalibration
3212                     == Calibration::ORIENTATION_CALIBRATION_INTERPOLATED) {
3213                 if (mRawPointerAxes.orientation.valid) {
3214                     if (mRawPointerAxes.orientation.maxValue > 0) {
3215                         mOrientationScale = M_PI_2 / mRawPointerAxes.orientation.maxValue;
3216                     } else if (mRawPointerAxes.orientation.minValue < 0) {
3217                         mOrientationScale = -M_PI_2 / mRawPointerAxes.orientation.minValue;
3218                     } else {
3219                         mOrientationScale = 0;
3220                     }
3221                 }
3222             }
3223
3224             mOrientedRanges.haveOrientation = true;
3225
3226             mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
3227             mOrientedRanges.orientation.source = mSource;
3228             mOrientedRanges.orientation.min = -M_PI_2;
3229             mOrientedRanges.orientation.max = M_PI_2;
3230             mOrientedRanges.orientation.flat = 0;
3231             mOrientedRanges.orientation.fuzz = 0;
3232             mOrientedRanges.orientation.resolution = 0;
3233         }
3234
3235         // Distance
3236         mDistanceScale = 0;
3237         if (mCalibration.distanceCalibration != Calibration::DISTANCE_CALIBRATION_NONE) {
3238             if (mCalibration.distanceCalibration
3239                     == Calibration::DISTANCE_CALIBRATION_SCALED) {
3240                 if (mCalibration.haveDistanceScale) {
3241                     mDistanceScale = mCalibration.distanceScale;
3242                 } else {
3243                     mDistanceScale = 1.0f;
3244                 }
3245             }
3246
3247             mOrientedRanges.haveDistance = true;
3248
3249             mOrientedRanges.distance.axis = AMOTION_EVENT_AXIS_DISTANCE;
3250             mOrientedRanges.distance.source = mSource;
3251             mOrientedRanges.distance.min =
3252                     mRawPointerAxes.distance.minValue * mDistanceScale;
3253             mOrientedRanges.distance.max =
3254                     mRawPointerAxes.distance.maxValue * mDistanceScale;
3255             mOrientedRanges.distance.flat = 0;
3256             mOrientedRanges.distance.fuzz =
3257                     mRawPointerAxes.distance.fuzz * mDistanceScale;
3258             mOrientedRanges.distance.resolution = 0;
3259         }
3260
3261         // Compute oriented precision, scales and ranges.
3262         // Note that the maximum value reported is an inclusive maximum value so it is one
3263         // unit less than the total width or height of surface.
3264         switch (mSurfaceOrientation) {
3265         case DISPLAY_ORIENTATION_90:
3266         case DISPLAY_ORIENTATION_270:
3267             mOrientedXPrecision = mYPrecision;
3268             mOrientedYPrecision = mXPrecision;
3269
3270             mOrientedRanges.x.min = mYTranslate;
3271             mOrientedRanges.x.max = mSurfaceHeight + mYTranslate - 1;
3272             mOrientedRanges.x.flat = 0;
3273             mOrientedRanges.x.fuzz = 0;
3274             mOrientedRanges.x.resolution = mRawPointerAxes.y.resolution * mYScale;
3275
3276             mOrientedRanges.y.min = mXTranslate;
3277             mOrientedRanges.y.max = mSurfaceWidth + mXTranslate - 1;
3278             mOrientedRanges.y.flat = 0;
3279             mOrientedRanges.y.fuzz = 0;
3280             mOrientedRanges.y.resolution = mRawPointerAxes.x.resolution * mXScale;
3281             break;
3282
3283         default:
3284             mOrientedXPrecision = mXPrecision;
3285             mOrientedYPrecision = mYPrecision;
3286
3287             mOrientedRanges.x.min = mXTranslate;
3288             mOrientedRanges.x.max = mSurfaceWidth + mXTranslate - 1;
3289             mOrientedRanges.x.flat = 0;
3290             mOrientedRanges.x.fuzz = 0;
3291             mOrientedRanges.x.resolution = mRawPointerAxes.x.resolution * mXScale;
3292
3293             mOrientedRanges.y.min = mYTranslate;
3294             mOrientedRanges.y.max = mSurfaceHeight + mYTranslate - 1;
3295             mOrientedRanges.y.flat = 0;
3296             mOrientedRanges.y.fuzz = 0;
3297             mOrientedRanges.y.resolution = mRawPointerAxes.y.resolution * mYScale;
3298             break;
3299         }
3300
3301         // Location
3302         updateAffineTransformation();
3303
3304         if (mDeviceMode == DEVICE_MODE_POINTER) {
3305             // Compute pointer gesture detection parameters.
3306             float rawDiagonal = hypotf(rawWidth, rawHeight);
3307             float displayDiagonal = hypotf(mSurfaceWidth, mSurfaceHeight);
3308
3309             // Scale movements such that one whole swipe of the touch pad covers a
3310             // given area relative to the diagonal size of the display when no acceleration
3311             // is applied.
3312             // Assume that the touch pad has a square aspect ratio such that movements in
3313             // X and Y of the same number of raw units cover the same physical distance.
3314             mPointerXMovementScale = mConfig.pointerGestureMovementSpeedRatio
3315                     * displayDiagonal / rawDiagonal;
3316             mPointerYMovementScale = mPointerXMovementScale;
3317
3318             // Scale zooms to cover a smaller range of the display than movements do.
3319             // This value determines the area around the pointer that is affected by freeform
3320             // pointer gestures.
3321             mPointerXZoomScale = mConfig.pointerGestureZoomSpeedRatio
3322                     * displayDiagonal / rawDiagonal;
3323             mPointerYZoomScale = mPointerXZoomScale;
3324
3325             // Max width between pointers to detect a swipe gesture is more than some fraction
3326             // of the diagonal axis of the touch pad.  Touches that are wider than this are
3327             // translated into freeform gestures.
3328             mPointerGestureMaxSwipeWidth =
3329                     mConfig.pointerGestureSwipeMaxWidthRatio * rawDiagonal;
3330
3331             // Abort current pointer usages because the state has changed.
3332             abortPointerUsage(when, 0 /*policyFlags*/);
3333         }
3334
3335         // Inform the dispatcher about the changes.
3336         *outResetNeeded = true;
3337         bumpGeneration();
3338     }
3339 }
3340
3341 void TouchInputMapper::dumpSurface(String8& dump) {
3342     dump.appendFormat(INDENT3 "Viewport: displayId=%d, orientation=%d, "
3343             "logicalFrame=[%d, %d, %d, %d], "
3344             "physicalFrame=[%d, %d, %d, %d], "
3345             "deviceSize=[%d, %d]\n",
3346             mViewport.displayId, mViewport.orientation,
3347             mViewport.logicalLeft, mViewport.logicalTop,
3348             mViewport.logicalRight, mViewport.logicalBottom,
3349             mViewport.physicalLeft, mViewport.physicalTop,
3350             mViewport.physicalRight, mViewport.physicalBottom,
3351             mViewport.deviceWidth, mViewport.deviceHeight);
3352
3353     dump.appendFormat(INDENT3 "SurfaceWidth: %dpx\n", mSurfaceWidth);
3354     dump.appendFormat(INDENT3 "SurfaceHeight: %dpx\n", mSurfaceHeight);
3355     dump.appendFormat(INDENT3 "SurfaceLeft: %d\n", mSurfaceLeft);
3356     dump.appendFormat(INDENT3 "SurfaceTop: %d\n", mSurfaceTop);
3357     dump.appendFormat(INDENT3 "SurfaceOrientation: %d\n", mSurfaceOrientation);
3358 }
3359
3360 void TouchInputMapper::configureVirtualKeys() {
3361     Vector<VirtualKeyDefinition> virtualKeyDefinitions;
3362     getEventHub()->getVirtualKeyDefinitions(getDeviceId(), virtualKeyDefinitions);
3363
3364     mVirtualKeys.clear();
3365
3366     if (virtualKeyDefinitions.size() == 0) {
3367         return;
3368     }
3369
3370     mVirtualKeys.setCapacity(virtualKeyDefinitions.size());
3371
3372     int32_t touchScreenLeft = mRawPointerAxes.x.minValue;
3373     int32_t touchScreenTop = mRawPointerAxes.y.minValue;
3374     int32_t touchScreenWidth = mRawPointerAxes.x.maxValue - mRawPointerAxes.x.minValue + 1;
3375     int32_t touchScreenHeight = mRawPointerAxes.y.maxValue - mRawPointerAxes.y.minValue + 1;
3376
3377     for (size_t i = 0; i < virtualKeyDefinitions.size(); i++) {
3378         const VirtualKeyDefinition& virtualKeyDefinition =
3379                 virtualKeyDefinitions[i];
3380
3381         mVirtualKeys.add();
3382         VirtualKey& virtualKey = mVirtualKeys.editTop();
3383
3384         virtualKey.scanCode = virtualKeyDefinition.scanCode;
3385         int32_t keyCode;
3386         uint32_t flags;
3387         if (getEventHub()->mapKey(getDeviceId(), virtualKey.scanCode, 0, &keyCode, &flags)) {
3388             ALOGW(INDENT "VirtualKey %d: could not obtain key code, ignoring",
3389                     virtualKey.scanCode);
3390             mVirtualKeys.pop(); // drop the key
3391             continue;
3392         }
3393
3394         virtualKey.keyCode = keyCode;
3395         virtualKey.flags = flags;
3396
3397         // convert the key definition's display coordinates into touch coordinates for a hit box
3398         int32_t halfWidth = virtualKeyDefinition.width / 2;
3399         int32_t halfHeight = virtualKeyDefinition.height / 2;
3400
3401         virtualKey.hitLeft = (virtualKeyDefinition.centerX - halfWidth)
3402                 * touchScreenWidth / mSurfaceWidth + touchScreenLeft;
3403         virtualKey.hitRight= (virtualKeyDefinition.centerX + halfWidth)
3404                 * touchScreenWidth / mSurfaceWidth + touchScreenLeft;
3405         virtualKey.hitTop = (virtualKeyDefinition.centerY - halfHeight)
3406                 * touchScreenHeight / mSurfaceHeight + touchScreenTop;
3407         virtualKey.hitBottom = (virtualKeyDefinition.centerY + halfHeight)
3408                 * touchScreenHeight / mSurfaceHeight + touchScreenTop;
3409     }
3410 }
3411
3412 void TouchInputMapper::dumpVirtualKeys(String8& dump) {
3413     if (!mVirtualKeys.isEmpty()) {
3414         dump.append(INDENT3 "Virtual Keys:\n");
3415
3416         for (size_t i = 0; i < mVirtualKeys.size(); i++) {
3417             const VirtualKey& virtualKey = mVirtualKeys.itemAt(i);
3418             dump.appendFormat(INDENT4 "%zu: scanCode=%d, keyCode=%d, "
3419                     "hitLeft=%d, hitRight=%d, hitTop=%d, hitBottom=%d\n",
3420                     i, virtualKey.scanCode, virtualKey.keyCode,
3421                     virtualKey.hitLeft, virtualKey.hitRight,
3422                     virtualKey.hitTop, virtualKey.hitBottom);
3423         }
3424     }
3425 }
3426
3427 void TouchInputMapper::parseCalibration() {
3428     const PropertyMap& in = getDevice()->getConfiguration();
3429     Calibration& out = mCalibration;
3430
3431     // Size
3432     out.sizeCalibration = Calibration::SIZE_CALIBRATION_DEFAULT;
3433     String8 sizeCalibrationString;
3434     if (in.tryGetProperty(String8("touch.size.calibration"), sizeCalibrationString)) {
3435         if (sizeCalibrationString == "none") {
3436             out.sizeCalibration = Calibration::SIZE_CALIBRATION_NONE;
3437         } else if (sizeCalibrationString == "geometric") {
3438             out.sizeCalibration = Calibration::SIZE_CALIBRATION_GEOMETRIC;
3439         } else if (sizeCalibrationString == "diameter") {
3440             out.sizeCalibration = Calibration::SIZE_CALIBRATION_DIAMETER;
3441         } else if (sizeCalibrationString == "box") {
3442             out.sizeCalibration = Calibration::SIZE_CALIBRATION_BOX;
3443         } else if (sizeCalibrationString == "area") {
3444             out.sizeCalibration = Calibration::SIZE_CALIBRATION_AREA;
3445         } else if (sizeCalibrationString != "default") {
3446             ALOGW("Invalid value for touch.size.calibration: '%s'",
3447                     sizeCalibrationString.string());
3448         }
3449     }
3450
3451     out.haveSizeScale = in.tryGetProperty(String8("touch.size.scale"),
3452             out.sizeScale);
3453     out.haveSizeBias = in.tryGetProperty(String8("touch.size.bias"),
3454             out.sizeBias);
3455     out.haveSizeIsSummed = in.tryGetProperty(String8("touch.size.isSummed"),
3456             out.sizeIsSummed);
3457
3458     // Pressure
3459     out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_DEFAULT;
3460     String8 pressureCalibrationString;
3461     if (in.tryGetProperty(String8("touch.pressure.calibration"), pressureCalibrationString)) {
3462         if (pressureCalibrationString == "none") {
3463             out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_NONE;
3464         } else if (pressureCalibrationString == "physical") {
3465             out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_PHYSICAL;
3466         } else if (pressureCalibrationString == "amplitude") {
3467             out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_AMPLITUDE;
3468         } else if (pressureCalibrationString != "default") {
3469             ALOGW("Invalid value for touch.pressure.calibration: '%s'",
3470                     pressureCalibrationString.string());
3471         }
3472     }
3473
3474     out.havePressureScale = in.tryGetProperty(String8("touch.pressure.scale"),
3475             out.pressureScale);
3476
3477     // Orientation
3478     out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_DEFAULT;
3479     String8 orientationCalibrationString;
3480     if (in.tryGetProperty(String8("touch.orientation.calibration"), orientationCalibrationString)) {
3481         if (orientationCalibrationString == "none") {
3482             out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_NONE;
3483         } else if (orientationCalibrationString == "interpolated") {
3484             out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_INTERPOLATED;
3485         } else if (orientationCalibrationString == "vector") {
3486             out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_VECTOR;
3487         } else if (orientationCalibrationString != "default") {
3488             ALOGW("Invalid value for touch.orientation.calibration: '%s'",
3489                     orientationCalibrationString.string());
3490         }
3491     }
3492
3493     // Distance
3494     out.distanceCalibration = Calibration::DISTANCE_CALIBRATION_DEFAULT;
3495     String8 distanceCalibrationString;
3496     if (in.tryGetProperty(String8("touch.distance.calibration"), distanceCalibrationString)) {
3497         if (distanceCalibrationString == "none") {
3498             out.distanceCalibration = Calibration::DISTANCE_CALIBRATION_NONE;
3499         } else if (distanceCalibrationString == "scaled") {
3500             out.distanceCalibration = Calibration::DISTANCE_CALIBRATION_SCALED;
3501         } else if (distanceCalibrationString != "default") {
3502             ALOGW("Invalid value for touch.distance.calibration: '%s'",
3503                     distanceCalibrationString.string());
3504         }
3505     }
3506
3507     out.haveDistanceScale = in.tryGetProperty(String8("touch.distance.scale"),
3508             out.distanceScale);
3509
3510     out.coverageCalibration = Calibration::COVERAGE_CALIBRATION_DEFAULT;
3511     String8 coverageCalibrationString;
3512     if (in.tryGetProperty(String8("touch.coverage.calibration"), coverageCalibrationString)) {
3513         if (coverageCalibrationString == "none") {
3514             out.coverageCalibration = Calibration::COVERAGE_CALIBRATION_NONE;
3515         } else if (coverageCalibrationString == "box") {
3516             out.coverageCalibration = Calibration::COVERAGE_CALIBRATION_BOX;
3517         } else if (coverageCalibrationString != "default") {
3518             ALOGW("Invalid value for touch.coverage.calibration: '%s'",
3519                     coverageCalibrationString.string());
3520         }
3521     }
3522 }
3523
3524 void TouchInputMapper::resolveCalibration() {
3525     // Size
3526     if (mRawPointerAxes.touchMajor.valid || mRawPointerAxes.toolMajor.valid) {
3527         if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_DEFAULT) {
3528             mCalibration.sizeCalibration = Calibration::SIZE_CALIBRATION_GEOMETRIC;
3529         }
3530     } else {
3531         mCalibration.sizeCalibration = Calibration::SIZE_CALIBRATION_NONE;
3532     }
3533
3534     // Pressure
3535     if (mRawPointerAxes.pressure.valid) {
3536         if (mCalibration.pressureCalibration == Calibration::PRESSURE_CALIBRATION_DEFAULT) {
3537             mCalibration.pressureCalibration = Calibration::PRESSURE_CALIBRATION_PHYSICAL;
3538         }
3539     } else {
3540         mCalibration.pressureCalibration = Calibration::PRESSURE_CALIBRATION_NONE;
3541     }
3542
3543     // Orientation
3544     if (mRawPointerAxes.orientation.valid) {
3545         if (mCalibration.orientationCalibration == Calibration::ORIENTATION_CALIBRATION_DEFAULT) {
3546             mCalibration.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_INTERPOLATED;
3547         }
3548     } else {
3549         mCalibration.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_NONE;
3550     }
3551
3552     // Distance
3553     if (mRawPointerAxes.distance.valid) {
3554         if (mCalibration.distanceCalibration == Calibration::DISTANCE_CALIBRATION_DEFAULT) {
3555             mCalibration.distanceCalibration = Calibration::DISTANCE_CALIBRATION_SCALED;
3556         }
3557     } else {
3558         mCalibration.distanceCalibration = Calibration::DISTANCE_CALIBRATION_NONE;
3559     }
3560
3561     // Coverage
3562     if (mCalibration.coverageCalibration == Calibration::COVERAGE_CALIBRATION_DEFAULT) {
3563         mCalibration.coverageCalibration = Calibration::COVERAGE_CALIBRATION_NONE;
3564     }
3565 }
3566
3567 void TouchInputMapper::dumpCalibration(String8& dump) {
3568     dump.append(INDENT3 "Calibration:\n");
3569
3570     // Size
3571     switch (mCalibration.sizeCalibration) {
3572     case Calibration::SIZE_CALIBRATION_NONE:
3573         dump.append(INDENT4 "touch.size.calibration: none\n");
3574         break;
3575     case Calibration::SIZE_CALIBRATION_GEOMETRIC:
3576         dump.append(INDENT4 "touch.size.calibration: geometric\n");
3577         break;
3578     case Calibration::SIZE_CALIBRATION_DIAMETER:
3579         dump.append(INDENT4 "touch.size.calibration: diameter\n");
3580         break;
3581     case Calibration::SIZE_CALIBRATION_BOX:
3582         dump.append(INDENT4 "touch.size.calibration: box\n");
3583         break;
3584     case Calibration::SIZE_CALIBRATION_AREA:
3585         dump.append(INDENT4 "touch.size.calibration: area\n");
3586         break;
3587     default:
3588         ALOG_ASSERT(false);
3589     }
3590
3591     if (mCalibration.haveSizeScale) {
3592         dump.appendFormat(INDENT4 "touch.size.scale: %0.3f\n",
3593                 mCalibration.sizeScale);
3594     }
3595
3596     if (mCalibration.haveSizeBias) {
3597         dump.appendFormat(INDENT4 "touch.size.bias: %0.3f\n",
3598                 mCalibration.sizeBias);
3599     }
3600
3601     if (mCalibration.haveSizeIsSummed) {
3602         dump.appendFormat(INDENT4 "touch.size.isSummed: %s\n",
3603                 toString(mCalibration.sizeIsSummed));
3604     }
3605
3606     // Pressure
3607     switch (mCalibration.pressureCalibration) {
3608     case Calibration::PRESSURE_CALIBRATION_NONE:
3609         dump.append(INDENT4 "touch.pressure.calibration: none\n");
3610         break;
3611     case Calibration::PRESSURE_CALIBRATION_PHYSICAL:
3612         dump.append(INDENT4 "touch.pressure.calibration: physical\n");
3613         break;
3614     case Calibration::PRESSURE_CALIBRATION_AMPLITUDE:
3615         dump.append(INDENT4 "touch.pressure.calibration: amplitude\n");
3616         break;
3617     default:
3618         ALOG_ASSERT(false);
3619     }
3620
3621     if (mCalibration.havePressureScale) {
3622         dump.appendFormat(INDENT4 "touch.pressure.scale: %0.3f\n",
3623                 mCalibration.pressureScale);
3624     }
3625
3626     // Orientation
3627     switch (mCalibration.orientationCalibration) {
3628     case Calibration::ORIENTATION_CALIBRATION_NONE:
3629         dump.append(INDENT4 "touch.orientation.calibration: none\n");
3630         break;
3631     case Calibration::ORIENTATION_CALIBRATION_INTERPOLATED:
3632         dump.append(INDENT4 "touch.orientation.calibration: interpolated\n");
3633         break;
3634     case Calibration::ORIENTATION_CALIBRATION_VECTOR:
3635         dump.append(INDENT4 "touch.orientation.calibration: vector\n");
3636         break;
3637     default:
3638         ALOG_ASSERT(false);
3639     }
3640
3641     // Distance
3642     switch (mCalibration.distanceCalibration) {
3643     case Calibration::DISTANCE_CALIBRATION_NONE:
3644         dump.append(INDENT4 "touch.distance.calibration: none\n");
3645         break;
3646     case Calibration::DISTANCE_CALIBRATION_SCALED:
3647         dump.append(INDENT4 "touch.distance.calibration: scaled\n");
3648         break;
3649     default:
3650         ALOG_ASSERT(false);
3651     }
3652
3653     if (mCalibration.haveDistanceScale) {
3654         dump.appendFormat(INDENT4 "touch.distance.scale: %0.3f\n",
3655                 mCalibration.distanceScale);
3656     }
3657
3658     switch (mCalibration.coverageCalibration) {
3659     case Calibration::COVERAGE_CALIBRATION_NONE:
3660         dump.append(INDENT4 "touch.coverage.calibration: none\n");
3661         break;
3662     case Calibration::COVERAGE_CALIBRATION_BOX:
3663         dump.append(INDENT4 "touch.coverage.calibration: box\n");
3664         break;
3665     default:
3666         ALOG_ASSERT(false);
3667     }
3668 }
3669
3670 void TouchInputMapper::dumpAffineTransformation(String8& dump) {
3671     dump.append(INDENT3 "Affine Transformation:\n");
3672
3673     dump.appendFormat(INDENT4 "X scale: %0.3f\n", mAffineTransform.x_scale);
3674     dump.appendFormat(INDENT4 "X ymix: %0.3f\n", mAffineTransform.x_ymix);
3675     dump.appendFormat(INDENT4 "X offset: %0.3f\n", mAffineTransform.x_offset);
3676     dump.appendFormat(INDENT4 "Y xmix: %0.3f\n", mAffineTransform.y_xmix);
3677     dump.appendFormat(INDENT4 "Y scale: %0.3f\n", mAffineTransform.y_scale);
3678     dump.appendFormat(INDENT4 "Y offset: %0.3f\n", mAffineTransform.y_offset);
3679 }
3680
3681 void TouchInputMapper::updateAffineTransformation() {
3682     mAffineTransform = getPolicy()->getTouchAffineTransformation(mDevice->getDescriptor(),
3683             mSurfaceOrientation);
3684 }
3685
3686 void TouchInputMapper::reset(nsecs_t when) {
3687     mCursorButtonAccumulator.reset(getDevice());
3688     mCursorScrollAccumulator.reset(getDevice());
3689     mTouchButtonAccumulator.reset(getDevice());
3690
3691     mPointerVelocityControl.reset();
3692     mWheelXVelocityControl.reset();
3693     mWheelYVelocityControl.reset();
3694
3695     mCurrentRawPointerData.clear();
3696     mLastRawPointerData.clear();
3697     mCurrentCookedPointerData.clear();
3698     mLastCookedPointerData.clear();
3699     mCurrentButtonState = 0;
3700     mLastButtonState = 0;
3701     mCurrentRawVScroll = 0;
3702     mCurrentRawHScroll = 0;
3703     mCurrentFingerIdBits.clear();
3704     mLastFingerIdBits.clear();
3705     mCurrentStylusIdBits.clear();
3706     mLastStylusIdBits.clear();
3707     mCurrentMouseIdBits.clear();
3708     mLastMouseIdBits.clear();
3709     mPointerUsage = POINTER_USAGE_NONE;
3710     mSentHoverEnter = false;
3711     mDownTime = 0;
3712
3713     mCurrentVirtualKey.down = false;
3714
3715     mPointerGesture.reset();
3716     mPointerSimple.reset();
3717
3718     if (mPointerController != NULL) {
3719         mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
3720         mPointerController->clearSpots();
3721     }
3722
3723     InputMapper::reset(when);
3724 }
3725
3726 void TouchInputMapper::process(const RawEvent* rawEvent) {
3727     mCursorButtonAccumulator.process(rawEvent);
3728     mCursorScrollAccumulator.process(rawEvent);
3729     mTouchButtonAccumulator.process(rawEvent);
3730
3731     if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
3732         sync(rawEvent->when);
3733     }
3734 }
3735
3736 void TouchInputMapper::sync(nsecs_t when) {
3737     // Sync button state.
3738     mCurrentButtonState = mTouchButtonAccumulator.getButtonState()
3739             | mCursorButtonAccumulator.getButtonState();
3740
3741     // Sync scroll state.
3742     mCurrentRawVScroll = mCursorScrollAccumulator.getRelativeVWheel();
3743     mCurrentRawHScroll = mCursorScrollAccumulator.getRelativeHWheel();
3744     mCursorScrollAccumulator.finishSync();
3745
3746     // Sync touch state.
3747     bool havePointerIds = true;
3748     mCurrentRawPointerData.clear();
3749     syncTouch(when, &havePointerIds);
3750
3751 #if DEBUG_RAW_EVENTS
3752     if (!havePointerIds) {
3753         ALOGD("syncTouch: pointerCount %d -> %d, no pointer ids",
3754                 mLastRawPointerData.pointerCount,
3755                 mCurrentRawPointerData.pointerCount);
3756     } else {
3757         ALOGD("syncTouch: pointerCount %d -> %d, touching ids 0x%08x -> 0x%08x, "
3758                 "hovering ids 0x%08x -> 0x%08x",
3759                 mLastRawPointerData.pointerCount,
3760                 mCurrentRawPointerData.pointerCount,
3761                 mLastRawPointerData.touchingIdBits.value,
3762                 mCurrentRawPointerData.touchingIdBits.value,
3763                 mLastRawPointerData.hoveringIdBits.value,
3764                 mCurrentRawPointerData.hoveringIdBits.value);
3765     }
3766 #endif
3767
3768     // Reset state that we will compute below.
3769     mCurrentFingerIdBits.clear();
3770     mCurrentStylusIdBits.clear();
3771     mCurrentMouseIdBits.clear();
3772     mCurrentCookedPointerData.clear();
3773
3774     if (mDeviceMode == DEVICE_MODE_DISABLED) {
3775         // Drop all input if the device is disabled.
3776         mCurrentRawPointerData.clear();
3777         mCurrentButtonState = 0;
3778     } else {
3779         // Preprocess pointer data.
3780         if (!havePointerIds) {
3781             assignPointerIds();
3782         }
3783
3784         // Handle policy on initial down or hover events.
3785         uint32_t policyFlags = 0;
3786         bool initialDown = mLastRawPointerData.pointerCount == 0
3787                 && mCurrentRawPointerData.pointerCount != 0;
3788         bool buttonsPressed = mCurrentButtonState & ~mLastButtonState;
3789         if (initialDown || buttonsPressed) {
3790             // If this is a touch screen, hide the pointer on an initial down.
3791             if (mDeviceMode == DEVICE_MODE_DIRECT) {
3792                 getContext()->fadePointer();
3793             }
3794
3795             if (mParameters.wake) {
3796                 policyFlags |= POLICY_FLAG_WAKE;
3797             }
3798         }
3799
3800         // Synthesize key down from raw buttons if needed.
3801         synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, getDeviceId(), mSource,
3802                 policyFlags, mLastButtonState, mCurrentButtonState);
3803
3804         // Consume raw off-screen touches before cooking pointer data.
3805         // If touches are consumed, subsequent code will not receive any pointer data.
3806         if (consumeRawTouches(when, policyFlags)) {
3807             mCurrentRawPointerData.clear();
3808         }
3809
3810         // Cook pointer data.  This call populates the mCurrentCookedPointerData structure
3811         // with cooked pointer data that has the same ids and indices as the raw data.
3812         // The following code can use either the raw or cooked data, as needed.
3813         cookPointerData();
3814
3815         // Dispatch the touches either directly or by translation through a pointer on screen.
3816         if (mDeviceMode == DEVICE_MODE_POINTER) {
3817             for (BitSet32 idBits(mCurrentRawPointerData.touchingIdBits); !idBits.isEmpty(); ) {
3818                 uint32_t id = idBits.clearFirstMarkedBit();
3819                 const RawPointerData::Pointer& pointer = mCurrentRawPointerData.pointerForId(id);
3820                 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS
3821                         || pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
3822                     mCurrentStylusIdBits.markBit(id);
3823                 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_FINGER
3824                         || pointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
3825                     mCurrentFingerIdBits.markBit(id);
3826                 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_MOUSE) {
3827                     mCurrentMouseIdBits.markBit(id);
3828                 }
3829             }
3830             for (BitSet32 idBits(mCurrentRawPointerData.hoveringIdBits); !idBits.isEmpty(); ) {
3831                 uint32_t id = idBits.clearFirstMarkedBit();
3832                 const RawPointerData::Pointer& pointer = mCurrentRawPointerData.pointerForId(id);
3833                 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS
3834                         || pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
3835                     mCurrentStylusIdBits.markBit(id);
3836                 }
3837             }
3838
3839             // Stylus takes precedence over all tools, then mouse, then finger.
3840             PointerUsage pointerUsage = mPointerUsage;
3841             if (!mCurrentStylusIdBits.isEmpty()) {
3842                 mCurrentMouseIdBits.clear();
3843                 mCurrentFingerIdBits.clear();
3844                 pointerUsage = POINTER_USAGE_STYLUS;
3845             } else if (!mCurrentMouseIdBits.isEmpty()) {
3846                 mCurrentFingerIdBits.clear();
3847                 pointerUsage = POINTER_USAGE_MOUSE;
3848             } else if (!mCurrentFingerIdBits.isEmpty() || isPointerDown(mCurrentButtonState)) {
3849                 pointerUsage = POINTER_USAGE_GESTURES;
3850             }
3851
3852             dispatchPointerUsage(when, policyFlags, pointerUsage);
3853         } else {
3854             if (mDeviceMode == DEVICE_MODE_DIRECT
3855                     && mConfig.showTouches && mPointerController != NULL) {
3856                 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_SPOT);
3857                 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
3858
3859                 mPointerController->setButtonState(mCurrentButtonState);
3860                 mPointerController->setSpots(mCurrentCookedPointerData.pointerCoords,
3861                         mCurrentCookedPointerData.idToIndex,
3862                         mCurrentCookedPointerData.touchingIdBits);
3863             }
3864
3865             dispatchHoverExit(when, policyFlags);
3866             dispatchTouches(when, policyFlags);
3867             dispatchHoverEnterAndMove(when, policyFlags);
3868         }
3869
3870         // Synthesize key up from raw buttons if needed.
3871         synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, getDeviceId(), mSource,
3872                 policyFlags, mLastButtonState, mCurrentButtonState);
3873     }
3874
3875     // Copy current touch to last touch in preparation for the next cycle.
3876     mLastRawPointerData.copyFrom(mCurrentRawPointerData);
3877     mLastCookedPointerData.copyFrom(mCurrentCookedPointerData);
3878     mLastButtonState = mCurrentButtonState;
3879     mLastFingerIdBits = mCurrentFingerIdBits;
3880     mLastStylusIdBits = mCurrentStylusIdBits;
3881     mLastMouseIdBits = mCurrentMouseIdBits;
3882
3883     // Clear some transient state.
3884     mCurrentRawVScroll = 0;
3885     mCurrentRawHScroll = 0;
3886 }
3887
3888 void TouchInputMapper::timeoutExpired(nsecs_t when) {
3889     if (mDeviceMode == DEVICE_MODE_POINTER) {
3890         if (mPointerUsage == POINTER_USAGE_GESTURES) {
3891             dispatchPointerGestures(when, 0 /*policyFlags*/, true /*isTimeout*/);
3892         }
3893     }
3894 }
3895
3896 bool TouchInputMapper::consumeRawTouches(nsecs_t when, uint32_t policyFlags) {
3897     // Check for release of a virtual key.
3898     if (mCurrentVirtualKey.down) {
3899         if (mCurrentRawPointerData.touchingIdBits.isEmpty()) {
3900             // Pointer went up while virtual key was down.
3901             mCurrentVirtualKey.down = false;
3902             if (!mCurrentVirtualKey.ignored) {
3903 #if DEBUG_VIRTUAL_KEYS
3904                 ALOGD("VirtualKeys: Generating key up: keyCode=%d, scanCode=%d",
3905                         mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
3906 #endif
3907                 dispatchVirtualKey(when, policyFlags,
3908                         AKEY_EVENT_ACTION_UP,
3909                         AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
3910             }
3911             return true;
3912         }
3913
3914         if (mCurrentRawPointerData.touchingIdBits.count() == 1) {
3915             uint32_t id = mCurrentRawPointerData.touchingIdBits.firstMarkedBit();
3916             const RawPointerData::Pointer& pointer = mCurrentRawPointerData.pointerForId(id);
3917             const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
3918             if (virtualKey && virtualKey->keyCode == mCurrentVirtualKey.keyCode) {
3919                 // Pointer is still within the space of the virtual key.
3920                 return true;
3921             }
3922         }
3923
3924         // Pointer left virtual key area or another pointer also went down.
3925         // Send key cancellation but do not consume the touch yet.
3926         // This is useful when the user swipes through from the virtual key area
3927         // into the main display surface.
3928         mCurrentVirtualKey.down = false;
3929         if (!mCurrentVirtualKey.ignored) {
3930 #if DEBUG_VIRTUAL_KEYS
3931             ALOGD("VirtualKeys: Canceling key: keyCode=%d, scanCode=%d",
3932                     mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
3933 #endif
3934             dispatchVirtualKey(when, policyFlags,
3935                     AKEY_EVENT_ACTION_UP,
3936                     AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY
3937                             | AKEY_EVENT_FLAG_CANCELED);
3938         }
3939     }
3940
3941     if (mLastRawPointerData.touchingIdBits.isEmpty()
3942             && !mCurrentRawPointerData.touchingIdBits.isEmpty()) {
3943         // Pointer just went down.  Check for virtual key press or off-screen touches.
3944         uint32_t id = mCurrentRawPointerData.touchingIdBits.firstMarkedBit();
3945         const RawPointerData::Pointer& pointer = mCurrentRawPointerData.pointerForId(id);
3946         if (!isPointInsideSurface(pointer.x, pointer.y)) {
3947             // If exactly one pointer went down, check for virtual key hit.
3948             // Otherwise we will drop the entire stroke.
3949             if (mCurrentRawPointerData.touchingIdBits.count() == 1) {
3950                 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
3951                 if (virtualKey) {
3952                     mCurrentVirtualKey.down = true;
3953                     mCurrentVirtualKey.downTime = when;
3954                     mCurrentVirtualKey.keyCode = virtualKey->keyCode;
3955                     mCurrentVirtualKey.scanCode = virtualKey->scanCode;
3956                     mCurrentVirtualKey.ignored = mContext->shouldDropVirtualKey(
3957                             when, getDevice(), virtualKey->keyCode, virtualKey->scanCode);
3958
3959                     if (!mCurrentVirtualKey.ignored) {
3960 #if DEBUG_VIRTUAL_KEYS
3961                         ALOGD("VirtualKeys: Generating key down: keyCode=%d, scanCode=%d",
3962                                 mCurrentVirtualKey.keyCode,
3963                                 mCurrentVirtualKey.scanCode);
3964 #endif
3965                         dispatchVirtualKey(when, policyFlags,
3966                                 AKEY_EVENT_ACTION_DOWN,
3967                                 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
3968                     }
3969                 }
3970             }
3971             return true;
3972         }
3973     }
3974
3975     // Disable all virtual key touches that happen within a short time interval of the
3976     // most recent touch within the screen area.  The idea is to filter out stray
3977     // virtual key presses when interacting with the touch screen.
3978     //
3979     // Problems we're trying to solve:
3980     //
3981     // 1. While scrolling a list or dragging the window shade, the user swipes down into a
3982     //    virtual key area that is implemented by a separate touch panel and accidentally
3983     //    triggers a virtual key.
3984     //
3985     // 2. While typing in the on screen keyboard, the user taps slightly outside the screen
3986     //    area and accidentally triggers a virtual key.  This often happens when virtual keys
3987     //    are layed out below the screen near to where the on screen keyboard's space bar
3988     //    is displayed.
3989     if (mConfig.virtualKeyQuietTime > 0 && !mCurrentRawPointerData.touchingIdBits.isEmpty()) {
3990         mContext->disableVirtualKeysUntil(when + mConfig.virtualKeyQuietTime);
3991     }
3992     return false;
3993 }
3994
3995 void TouchInputMapper::dispatchVirtualKey(nsecs_t when, uint32_t policyFlags,
3996         int32_t keyEventAction, int32_t keyEventFlags) {
3997     int32_t keyCode = mCurrentVirtualKey.keyCode;
3998     int32_t scanCode = mCurrentVirtualKey.scanCode;
3999     nsecs_t downTime = mCurrentVirtualKey.downTime;
4000     int32_t metaState = mContext->getGlobalMetaState();
4001     policyFlags |= POLICY_FLAG_VIRTUAL;
4002
4003     NotifyKeyArgs args(when, getDeviceId(), AINPUT_SOURCE_KEYBOARD, policyFlags,
4004             keyEventAction, keyEventFlags, keyCode, scanCode, metaState, downTime);
4005     getListener()->notifyKey(&args);
4006 }
4007
4008 void TouchInputMapper::dispatchTouches(nsecs_t when, uint32_t policyFlags) {
4009     BitSet32 currentIdBits = mCurrentCookedPointerData.touchingIdBits;
4010     BitSet32 lastIdBits = mLastCookedPointerData.touchingIdBits;
4011     int32_t metaState = getContext()->getGlobalMetaState();
4012     int32_t buttonState = mCurrentButtonState;
4013
4014     if (currentIdBits == lastIdBits) {
4015         if (!currentIdBits.isEmpty()) {
4016             // No pointer id changes so this is a move event.
4017             // The listener takes care of batching moves so we don't have to deal with that here.
4018             dispatchMotion(when, policyFlags, mSource,
4019                     AMOTION_EVENT_ACTION_MOVE, 0, metaState, buttonState,
4020                     AMOTION_EVENT_EDGE_FLAG_NONE,
4021                     mCurrentCookedPointerData.pointerProperties,
4022                     mCurrentCookedPointerData.pointerCoords,
4023                     mCurrentCookedPointerData.idToIndex,
4024                     currentIdBits, -1,
4025                     mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4026         }
4027     } else {
4028         // There may be pointers going up and pointers going down and pointers moving
4029         // all at the same time.
4030         BitSet32 upIdBits(lastIdBits.value & ~currentIdBits.value);
4031         BitSet32 downIdBits(currentIdBits.value & ~lastIdBits.value);
4032         BitSet32 moveIdBits(lastIdBits.value & currentIdBits.value);
4033         BitSet32 dispatchedIdBits(lastIdBits.value);
4034
4035         // Update last coordinates of pointers that have moved so that we observe the new
4036         // pointer positions at the same time as other pointers that have just gone up.
4037         bool moveNeeded = updateMovedPointers(
4038                 mCurrentCookedPointerData.pointerProperties,
4039                 mCurrentCookedPointerData.pointerCoords,
4040                 mCurrentCookedPointerData.idToIndex,
4041                 mLastCookedPointerData.pointerProperties,
4042                 mLastCookedPointerData.pointerCoords,
4043                 mLastCookedPointerData.idToIndex,
4044                 moveIdBits);
4045         if (buttonState != mLastButtonState) {
4046             moveNeeded = true;
4047         }
4048
4049         // Dispatch pointer up events.
4050         while (!upIdBits.isEmpty()) {
4051             uint32_t upId = upIdBits.clearFirstMarkedBit();
4052
4053             dispatchMotion(when, policyFlags, mSource,
4054                     AMOTION_EVENT_ACTION_POINTER_UP, 0, metaState, buttonState, 0,
4055                     mLastCookedPointerData.pointerProperties,
4056                     mLastCookedPointerData.pointerCoords,
4057                     mLastCookedPointerData.idToIndex,
4058                     dispatchedIdBits, upId,
4059                     mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4060             dispatchedIdBits.clearBit(upId);
4061         }
4062
4063         // Dispatch move events if any of the remaining pointers moved from their old locations.
4064         // Although applications receive new locations as part of individual pointer up
4065         // events, they do not generally handle them except when presented in a move event.
4066         if (moveNeeded) {
4067             ALOG_ASSERT(moveIdBits.value == dispatchedIdBits.value);
4068             dispatchMotion(when, policyFlags, mSource,
4069                     AMOTION_EVENT_ACTION_MOVE, 0, metaState, buttonState, 0,
4070                     mCurrentCookedPointerData.pointerProperties,
4071                     mCurrentCookedPointerData.pointerCoords,
4072                     mCurrentCookedPointerData.idToIndex,
4073                     dispatchedIdBits, -1,
4074                     mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4075         }
4076
4077         // Dispatch pointer down events using the new pointer locations.
4078         while (!downIdBits.isEmpty()) {
4079             uint32_t downId = downIdBits.clearFirstMarkedBit();
4080             dispatchedIdBits.markBit(downId);
4081
4082             if (dispatchedIdBits.count() == 1) {
4083                 // First pointer is going down.  Set down time.
4084                 mDownTime = when;
4085             }
4086
4087             dispatchMotion(when, policyFlags, mSource,
4088                     AMOTION_EVENT_ACTION_POINTER_DOWN, 0, metaState, buttonState, 0,
4089                     mCurrentCookedPointerData.pointerProperties,
4090                     mCurrentCookedPointerData.pointerCoords,
4091                     mCurrentCookedPointerData.idToIndex,
4092                     dispatchedIdBits, downId,
4093                     mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4094         }
4095     }
4096 }
4097
4098 void TouchInputMapper::dispatchHoverExit(nsecs_t when, uint32_t policyFlags) {
4099     if (mSentHoverEnter &&
4100             (mCurrentCookedPointerData.hoveringIdBits.isEmpty()
4101                     || !mCurrentCookedPointerData.touchingIdBits.isEmpty())) {
4102         int32_t metaState = getContext()->getGlobalMetaState();
4103         dispatchMotion(when, policyFlags, mSource,
4104                 AMOTION_EVENT_ACTION_HOVER_EXIT, 0, metaState, mLastButtonState, 0,
4105                 mLastCookedPointerData.pointerProperties,
4106                 mLastCookedPointerData.pointerCoords,
4107                 mLastCookedPointerData.idToIndex,
4108                 mLastCookedPointerData.hoveringIdBits, -1,
4109                 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4110         mSentHoverEnter = false;
4111     }
4112 }
4113
4114 void TouchInputMapper::dispatchHoverEnterAndMove(nsecs_t when, uint32_t policyFlags) {
4115     if (mCurrentCookedPointerData.touchingIdBits.isEmpty()
4116             && !mCurrentCookedPointerData.hoveringIdBits.isEmpty()) {
4117         int32_t metaState = getContext()->getGlobalMetaState();
4118         if (!mSentHoverEnter) {
4119             dispatchMotion(when, policyFlags, mSource,
4120                     AMOTION_EVENT_ACTION_HOVER_ENTER, 0, metaState, mCurrentButtonState, 0,
4121                     mCurrentCookedPointerData.pointerProperties,
4122                     mCurrentCookedPointerData.pointerCoords,
4123                     mCurrentCookedPointerData.idToIndex,
4124                     mCurrentCookedPointerData.hoveringIdBits, -1,
4125                     mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4126             mSentHoverEnter = true;
4127         }
4128
4129         dispatchMotion(when, policyFlags, mSource,
4130                 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, metaState, mCurrentButtonState, 0,
4131                 mCurrentCookedPointerData.pointerProperties,
4132                 mCurrentCookedPointerData.pointerCoords,
4133                 mCurrentCookedPointerData.idToIndex,
4134                 mCurrentCookedPointerData.hoveringIdBits, -1,
4135                 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4136     }
4137 }
4138
4139 void TouchInputMapper::cookPointerData() {
4140     uint32_t currentPointerCount = mCurrentRawPointerData.pointerCount;
4141
4142     mCurrentCookedPointerData.clear();
4143     mCurrentCookedPointerData.pointerCount = currentPointerCount;
4144     mCurrentCookedPointerData.hoveringIdBits = mCurrentRawPointerData.hoveringIdBits;
4145     mCurrentCookedPointerData.touchingIdBits = mCurrentRawPointerData.touchingIdBits;
4146
4147     // Walk through the the active pointers and map device coordinates onto
4148     // surface coordinates and adjust for display orientation.
4149     for (uint32_t i = 0; i < currentPointerCount; i++) {
4150         const RawPointerData::Pointer& in = mCurrentRawPointerData.pointers[i];
4151
4152         // Size
4153         float touchMajor, touchMinor, toolMajor, toolMinor, size;
4154         switch (mCalibration.sizeCalibration) {
4155         case Calibration::SIZE_CALIBRATION_GEOMETRIC:
4156         case Calibration::SIZE_CALIBRATION_DIAMETER:
4157         case Calibration::SIZE_CALIBRATION_BOX:
4158         case Calibration::SIZE_CALIBRATION_AREA:
4159             if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.toolMajor.valid) {
4160                 touchMajor = in.touchMajor;
4161                 touchMinor = mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
4162                 toolMajor = in.toolMajor;
4163                 toolMinor = mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
4164                 size = mRawPointerAxes.touchMinor.valid
4165                         ? avg(in.touchMajor, in.touchMinor) : in.touchMajor;
4166             } else if (mRawPointerAxes.touchMajor.valid) {
4167                 toolMajor = touchMajor = in.touchMajor;
4168                 toolMinor = touchMinor = mRawPointerAxes.touchMinor.valid
4169                         ? in.touchMinor : in.touchMajor;
4170                 size = mRawPointerAxes.touchMinor.valid
4171                         ? avg(in.touchMajor, in.touchMinor) : in.touchMajor;
4172             } else if (mRawPointerAxes.toolMajor.valid) {
4173                 touchMajor = toolMajor = in.toolMajor;
4174                 touchMinor = toolMinor = mRawPointerAxes.toolMinor.valid
4175                         ? in.toolMinor : in.toolMajor;
4176                 size = mRawPointerAxes.toolMinor.valid
4177                         ? avg(in.toolMajor, in.toolMinor) : in.toolMajor;
4178             } else {
4179                 ALOG_ASSERT(false, "No touch or tool axes.  "
4180                         "Size calibration should have been resolved to NONE.");
4181                 touchMajor = 0;
4182                 touchMinor = 0;
4183                 toolMajor = 0;
4184                 toolMinor = 0;
4185                 size = 0;
4186             }
4187
4188             if (mCalibration.haveSizeIsSummed && mCalibration.sizeIsSummed) {
4189                 uint32_t touchingCount = mCurrentRawPointerData.touchingIdBits.count();
4190                 if (touchingCount > 1) {
4191                     touchMajor /= touchingCount;
4192                     touchMinor /= touchingCount;
4193                     toolMajor /= touchingCount;
4194                     toolMinor /= touchingCount;
4195                     size /= touchingCount;
4196                 }
4197             }
4198
4199             if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_GEOMETRIC) {
4200                 touchMajor *= mGeometricScale;
4201                 touchMinor *= mGeometricScale;
4202                 toolMajor *= mGeometricScale;
4203                 toolMinor *= mGeometricScale;
4204             } else if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_AREA) {
4205                 touchMajor = touchMajor > 0 ? sqrtf(touchMajor) : 0;
4206                 touchMinor = touchMajor;
4207                 toolMajor = toolMajor > 0 ? sqrtf(toolMajor) : 0;
4208                 toolMinor = toolMajor;
4209             } else if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_DIAMETER) {
4210                 touchMinor = touchMajor;
4211                 toolMinor = toolMajor;
4212             }
4213
4214             mCalibration.applySizeScaleAndBias(&touchMajor);
4215             mCalibration.applySizeScaleAndBias(&touchMinor);
4216             mCalibration.applySizeScaleAndBias(&toolMajor);
4217             mCalibration.applySizeScaleAndBias(&toolMinor);
4218             size *= mSizeScale;
4219             break;
4220         default:
4221             touchMajor = 0;
4222             touchMinor = 0;
4223             toolMajor = 0;
4224             toolMinor = 0;
4225             size = 0;
4226             break;
4227         }
4228
4229         // Pressure
4230         float pressure;
4231         switch (mCalibration.pressureCalibration) {
4232         case Calibration::PRESSURE_CALIBRATION_PHYSICAL:
4233         case Calibration::PRESSURE_CALIBRATION_AMPLITUDE:
4234             pressure = in.pressure * mPressureScale;
4235             break;
4236         default:
4237             pressure = in.isHovering ? 0 : 1;
4238             break;
4239         }
4240
4241         // Tilt and Orientation
4242         float tilt;
4243         float orientation;
4244         if (mHaveTilt) {
4245             float tiltXAngle = (in.tiltX - mTiltXCenter) * mTiltXScale;
4246             float tiltYAngle = (in.tiltY - mTiltYCenter) * mTiltYScale;
4247             orientation = atan2f(-sinf(tiltXAngle), sinf(tiltYAngle));
4248             tilt = acosf(cosf(tiltXAngle) * cosf(tiltYAngle));
4249         } else {
4250             tilt = 0;
4251
4252             switch (mCalibration.orientationCalibration) {
4253             case Calibration::ORIENTATION_CALIBRATION_INTERPOLATED:
4254                 orientation = in.orientation * mOrientationScale;
4255                 break;
4256             case Calibration::ORIENTATION_CALIBRATION_VECTOR: {
4257                 int32_t c1 = signExtendNybble((in.orientation & 0xf0) >> 4);
4258                 int32_t c2 = signExtendNybble(in.orientation & 0x0f);
4259                 if (c1 != 0 || c2 != 0) {
4260                     orientation = atan2f(c1, c2) * 0.5f;
4261                     float confidence = hypotf(c1, c2);
4262                     float scale = 1.0f + confidence / 16.0f;
4263                     touchMajor *= scale;
4264                     touchMinor /= scale;
4265                     toolMajor *= scale;
4266                     toolMinor /= scale;
4267                 } else {
4268                     orientation = 0;
4269                 }
4270                 break;
4271             }
4272             default:
4273                 orientation = 0;
4274             }
4275         }
4276
4277         // Distance
4278         float distance;
4279         switch (mCalibration.distanceCalibration) {
4280         case Calibration::DISTANCE_CALIBRATION_SCALED:
4281             distance = in.distance * mDistanceScale;
4282             break;
4283         default:
4284             distance = 0;
4285         }
4286
4287         // Coverage
4288         int32_t rawLeft, rawTop, rawRight, rawBottom;
4289         switch (mCalibration.coverageCalibration) {
4290         case Calibration::COVERAGE_CALIBRATION_BOX:
4291             rawLeft = (in.toolMinor & 0xffff0000) >> 16;
4292             rawRight = in.toolMinor & 0x0000ffff;
4293             rawBottom = in.toolMajor & 0x0000ffff;
4294             rawTop = (in.toolMajor & 0xffff0000) >> 16;
4295             break;
4296         default:
4297             rawLeft = rawTop = rawRight = rawBottom = 0;
4298             break;
4299         }
4300
4301         // Adjust X,Y coords for device calibration
4302         // TODO: Adjust coverage coords?
4303         float xTransformed = in.x, yTransformed = in.y;
4304         mAffineTransform.applyTo(xTransformed, yTransformed);
4305
4306         // Adjust X, Y, and coverage coords for surface orientation.
4307         float x, y;
4308         float left, top, right, bottom;
4309
4310         switch (mSurfaceOrientation) {
4311         case DISPLAY_ORIENTATION_90:
4312             x = float(yTransformed - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
4313             y = float(mRawPointerAxes.x.maxValue - xTransformed) * mXScale + mXTranslate;
4314             left = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
4315             right = float(rawBottom- mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
4316             bottom = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale + mXTranslate;
4317             top = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale + mXTranslate;
4318             orientation -= M_PI_2;
4319             if (orientation < mOrientedRanges.orientation.min) {
4320                 orientation += (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
4321             }
4322             break;
4323         case DISPLAY_ORIENTATION_180:
4324             x = float(mRawPointerAxes.x.maxValue - xTransformed) * mXScale + mXTranslate;
4325             y = float(mRawPointerAxes.y.maxValue - yTransformed) * mYScale + mYTranslate;
4326             left = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale + mXTranslate;
4327             right = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale + mXTranslate;
4328             bottom = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale + mYTranslate;
4329             top = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale + mYTranslate;
4330             orientation -= M_PI;
4331             if (orientation < mOrientedRanges.orientation.min) {
4332                 orientation += (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
4333             }
4334             break;
4335         case DISPLAY_ORIENTATION_270:
4336             x = float(mRawPointerAxes.y.maxValue - yTransformed) * mYScale + mYTranslate;
4337             y = float(xTransformed - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
4338             left = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale + mYTranslate;
4339             right = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale + mYTranslate;
4340             bottom = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
4341             top = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
4342             orientation += M_PI_2;
4343             if (orientation > mOrientedRanges.orientation.max) {
4344                 orientation -= (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
4345             }
4346             break;
4347         default:
4348             x = float(xTransformed - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
4349             y = float(yTransformed - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
4350             left = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
4351             right = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
4352             bottom = float(rawBottom - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
4353             top = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
4354             break;
4355         }
4356
4357         // Write output coords.
4358         PointerCoords& out = mCurrentCookedPointerData.pointerCoords[i];
4359         out.clear();
4360         out.setAxisValue(AMOTION_EVENT_AXIS_X, x);
4361         out.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
4362         out.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
4363         out.setAxisValue(AMOTION_EVENT_AXIS_SIZE, size);
4364         out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR, touchMajor);
4365         out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR, touchMinor);
4366         out.setAxisValue(AMOTION_EVENT_AXIS_ORIENTATION, orientation);
4367         out.setAxisValue(AMOTION_EVENT_AXIS_TILT, tilt);
4368         out.setAxisValue(AMOTION_EVENT_AXIS_DISTANCE, distance);
4369         if (mCalibration.coverageCalibration == Calibration::COVERAGE_CALIBRATION_BOX) {
4370             out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_1, left);
4371             out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_2, top);
4372             out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_3, right);
4373             out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_4, bottom);
4374         } else {
4375             out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR, toolMajor);
4376             out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR, toolMinor);
4377         }
4378
4379         // Write output properties.
4380         PointerProperties& properties = mCurrentCookedPointerData.pointerProperties[i];
4381         uint32_t id = in.id;
4382         properties.clear();
4383         properties.id = id;
4384         properties.toolType = in.toolType;
4385
4386         // Write id index.
4387         mCurrentCookedPointerData.idToIndex[id] = i;
4388     }
4389 }
4390
4391 void TouchInputMapper::dispatchPointerUsage(nsecs_t when, uint32_t policyFlags,
4392         PointerUsage pointerUsage) {
4393     if (pointerUsage != mPointerUsage) {
4394         abortPointerUsage(when, policyFlags);
4395         mPointerUsage = pointerUsage;
4396     }
4397
4398     switch (mPointerUsage) {
4399     case POINTER_USAGE_GESTURES:
4400         dispatchPointerGestures(when, policyFlags, false /*isTimeout*/);
4401         break;
4402     case POINTER_USAGE_STYLUS:
4403         dispatchPointerStylus(when, policyFlags);
4404         break;
4405     case POINTER_USAGE_MOUSE:
4406         dispatchPointerMouse(when, policyFlags);
4407         break;
4408     default:
4409         break;
4410     }
4411 }
4412
4413 void TouchInputMapper::abortPointerUsage(nsecs_t when, uint32_t policyFlags) {
4414     switch (mPointerUsage) {
4415     case POINTER_USAGE_GESTURES:
4416         abortPointerGestures(when, policyFlags);
4417         break;
4418     case POINTER_USAGE_STYLUS:
4419         abortPointerStylus(when, policyFlags);
4420         break;
4421     case POINTER_USAGE_MOUSE:
4422         abortPointerMouse(when, policyFlags);
4423         break;
4424     default:
4425         break;
4426     }
4427
4428     mPointerUsage = POINTER_USAGE_NONE;
4429 }
4430
4431 void TouchInputMapper::dispatchPointerGestures(nsecs_t when, uint32_t policyFlags,
4432         bool isTimeout) {
4433     // Update current gesture coordinates.
4434     bool cancelPreviousGesture, finishPreviousGesture;
4435     bool sendEvents = preparePointerGestures(when,
4436             &cancelPreviousGesture, &finishPreviousGesture, isTimeout);
4437     if (!sendEvents) {
4438         return;
4439     }
4440     if (finishPreviousGesture) {
4441         cancelPreviousGesture = false;
4442     }
4443
4444     // Update the pointer presentation and spots.
4445     if (mParameters.gestureMode == Parameters::GESTURE_MODE_SPOTS) {
4446         mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_SPOT);
4447         if (finishPreviousGesture || cancelPreviousGesture) {
4448             mPointerController->clearSpots();
4449         }
4450         mPointerController->setSpots(mPointerGesture.currentGestureCoords,
4451                 mPointerGesture.currentGestureIdToIndex,
4452                 mPointerGesture.currentGestureIdBits);
4453     } else {
4454         mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_POINTER);
4455     }
4456
4457     // Show or hide the pointer if needed.
4458     switch (mPointerGesture.currentGestureMode) {
4459     case PointerGesture::NEUTRAL:
4460     case PointerGesture::QUIET:
4461         if (mParameters.gestureMode == Parameters::GESTURE_MODE_SPOTS
4462                 && (mPointerGesture.lastGestureMode == PointerGesture::SWIPE
4463                         || mPointerGesture.lastGestureMode == PointerGesture::FREEFORM)) {
4464             // Remind the user of where the pointer is after finishing a gesture with spots.
4465             mPointerController->unfade(PointerControllerInterface::TRANSITION_GRADUAL);
4466         }
4467         break;
4468     case PointerGesture::TAP:
4469     case PointerGesture::TAP_DRAG:
4470     case PointerGesture::BUTTON_CLICK_OR_DRAG:
4471     case PointerGesture::HOVER:
4472     case PointerGesture::PRESS:
4473         // Unfade the pointer when the current gesture manipulates the
4474         // area directly under the pointer.
4475         mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
4476         break;
4477     case PointerGesture::SWIPE:
4478     case PointerGesture::FREEFORM:
4479         // Fade the pointer when the current gesture manipulates a different
4480         // area and there are spots to guide the user experience.
4481         if (mParameters.gestureMode == Parameters::GESTURE_MODE_SPOTS) {
4482             mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
4483         } else {
4484             mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
4485         }
4486         break;
4487     }
4488
4489     // Send events!
4490     int32_t metaState = getContext()->getGlobalMetaState();
4491     int32_t buttonState = mCurrentButtonState;
4492
4493     // Update last coordinates of pointers that have moved so that we observe the new
4494     // pointer positions at the same time as other pointers that have just gone up.
4495     bool down = mPointerGesture.currentGestureMode == PointerGesture::TAP
4496             || mPointerGesture.currentGestureMode == PointerGesture::TAP_DRAG
4497             || mPointerGesture.currentGestureMode == PointerGesture::BUTTON_CLICK_OR_DRAG
4498             || mPointerGesture.currentGestureMode == PointerGesture::PRESS
4499             || mPointerGesture.currentGestureMode == PointerGesture::SWIPE
4500             || mPointerGesture.currentGestureMode == PointerGesture::FREEFORM;
4501     bool moveNeeded = false;
4502     if (down && !cancelPreviousGesture && !finishPreviousGesture
4503             && !mPointerGesture.lastGestureIdBits.isEmpty()
4504             && !mPointerGesture.currentGestureIdBits.isEmpty()) {
4505         BitSet32 movedGestureIdBits(mPointerGesture.currentGestureIdBits.value
4506                 & mPointerGesture.lastGestureIdBits.value);
4507         moveNeeded = updateMovedPointers(mPointerGesture.currentGestureProperties,
4508                 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
4509                 mPointerGesture.lastGestureProperties,
4510                 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
4511                 movedGestureIdBits);
4512         if (buttonState != mLastButtonState) {
4513             moveNeeded = true;
4514         }
4515     }
4516
4517     // Send motion events for all pointers that went up or were canceled.
4518     BitSet32 dispatchedGestureIdBits(mPointerGesture.lastGestureIdBits);
4519     if (!dispatchedGestureIdBits.isEmpty()) {
4520         if (cancelPreviousGesture) {
4521             dispatchMotion(when, policyFlags, mSource,
4522                     AMOTION_EVENT_ACTION_CANCEL, 0, metaState, buttonState,
4523                     AMOTION_EVENT_EDGE_FLAG_NONE,
4524                     mPointerGesture.lastGestureProperties,
4525                     mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
4526                     dispatchedGestureIdBits, -1,
4527                     0, 0, mPointerGesture.downTime);
4528
4529             dispatchedGestureIdBits.clear();
4530         } else {
4531             BitSet32 upGestureIdBits;
4532             if (finishPreviousGesture) {
4533                 upGestureIdBits = dispatchedGestureIdBits;
4534             } else {
4535                 upGestureIdBits.value = dispatchedGestureIdBits.value
4536                         & ~mPointerGesture.currentGestureIdBits.value;
4537             }
4538             while (!upGestureIdBits.isEmpty()) {
4539                 uint32_t id = upGestureIdBits.clearFirstMarkedBit();
4540
4541                 dispatchMotion(when, policyFlags, mSource,
4542                         AMOTION_EVENT_ACTION_POINTER_UP, 0,
4543                         metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
4544                         mPointerGesture.lastGestureProperties,
4545                         mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
4546                         dispatchedGestureIdBits, id,
4547                         0, 0, mPointerGesture.downTime);
4548
4549                 dispatchedGestureIdBits.clearBit(id);
4550             }
4551         }
4552     }
4553
4554     // Send motion events for all pointers that moved.
4555     if (moveNeeded) {
4556         dispatchMotion(when, policyFlags, mSource,
4557                 AMOTION_EVENT_ACTION_MOVE, 0, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
4558                 mPointerGesture.currentGestureProperties,
4559                 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
4560                 dispatchedGestureIdBits, -1,
4561                 0, 0, mPointerGesture.downTime);
4562     }
4563
4564     // Send motion events for all pointers that went down.
4565     if (down) {
4566         BitSet32 downGestureIdBits(mPointerGesture.currentGestureIdBits.value
4567                 & ~dispatchedGestureIdBits.value);
4568         while (!downGestureIdBits.isEmpty()) {
4569             uint32_t id = downGestureIdBits.clearFirstMarkedBit();
4570             dispatchedGestureIdBits.markBit(id);
4571
4572             if (dispatchedGestureIdBits.count() == 1) {
4573                 mPointerGesture.downTime = when;
4574             }
4575
4576             dispatchMotion(when, policyFlags, mSource,
4577                     AMOTION_EVENT_ACTION_POINTER_DOWN, 0, metaState, buttonState, 0,
4578                     mPointerGesture.currentGestureProperties,
4579                     mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
4580                     dispatchedGestureIdBits, id,
4581                     0, 0, mPointerGesture.downTime);
4582         }
4583     }
4584
4585     // Send motion events for hover.
4586     if (mPointerGesture.currentGestureMode == PointerGesture::HOVER) {
4587         dispatchMotion(when, policyFlags, mSource,
4588                 AMOTION_EVENT_ACTION_HOVER_MOVE, 0,
4589                 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
4590                 mPointerGesture.currentGestureProperties,
4591                 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
4592                 mPointerGesture.currentGestureIdBits, -1,
4593                 0, 0, mPointerGesture.downTime);
4594     } else if (dispatchedGestureIdBits.isEmpty()
4595             && !mPointerGesture.lastGestureIdBits.isEmpty()) {
4596         // Synthesize a hover move event after all pointers go up to indicate that
4597         // the pointer is hovering again even if the user is not currently touching
4598         // the touch pad.  This ensures that a view will receive a fresh hover enter
4599         // event after a tap.
4600         float x, y;
4601         mPointerController->getPosition(&x, &y);
4602
4603         PointerProperties pointerProperties;
4604         pointerProperties.clear();
4605         pointerProperties.id = 0;
4606         pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
4607
4608         PointerCoords pointerCoords;
4609         pointerCoords.clear();
4610         pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
4611         pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
4612
4613         NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
4614                 AMOTION_EVENT_ACTION_HOVER_MOVE, 0,
4615                 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
4616                 mViewport.displayId, 1, &pointerProperties, &pointerCoords,
4617                 0, 0, mPointerGesture.downTime);
4618         getListener()->notifyMotion(&args);
4619     }
4620
4621     // Update state.
4622     mPointerGesture.lastGestureMode = mPointerGesture.currentGestureMode;
4623     if (!down) {
4624         mPointerGesture.lastGestureIdBits.clear();
4625     } else {
4626         mPointerGesture.lastGestureIdBits = mPointerGesture.currentGestureIdBits;
4627         for (BitSet32 idBits(mPointerGesture.currentGestureIdBits); !idBits.isEmpty(); ) {
4628             uint32_t id = idBits.clearFirstMarkedBit();
4629             uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
4630             mPointerGesture.lastGestureProperties[index].copyFrom(
4631                     mPointerGesture.currentGestureProperties[index]);
4632             mPointerGesture.lastGestureCoords[index].copyFrom(
4633                     mPointerGesture.currentGestureCoords[index]);
4634             mPointerGesture.lastGestureIdToIndex[id] = index;
4635         }
4636     }
4637 }
4638
4639 void TouchInputMapper::abortPointerGestures(nsecs_t when, uint32_t policyFlags) {
4640     // Cancel previously dispatches pointers.
4641     if (!mPointerGesture.lastGestureIdBits.isEmpty()) {
4642         int32_t metaState = getContext()->getGlobalMetaState();
4643         int32_t buttonState = mCurrentButtonState;
4644         dispatchMotion(when, policyFlags, mSource,
4645                 AMOTION_EVENT_ACTION_CANCEL, 0, metaState, buttonState,
4646                 AMOTION_EVENT_EDGE_FLAG_NONE,
4647                 mPointerGesture.lastGestureProperties,
4648                 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
4649                 mPointerGesture.lastGestureIdBits, -1,
4650                 0, 0, mPointerGesture.downTime);
4651     }
4652
4653     // Reset the current pointer gesture.
4654     mPointerGesture.reset();
4655     mPointerVelocityControl.reset();
4656
4657     // Remove any current spots.
4658     if (mPointerController != NULL) {
4659         mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
4660         mPointerController->clearSpots();
4661     }
4662 }
4663
4664 bool TouchInputMapper::preparePointerGestures(nsecs_t when,
4665         bool* outCancelPreviousGesture, bool* outFinishPreviousGesture, bool isTimeout) {
4666     *outCancelPreviousGesture = false;
4667     *outFinishPreviousGesture = false;
4668
4669     // Handle TAP timeout.
4670     if (isTimeout) {
4671 #if DEBUG_GESTURES
4672         ALOGD("Gestures: Processing timeout");
4673 #endif
4674
4675         if (mPointerGesture.lastGestureMode == PointerGesture::TAP) {
4676             if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
4677                 // The tap/drag timeout has not yet expired.
4678                 getContext()->requestTimeoutAtTime(mPointerGesture.tapUpTime
4679                         + mConfig.pointerGestureTapDragInterval);
4680             } else {
4681                 // The tap is finished.
4682 #if DEBUG_GESTURES
4683                 ALOGD("Gestures: TAP finished");
4684 #endif
4685                 *outFinishPreviousGesture = true;
4686
4687                 mPointerGesture.activeGestureId = -1;
4688                 mPointerGesture.currentGestureMode = PointerGesture::NEUTRAL;
4689                 mPointerGesture.currentGestureIdBits.clear();
4690
4691                 mPointerVelocityControl.reset();
4692                 return true;
4693             }
4694         }
4695
4696         // We did not handle this timeout.
4697         return false;
4698     }
4699
4700     const uint32_t currentFingerCount = mCurrentFingerIdBits.count();
4701     const uint32_t lastFingerCount = mLastFingerIdBits.count();
4702
4703     // Update the velocity tracker.
4704     {
4705         VelocityTracker::Position positions[MAX_POINTERS];
4706         uint32_t count = 0;
4707         for (BitSet32 idBits(mCurrentFingerIdBits); !idBits.isEmpty(); count++) {
4708             uint32_t id = idBits.clearFirstMarkedBit();
4709             const RawPointerData::Pointer& pointer = mCurrentRawPointerData.pointerForId(id);
4710             positions[count].x = pointer.x * mPointerXMovementScale;
4711             positions[count].y = pointer.y * mPointerYMovementScale;
4712         }
4713         mPointerGesture.velocityTracker.addMovement(when,
4714                 mCurrentFingerIdBits, positions);
4715     }
4716
4717     // If the gesture ever enters a mode other than TAP, HOVER or TAP_DRAG, without first returning
4718     // to NEUTRAL, then we should not generate tap event.
4719     if (mPointerGesture.lastGestureMode != PointerGesture::HOVER
4720             && mPointerGesture.lastGestureMode != PointerGesture::TAP
4721             && mPointerGesture.lastGestureMode != PointerGesture::TAP_DRAG) {
4722         mPointerGesture.resetTap();
4723     }
4724
4725     // Pick a new active touch id if needed.
4726     // Choose an arbitrary pointer that just went down, if there is one.
4727     // Otherwise choose an arbitrary remaining pointer.
4728     // This guarantees we always have an active touch id when there is at least one pointer.
4729     // We keep the same active touch id for as long as possible.
4730     bool activeTouchChanged = false;
4731     int32_t lastActiveTouchId = mPointerGesture.activeTouchId;
4732     int32_t activeTouchId = lastActiveTouchId;
4733     if (activeTouchId < 0) {
4734         if (!mCurrentFingerIdBits.isEmpty()) {
4735             activeTouchChanged = true;
4736             activeTouchId = mPointerGesture.activeTouchId =
4737                     mCurrentFingerIdBits.firstMarkedBit();
4738             mPointerGesture.firstTouchTime = when;
4739         }
4740     } else if (!mCurrentFingerIdBits.hasBit(activeTouchId)) {
4741         activeTouchChanged = true;
4742         if (!mCurrentFingerIdBits.isEmpty()) {
4743             activeTouchId = mPointerGesture.activeTouchId =
4744                     mCurrentFingerIdBits.firstMarkedBit();
4745         } else {
4746             activeTouchId = mPointerGesture.activeTouchId = -1;
4747         }
4748     }
4749
4750     // Determine whether we are in quiet time.
4751     bool isQuietTime = false;
4752     if (activeTouchId < 0) {
4753         mPointerGesture.resetQuietTime();
4754     } else {
4755         isQuietTime = when < mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval;
4756         if (!isQuietTime) {
4757             if ((mPointerGesture.lastGestureMode == PointerGesture::PRESS
4758                     || mPointerGesture.lastGestureMode == PointerGesture::SWIPE
4759                     || mPointerGesture.lastGestureMode == PointerGesture::FREEFORM)
4760                     && currentFingerCount < 2) {
4761                 // Enter quiet time when exiting swipe or freeform state.
4762                 // This is to prevent accidentally entering the hover state and flinging the
4763                 // pointer when finishing a swipe and there is still one pointer left onscreen.
4764                 isQuietTime = true;
4765             } else if (mPointerGesture.lastGestureMode == PointerGesture::BUTTON_CLICK_OR_DRAG
4766                     && currentFingerCount >= 2
4767                     && !isPointerDown(mCurrentButtonState)) {
4768                 // Enter quiet time when releasing the button and there are still two or more
4769                 // fingers down.  This may indicate that one finger was used to press the button
4770                 // but it has not gone up yet.
4771                 isQuietTime = true;
4772             }
4773             if (isQuietTime) {
4774                 mPointerGesture.quietTime = when;
4775             }
4776         }
4777     }
4778
4779     // Switch states based on button and pointer state.
4780     if (isQuietTime) {
4781         // Case 1: Quiet time. (QUIET)
4782 #if DEBUG_GESTURES
4783         ALOGD("Gestures: QUIET for next %0.3fms", (mPointerGesture.quietTime
4784                 + mConfig.pointerGestureQuietInterval - when) * 0.000001f);
4785 #endif
4786         if (mPointerGesture.lastGestureMode != PointerGesture::QUIET) {
4787             *outFinishPreviousGesture = true;
4788         }
4789
4790         mPointerGesture.activeGestureId = -1;
4791         mPointerGesture.currentGestureMode = PointerGesture::QUIET;
4792         mPointerGesture.currentGestureIdBits.clear();
4793
4794         mPointerVelocityControl.reset();
4795     } else if (isPointerDown(mCurrentButtonState)) {
4796         // Case 2: Button is pressed. (BUTTON_CLICK_OR_DRAG)
4797         // The pointer follows the active touch point.
4798         // Emit DOWN, MOVE, UP events at the pointer location.
4799         //
4800         // Only the active touch matters; other fingers are ignored.  This policy helps
4801         // to handle the case where the user places a second finger on the touch pad
4802         // to apply the necessary force to depress an integrated button below the surface.
4803         // We don't want the second finger to be delivered to applications.
4804         //
4805         // For this to work well, we need to make sure to track the pointer that is really
4806         // active.  If the user first puts one finger down to click then adds another
4807         // finger to drag then the active pointer should switch to the finger that is
4808         // being dragged.
4809 #if DEBUG_GESTURES
4810         ALOGD("Gestures: BUTTON_CLICK_OR_DRAG activeTouchId=%d, "
4811                 "currentFingerCount=%d", activeTouchId, currentFingerCount);
4812 #endif
4813         // Reset state when just starting.
4814         if (mPointerGesture.lastGestureMode != PointerGesture::BUTTON_CLICK_OR_DRAG) {
4815             *outFinishPreviousGesture = true;
4816             mPointerGesture.activeGestureId = 0;
4817         }
4818
4819         // Switch pointers if needed.
4820         // Find the fastest pointer and follow it.
4821         if (activeTouchId >= 0 && currentFingerCount > 1) {
4822             int32_t bestId = -1;
4823             float bestSpeed = mConfig.pointerGestureDragMinSwitchSpeed;
4824             for (BitSet32 idBits(mCurrentFingerIdBits); !idBits.isEmpty(); ) {
4825                 uint32_t id = idBits.clearFirstMarkedBit();
4826                 float vx, vy;
4827                 if (mPointerGesture.velocityTracker.getVelocity(id, &vx, &vy)) {
4828                     float speed = hypotf(vx, vy);
4829                     if (speed > bestSpeed) {
4830                         bestId = id;
4831                         bestSpeed = speed;
4832                     }
4833                 }
4834             }
4835             if (bestId >= 0 && bestId != activeTouchId) {
4836                 mPointerGesture.activeTouchId = activeTouchId = bestId;
4837                 activeTouchChanged = true;
4838 #if DEBUG_GESTURES
4839                 ALOGD("Gestures: BUTTON_CLICK_OR_DRAG switched pointers, "
4840                         "bestId=%d, bestSpeed=%0.3f", bestId, bestSpeed);
4841 #endif
4842             }
4843         }
4844
4845         if (activeTouchId >= 0 && mLastFingerIdBits.hasBit(activeTouchId)) {
4846             const RawPointerData::Pointer& currentPointer =
4847                     mCurrentRawPointerData.pointerForId(activeTouchId);
4848             const RawPointerData::Pointer& lastPointer =
4849                     mLastRawPointerData.pointerForId(activeTouchId);
4850             float deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
4851             float deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
4852
4853             rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
4854             mPointerVelocityControl.move(when, &deltaX, &deltaY);
4855
4856             // Move the pointer using a relative motion.
4857             // When using spots, the click will occur at the position of the anchor
4858             // spot and all other spots will move there.
4859             mPointerController->move(deltaX, deltaY);
4860         } else {
4861             mPointerVelocityControl.reset();
4862         }
4863
4864         float x, y;
4865         mPointerController->getPosition(&x, &y);
4866
4867         mPointerGesture.currentGestureMode = PointerGesture::BUTTON_CLICK_OR_DRAG;
4868         mPointerGesture.currentGestureIdBits.clear();
4869         mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
4870         mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
4871         mPointerGesture.currentGestureProperties[0].clear();
4872         mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
4873         mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
4874         mPointerGesture.currentGestureCoords[0].clear();
4875         mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
4876         mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
4877         mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
4878     } else if (currentFingerCount == 0) {
4879         // Case 3. No fingers down and button is not pressed. (NEUTRAL)
4880         if (mPointerGesture.lastGestureMode != PointerGesture::NEUTRAL) {
4881             *outFinishPreviousGesture = true;
4882         }
4883
4884         // Watch for taps coming out of HOVER or TAP_DRAG mode.
4885         // Checking for taps after TAP_DRAG allows us to detect double-taps.
4886         bool tapped = false;
4887         if ((mPointerGesture.lastGestureMode == PointerGesture::HOVER
4888                 || mPointerGesture.lastGestureMode == PointerGesture::TAP_DRAG)
4889                 && lastFingerCount == 1) {
4890             if (when <= mPointerGesture.tapDownTime + mConfig.pointerGestureTapInterval) {
4891                 float x, y;
4892                 mPointerController->getPosition(&x, &y);
4893                 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop
4894                         && fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
4895 #if DEBUG_GESTURES
4896                     ALOGD("Gestures: TAP");
4897 #endif
4898
4899                     mPointerGesture.tapUpTime = when;
4900                     getContext()->requestTimeoutAtTime(when
4901                             + mConfig.pointerGestureTapDragInterval);
4902
4903                     mPointerGesture.activeGestureId = 0;
4904                     mPointerGesture.currentGestureMode = PointerGesture::TAP;
4905                     mPointerGesture.currentGestureIdBits.clear();
4906                     mPointerGesture.currentGestureIdBits.markBit(
4907                             mPointerGesture.activeGestureId);
4908                     mPointerGesture.currentGestureIdToIndex[
4909                             mPointerGesture.activeGestureId] = 0;
4910                     mPointerGesture.currentGestureProperties[0].clear();
4911                     mPointerGesture.currentGestureProperties[0].id =
4912                             mPointerGesture.activeGestureId;
4913                     mPointerGesture.currentGestureProperties[0].toolType =
4914                             AMOTION_EVENT_TOOL_TYPE_FINGER;
4915                     mPointerGesture.currentGestureCoords[0].clear();
4916                     mPointerGesture.currentGestureCoords[0].setAxisValue(
4917                             AMOTION_EVENT_AXIS_X, mPointerGesture.tapX);
4918                     mPointerGesture.currentGestureCoords[0].setAxisValue(
4919                             AMOTION_EVENT_AXIS_Y, mPointerGesture.tapY);
4920                     mPointerGesture.currentGestureCoords[0].setAxisValue(
4921                             AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
4922
4923                     tapped = true;
4924                 } else {
4925 #if DEBUG_GESTURES
4926                     ALOGD("Gestures: Not a TAP, deltaX=%f, deltaY=%f",
4927                             x - mPointerGesture.tapX,
4928                             y - mPointerGesture.tapY);
4929 #endif
4930                 }
4931             } else {
4932 #if DEBUG_GESTURES
4933                 if (mPointerGesture.tapDownTime != LLONG_MIN) {
4934                     ALOGD("Gestures: Not a TAP, %0.3fms since down",
4935                             (when - mPointerGesture.tapDownTime) * 0.000001f);
4936                 } else {
4937                     ALOGD("Gestures: Not a TAP, incompatible mode transitions");
4938                 }
4939 #endif
4940             }
4941         }
4942
4943         mPointerVelocityControl.reset();
4944
4945         if (!tapped) {
4946 #if DEBUG_GESTURES
4947             ALOGD("Gestures: NEUTRAL");
4948 #endif
4949             mPointerGesture.activeGestureId = -1;
4950             mPointerGesture.currentGestureMode = PointerGesture::NEUTRAL;
4951             mPointerGesture.currentGestureIdBits.clear();
4952         }
4953     } else if (currentFingerCount == 1) {
4954         // Case 4. Exactly one finger down, button is not pressed. (HOVER or TAP_DRAG)
4955         // The pointer follows the active touch point.
4956         // When in HOVER, emit HOVER_MOVE events at the pointer location.
4957         // When in TAP_DRAG, emit MOVE events at the pointer location.
4958         ALOG_ASSERT(activeTouchId >= 0);
4959
4960         mPointerGesture.currentGestureMode = PointerGesture::HOVER;
4961         if (mPointerGesture.lastGestureMode == PointerGesture::TAP) {
4962             if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
4963                 float x, y;
4964                 mPointerController->getPosition(&x, &y);
4965                 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop
4966                         && fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
4967                     mPointerGesture.currentGestureMode = PointerGesture::TAP_DRAG;
4968                 } else {
4969 #if DEBUG_GESTURES
4970                     ALOGD("Gestures: Not a TAP_DRAG, deltaX=%f, deltaY=%f",
4971                             x - mPointerGesture.tapX,
4972                             y - mPointerGesture.tapY);
4973 #endif
4974                 }
4975             } else {
4976 #if DEBUG_GESTURES
4977                 ALOGD("Gestures: Not a TAP_DRAG, %0.3fms time since up",
4978                         (when - mPointerGesture.tapUpTime) * 0.000001f);
4979 #endif
4980             }
4981         } else if (mPointerGesture.lastGestureMode == PointerGesture::TAP_DRAG) {
4982             mPointerGesture.currentGestureMode = PointerGesture::TAP_DRAG;
4983         }
4984
4985         if (mLastFingerIdBits.hasBit(activeTouchId)) {
4986             const RawPointerData::Pointer& currentPointer =
4987                     mCurrentRawPointerData.pointerForId(activeTouchId);
4988             const RawPointerData::Pointer& lastPointer =
4989                     mLastRawPointerData.pointerForId(activeTouchId);
4990             float deltaX = (currentPointer.x - lastPointer.x)
4991                     * mPointerXMovementScale;
4992             float deltaY = (currentPointer.y - lastPointer.y)
4993                     * mPointerYMovementScale;
4994
4995             rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
4996             mPointerVelocityControl.move(when, &deltaX, &deltaY);
4997
4998             // Move the pointer using a relative motion.
4999             // When using spots, the hover or drag will occur at the position of the anchor spot.
5000             mPointerController->move(deltaX, deltaY);
5001         } else {
5002             mPointerVelocityControl.reset();
5003         }
5004
5005         bool down;
5006         if (mPointerGesture.currentGestureMode == PointerGesture::TAP_DRAG) {
5007 #if DEBUG_GESTURES
5008             ALOGD("Gestures: TAP_DRAG");
5009 #endif
5010             down = true;
5011         } else {
5012 #if DEBUG_GESTURES
5013             ALOGD("Gestures: HOVER");
5014 #endif
5015             if (mPointerGesture.lastGestureMode != PointerGesture::HOVER) {
5016                 *outFinishPreviousGesture = true;
5017             }
5018             mPointerGesture.activeGestureId = 0;
5019             down = false;
5020         }
5021
5022         float x, y;
5023         mPointerController->getPosition(&x, &y);
5024
5025         mPointerGesture.currentGestureIdBits.clear();
5026         mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
5027         mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
5028         mPointerGesture.currentGestureProperties[0].clear();
5029         mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
5030         mPointerGesture.currentGestureProperties[0].toolType =
5031                 AMOTION_EVENT_TOOL_TYPE_FINGER;
5032         mPointerGesture.currentGestureCoords[0].clear();
5033         mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
5034         mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5035         mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
5036                 down ? 1.0f : 0.0f);
5037
5038         if (lastFingerCount == 0 && currentFingerCount != 0) {
5039             mPointerGesture.resetTap();
5040             mPointerGesture.tapDownTime = when;
5041             mPointerGesture.tapX = x;
5042             mPointerGesture.tapY = y;
5043         }
5044     } else {
5045         // Case 5. At least two fingers down, button is not pressed. (PRESS, SWIPE or FREEFORM)
5046         // We need to provide feedback for each finger that goes down so we cannot wait
5047         // for the fingers to move before deciding what to do.
5048         //
5049         // The ambiguous case is deciding what to do when there are two fingers down but they
5050         // have not moved enough to determine whether they are part of a drag or part of a
5051         // freeform gesture, or just a press or long-press at the pointer location.
5052         //
5053         // When there are two fingers we start with the PRESS hypothesis and we generate a
5054         // down at the pointer location.
5055         //
5056         // When the two fingers move enough or when additional fingers are added, we make
5057         // a decision to transition into SWIPE or FREEFORM mode accordingly.
5058         ALOG_ASSERT(activeTouchId >= 0);
5059
5060         bool settled = when >= mPointerGesture.firstTouchTime
5061                 + mConfig.pointerGestureMultitouchSettleInterval;
5062         if (mPointerGesture.lastGestureMode != PointerGesture::PRESS
5063                 && mPointerGesture.lastGestureMode != PointerGesture::SWIPE
5064                 && mPointerGesture.lastGestureMode != PointerGesture::FREEFORM) {
5065             *outFinishPreviousGesture = true;
5066         } else if (!settled && currentFingerCount > lastFingerCount) {
5067             // Additional pointers have gone down but not yet settled.
5068             // Reset the gesture.
5069 #if DEBUG_GESTURES
5070             ALOGD("Gestures: Resetting gesture since additional pointers went down for MULTITOUCH, "
5071                     "settle time remaining %0.3fms", (mPointerGesture.firstTouchTime
5072                             + mConfig.pointerGestureMultitouchSettleInterval - when)
5073                             * 0.000001f);
5074 #endif
5075             *outCancelPreviousGesture = true;
5076         } else {
5077             // Continue previous gesture.
5078             mPointerGesture.currentGestureMode = mPointerGesture.lastGestureMode;
5079         }
5080
5081         if (*outFinishPreviousGesture || *outCancelPreviousGesture) {
5082             mPointerGesture.currentGestureMode = PointerGesture::PRESS;
5083             mPointerGesture.activeGestureId = 0;
5084             mPointerGesture.referenceIdBits.clear();
5085             mPointerVelocityControl.reset();
5086
5087             // Use the centroid and pointer location as the reference points for the gesture.
5088 #if DEBUG_GESTURES
5089             ALOGD("Gestures: Using centroid as reference for MULTITOUCH, "
5090                     "settle time remaining %0.3fms", (mPointerGesture.firstTouchTime
5091                             + mConfig.pointerGestureMultitouchSettleInterval - when)
5092                             * 0.000001f);
5093 #endif
5094             mCurrentRawPointerData.getCentroidOfTouchingPointers(
5095                     &mPointerGesture.referenceTouchX,
5096                     &mPointerGesture.referenceTouchY);
5097             mPointerController->getPosition(&mPointerGesture.referenceGestureX,
5098                     &mPointerGesture.referenceGestureY);
5099         }
5100
5101         // Clear the reference deltas for fingers not yet included in the reference calculation.
5102         for (BitSet32 idBits(mCurrentFingerIdBits.value
5103                 & ~mPointerGesture.referenceIdBits.value); !idBits.isEmpty(); ) {
5104             uint32_t id = idBits.clearFirstMarkedBit();
5105             mPointerGesture.referenceDeltas[id].dx = 0;
5106             mPointerGesture.referenceDeltas[id].dy = 0;
5107         }
5108         mPointerGesture.referenceIdBits = mCurrentFingerIdBits;
5109
5110         // Add delta for all fingers and calculate a common movement delta.
5111         float commonDeltaX = 0, commonDeltaY = 0;
5112         BitSet32 commonIdBits(mLastFingerIdBits.value
5113                 & mCurrentFingerIdBits.value);
5114         for (BitSet32 idBits(commonIdBits); !idBits.isEmpty(); ) {
5115             bool first = (idBits == commonIdBits);
5116             uint32_t id = idBits.clearFirstMarkedBit();
5117             const RawPointerData::Pointer& cpd = mCurrentRawPointerData.pointerForId(id);
5118             const RawPointerData::Pointer& lpd = mLastRawPointerData.pointerForId(id);
5119             PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
5120             delta.dx += cpd.x - lpd.x;
5121             delta.dy += cpd.y - lpd.y;
5122
5123             if (first) {
5124                 commonDeltaX = delta.dx;
5125                 commonDeltaY = delta.dy;
5126             } else {
5127                 commonDeltaX = calculateCommonVector(commonDeltaX, delta.dx);
5128                 commonDeltaY = calculateCommonVector(commonDeltaY, delta.dy);
5129             }
5130         }
5131
5132         // Consider transitions from PRESS to SWIPE or MULTITOUCH.
5133         if (mPointerGesture.currentGestureMode == PointerGesture::PRESS) {
5134             float dist[MAX_POINTER_ID + 1];
5135             int32_t distOverThreshold = 0;
5136             for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty(); ) {
5137                 uint32_t id = idBits.clearFirstMarkedBit();
5138                 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
5139                 dist[id] = hypotf(delta.dx * mPointerXZoomScale,
5140                         delta.dy * mPointerYZoomScale);
5141                 if (dist[id] > mConfig.pointerGestureMultitouchMinDistance) {
5142                     distOverThreshold += 1;
5143                 }
5144             }
5145
5146             // Only transition when at least two pointers have moved further than
5147             // the minimum distance threshold.
5148             if (distOverThreshold >= 2) {
5149                 if (currentFingerCount > 2) {
5150                     // There are more than two pointers, switch to FREEFORM.
5151 #if DEBUG_GESTURES
5152                     ALOGD("Gestures: PRESS transitioned to FREEFORM, number of pointers %d > 2",
5153                             currentFingerCount);
5154 #endif
5155                     *outCancelPreviousGesture = true;
5156                     mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
5157                 } else {
5158                     // There are exactly two pointers.
5159                     BitSet32 idBits(mCurrentFingerIdBits);
5160                     uint32_t id1 = idBits.clearFirstMarkedBit();
5161                     uint32_t id2 = idBits.firstMarkedBit();
5162                     const RawPointerData::Pointer& p1 = mCurrentRawPointerData.pointerForId(id1);
5163                     const RawPointerData::Pointer& p2 = mCurrentRawPointerData.pointerForId(id2);
5164                     float mutualDistance = distance(p1.x, p1.y, p2.x, p2.y);
5165                     if (mutualDistance > mPointerGestureMaxSwipeWidth) {
5166                         // There are two pointers but they are too far apart for a SWIPE,
5167                         // switch to FREEFORM.
5168 #if DEBUG_GESTURES
5169                         ALOGD("Gestures: PRESS transitioned to FREEFORM, distance %0.3f > %0.3f",
5170                                 mutualDistance, mPointerGestureMaxSwipeWidth);
5171 #endif
5172                         *outCancelPreviousGesture = true;
5173                         mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
5174                     } else {
5175                         // There are two pointers.  Wait for both pointers to start moving
5176                         // before deciding whether this is a SWIPE or FREEFORM gesture.
5177                         float dist1 = dist[id1];
5178                         float dist2 = dist[id2];
5179                         if (dist1 >= mConfig.pointerGestureMultitouchMinDistance
5180                                 && dist2 >= mConfig.pointerGestureMultitouchMinDistance) {
5181                             // Calculate the dot product of the displacement vectors.
5182                             // When the vectors are oriented in approximately the same direction,
5183                             // the angle betweeen them is near zero and the cosine of the angle
5184                             // approches 1.0.  Recall that dot(v1, v2) = cos(angle) * mag(v1) * mag(v2).
5185                             PointerGesture::Delta& delta1 = mPointerGesture.referenceDeltas[id1];
5186                             PointerGesture::Delta& delta2 = mPointerGesture.referenceDeltas[id2];
5187                             float dx1 = delta1.dx * mPointerXZoomScale;
5188                             float dy1 = delta1.dy * mPointerYZoomScale;
5189                             float dx2 = delta2.dx * mPointerXZoomScale;
5190                             float dy2 = delta2.dy * mPointerYZoomScale;
5191                             float dot = dx1 * dx2 + dy1 * dy2;
5192                             float cosine = dot / (dist1 * dist2); // denominator always > 0
5193                             if (cosine >= mConfig.pointerGestureSwipeTransitionAngleCosine) {
5194                                 // Pointers are moving in the same direction.  Switch to SWIPE.
5195 #if DEBUG_GESTURES
5196                                 ALOGD("Gestures: PRESS transitioned to SWIPE, "
5197                                         "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
5198                                         "cosine %0.3f >= %0.3f",
5199                                         dist1, mConfig.pointerGestureMultitouchMinDistance,
5200                                         dist2, mConfig.pointerGestureMultitouchMinDistance,
5201                                         cosine, mConfig.pointerGestureSwipeTransitionAngleCosine);
5202 #endif
5203                                 mPointerGesture.currentGestureMode = PointerGesture::SWIPE;
5204                             } else {
5205                                 // Pointers are moving in different directions.  Switch to FREEFORM.
5206 #if DEBUG_GESTURES
5207                                 ALOGD("Gestures: PRESS transitioned to FREEFORM, "
5208                                         "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
5209                                         "cosine %0.3f < %0.3f",
5210                                         dist1, mConfig.pointerGestureMultitouchMinDistance,
5211                                         dist2, mConfig.pointerGestureMultitouchMinDistance,
5212                                         cosine, mConfig.pointerGestureSwipeTransitionAngleCosine);
5213 #endif
5214                                 *outCancelPreviousGesture = true;
5215                                 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
5216                             }
5217                         }
5218                     }
5219                 }
5220             }
5221         } else if (mPointerGesture.currentGestureMode == PointerGesture::SWIPE) {
5222             // Switch from SWIPE to FREEFORM if additional pointers go down.
5223             // Cancel previous gesture.
5224             if (currentFingerCount > 2) {
5225 #if DEBUG_GESTURES
5226                 ALOGD("Gestures: SWIPE transitioned to FREEFORM, number of pointers %d > 2",
5227                         currentFingerCount);
5228 #endif
5229                 *outCancelPreviousGesture = true;
5230                 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
5231             }
5232         }
5233
5234         // Move the reference points based on the overall group motion of the fingers
5235         // except in PRESS mode while waiting for a transition to occur.
5236         if (mPointerGesture.currentGestureMode != PointerGesture::PRESS
5237                 && (commonDeltaX || commonDeltaY)) {
5238             for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty(); ) {
5239                 uint32_t id = idBits.clearFirstMarkedBit();
5240                 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
5241                 delta.dx = 0;
5242                 delta.dy = 0;
5243             }
5244
5245             mPointerGesture.referenceTouchX += commonDeltaX;
5246             mPointerGesture.referenceTouchY += commonDeltaY;
5247
5248             commonDeltaX *= mPointerXMovementScale;
5249             commonDeltaY *= mPointerYMovementScale;
5250
5251             rotateDelta(mSurfaceOrientation, &commonDeltaX, &commonDeltaY);
5252             mPointerVelocityControl.move(when, &commonDeltaX, &commonDeltaY);
5253
5254             mPointerGesture.referenceGestureX += commonDeltaX;
5255             mPointerGesture.referenceGestureY += commonDeltaY;
5256         }
5257
5258         // Report gestures.
5259         if (mPointerGesture.currentGestureMode == PointerGesture::PRESS
5260                 || mPointerGesture.currentGestureMode == PointerGesture::SWIPE) {
5261             // PRESS or SWIPE mode.
5262 #if DEBUG_GESTURES
5263             ALOGD("Gestures: PRESS or SWIPE activeTouchId=%d,"
5264                     "activeGestureId=%d, currentTouchPointerCount=%d",
5265                     activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
5266 #endif
5267             ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
5268
5269             mPointerGesture.currentGestureIdBits.clear();
5270             mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
5271             mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
5272             mPointerGesture.currentGestureProperties[0].clear();
5273             mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
5274             mPointerGesture.currentGestureProperties[0].toolType =
5275                     AMOTION_EVENT_TOOL_TYPE_FINGER;
5276             mPointerGesture.currentGestureCoords[0].clear();
5277             mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
5278                     mPointerGesture.referenceGestureX);
5279             mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
5280                     mPointerGesture.referenceGestureY);
5281             mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
5282         } else if (mPointerGesture.currentGestureMode == PointerGesture::FREEFORM) {
5283             // FREEFORM mode.
5284 #if DEBUG_GESTURES
5285             ALOGD("Gestures: FREEFORM activeTouchId=%d,"
5286                     "activeGestureId=%d, currentTouchPointerCount=%d",
5287                     activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
5288 #endif
5289             ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
5290
5291             mPointerGesture.currentGestureIdBits.clear();
5292
5293             BitSet32 mappedTouchIdBits;
5294             BitSet32 usedGestureIdBits;
5295             if (mPointerGesture.lastGestureMode != PointerGesture::FREEFORM) {
5296                 // Initially, assign the active gesture id to the active touch point
5297                 // if there is one.  No other touch id bits are mapped yet.
5298                 if (!*outCancelPreviousGesture) {
5299                     mappedTouchIdBits.markBit(activeTouchId);
5300                     usedGestureIdBits.markBit(mPointerGesture.activeGestureId);
5301                     mPointerGesture.freeformTouchToGestureIdMap[activeTouchId] =
5302                             mPointerGesture.activeGestureId;
5303                 } else {
5304                     mPointerGesture.activeGestureId = -1;
5305                 }
5306             } else {
5307                 // Otherwise, assume we mapped all touches from the previous frame.
5308                 // Reuse all mappings that are still applicable.
5309                 mappedTouchIdBits.value = mLastFingerIdBits.value
5310                         & mCurrentFingerIdBits.value;
5311                 usedGestureIdBits = mPointerGesture.lastGestureIdBits;
5312
5313                 // Check whether we need to choose a new active gesture id because the
5314                 // current went went up.
5315                 for (BitSet32 upTouchIdBits(mLastFingerIdBits.value
5316                         & ~mCurrentFingerIdBits.value);
5317                         !upTouchIdBits.isEmpty(); ) {
5318                     uint32_t upTouchId = upTouchIdBits.clearFirstMarkedBit();
5319                     uint32_t upGestureId = mPointerGesture.freeformTouchToGestureIdMap[upTouchId];
5320                     if (upGestureId == uint32_t(mPointerGesture.activeGestureId)) {
5321                         mPointerGesture.activeGestureId = -1;
5322                         break;
5323                     }
5324                 }
5325             }
5326
5327 #if DEBUG_GESTURES
5328             ALOGD("Gestures: FREEFORM follow up "
5329                     "mappedTouchIdBits=0x%08x, usedGestureIdBits=0x%08x, "
5330                     "activeGestureId=%d",
5331                     mappedTouchIdBits.value, usedGestureIdBits.value,
5332                     mPointerGesture.activeGestureId);
5333 #endif
5334
5335             BitSet32 idBits(mCurrentFingerIdBits);
5336             for (uint32_t i = 0; i < currentFingerCount; i++) {
5337                 uint32_t touchId = idBits.clearFirstMarkedBit();
5338                 uint32_t gestureId;
5339                 if (!mappedTouchIdBits.hasBit(touchId)) {
5340                     gestureId = usedGestureIdBits.markFirstUnmarkedBit();
5341                     mPointerGesture.freeformTouchToGestureIdMap[touchId] = gestureId;
5342 #if DEBUG_GESTURES
5343                     ALOGD("Gestures: FREEFORM "
5344                             "new mapping for touch id %d -> gesture id %d",
5345                             touchId, gestureId);
5346 #endif
5347                 } else {
5348                     gestureId = mPointerGesture.freeformTouchToGestureIdMap[touchId];
5349 #if DEBUG_GESTURES
5350                     ALOGD("Gestures: FREEFORM "
5351                             "existing mapping for touch id %d -> gesture id %d",
5352                             touchId, gestureId);
5353 #endif
5354                 }
5355                 mPointerGesture.currentGestureIdBits.markBit(gestureId);
5356                 mPointerGesture.currentGestureIdToIndex[gestureId] = i;
5357
5358                 const RawPointerData::Pointer& pointer =
5359                         mCurrentRawPointerData.pointerForId(touchId);
5360                 float deltaX = (pointer.x - mPointerGesture.referenceTouchX)
5361                         * mPointerXZoomScale;
5362                 float deltaY = (pointer.y - mPointerGesture.referenceTouchY)
5363                         * mPointerYZoomScale;
5364                 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
5365
5366                 mPointerGesture.currentGestureProperties[i].clear();
5367                 mPointerGesture.currentGestureProperties[i].id = gestureId;
5368                 mPointerGesture.currentGestureProperties[i].toolType =
5369                         AMOTION_EVENT_TOOL_TYPE_FINGER;
5370                 mPointerGesture.currentGestureCoords[i].clear();
5371                 mPointerGesture.currentGestureCoords[i].setAxisValue(
5372                         AMOTION_EVENT_AXIS_X, mPointerGesture.referenceGestureX + deltaX);
5373                 mPointerGesture.currentGestureCoords[i].setAxisValue(
5374                         AMOTION_EVENT_AXIS_Y, mPointerGesture.referenceGestureY + deltaY);
5375                 mPointerGesture.currentGestureCoords[i].setAxisValue(
5376                         AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
5377             }
5378
5379             if (mPointerGesture.activeGestureId < 0) {
5380                 mPointerGesture.activeGestureId =
5381                         mPointerGesture.currentGestureIdBits.firstMarkedBit();
5382 #if DEBUG_GESTURES
5383                 ALOGD("Gestures: FREEFORM new "
5384                         "activeGestureId=%d", mPointerGesture.activeGestureId);
5385 #endif
5386             }
5387         }
5388     }
5389
5390     mPointerController->setButtonState(mCurrentButtonState);
5391
5392 #if DEBUG_GESTURES
5393     ALOGD("Gestures: finishPreviousGesture=%s, cancelPreviousGesture=%s, "
5394             "currentGestureMode=%d, currentGestureIdBits=0x%08x, "
5395             "lastGestureMode=%d, lastGestureIdBits=0x%08x",
5396             toString(*outFinishPreviousGesture), toString(*outCancelPreviousGesture),
5397             mPointerGesture.currentGestureMode, mPointerGesture.currentGestureIdBits.value,
5398             mPointerGesture.lastGestureMode, mPointerGesture.lastGestureIdBits.value);
5399     for (BitSet32 idBits = mPointerGesture.currentGestureIdBits; !idBits.isEmpty(); ) {
5400         uint32_t id = idBits.clearFirstMarkedBit();
5401         uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
5402         const PointerProperties& properties = mPointerGesture.currentGestureProperties[index];
5403         const PointerCoords& coords = mPointerGesture.currentGestureCoords[index];
5404         ALOGD("  currentGesture[%d]: index=%d, toolType=%d, "
5405                 "x=%0.3f, y=%0.3f, pressure=%0.3f",
5406                 id, index, properties.toolType,
5407                 coords.getAxisValue(AMOTION_EVENT_AXIS_X),
5408                 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
5409                 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
5410     }
5411     for (BitSet32 idBits = mPointerGesture.lastGestureIdBits; !idBits.isEmpty(); ) {
5412         uint32_t id = idBits.clearFirstMarkedBit();
5413         uint32_t index = mPointerGesture.lastGestureIdToIndex[id];
5414         const PointerProperties& properties = mPointerGesture.lastGestureProperties[index];
5415         const PointerCoords& coords = mPointerGesture.lastGestureCoords[index];
5416         ALOGD("  lastGesture[%d]: index=%d, toolType=%d, "
5417                 "x=%0.3f, y=%0.3f, pressure=%0.3f",
5418                 id, index, properties.toolType,
5419                 coords.getAxisValue(AMOTION_EVENT_AXIS_X),
5420                 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
5421                 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
5422     }
5423 #endif
5424     return true;
5425 }
5426
5427 void TouchInputMapper::dispatchPointerStylus(nsecs_t when, uint32_t policyFlags) {
5428     mPointerSimple.currentCoords.clear();
5429     mPointerSimple.currentProperties.clear();
5430
5431     bool down, hovering;
5432     if (!mCurrentStylusIdBits.isEmpty()) {
5433         uint32_t id = mCurrentStylusIdBits.firstMarkedBit();
5434         uint32_t index = mCurrentCookedPointerData.idToIndex[id];
5435         float x = mCurrentCookedPointerData.pointerCoords[index].getX();
5436         float y = mCurrentCookedPointerData.pointerCoords[index].getY();
5437         mPointerController->setPosition(x, y);
5438
5439         hovering = mCurrentCookedPointerData.hoveringIdBits.hasBit(id);
5440         down = !hovering;
5441
5442         mPointerController->getPosition(&x, &y);
5443         mPointerSimple.currentCoords.copyFrom(mCurrentCookedPointerData.pointerCoords[index]);
5444         mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
5445         mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5446         mPointerSimple.currentProperties.id = 0;
5447         mPointerSimple.currentProperties.toolType =
5448                 mCurrentCookedPointerData.pointerProperties[index].toolType;
5449     } else {
5450         down = false;
5451         hovering = false;
5452     }
5453
5454     dispatchPointerSimple(when, policyFlags, down, hovering);
5455 }
5456
5457 void TouchInputMapper::abortPointerStylus(nsecs_t when, uint32_t policyFlags) {
5458     abortPointerSimple(when, policyFlags);
5459 }
5460
5461 void TouchInputMapper::dispatchPointerMouse(nsecs_t when, uint32_t policyFlags) {
5462     mPointerSimple.currentCoords.clear();
5463     mPointerSimple.currentProperties.clear();
5464
5465     bool down, hovering;
5466     if (!mCurrentMouseIdBits.isEmpty()) {
5467         uint32_t id = mCurrentMouseIdBits.firstMarkedBit();
5468         uint32_t currentIndex = mCurrentRawPointerData.idToIndex[id];
5469         if (mLastMouseIdBits.hasBit(id)) {
5470             uint32_t lastIndex = mCurrentRawPointerData.idToIndex[id];
5471             float deltaX = (mCurrentRawPointerData.pointers[currentIndex].x
5472                     - mLastRawPointerData.pointers[lastIndex].x)
5473                     * mPointerXMovementScale;
5474             float deltaY = (mCurrentRawPointerData.pointers[currentIndex].y
5475                     - mLastRawPointerData.pointers[lastIndex].y)
5476                     * mPointerYMovementScale;
5477
5478             rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
5479             mPointerVelocityControl.move(when, &deltaX, &deltaY);
5480
5481             mPointerController->move(deltaX, deltaY);
5482         } else {
5483             mPointerVelocityControl.reset();
5484         }
5485
5486         down = isPointerDown(mCurrentButtonState);
5487         hovering = !down;
5488
5489         float x, y;
5490         mPointerController->getPosition(&x, &y);
5491         mPointerSimple.currentCoords.copyFrom(
5492                 mCurrentCookedPointerData.pointerCoords[currentIndex]);
5493         mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
5494         mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5495         mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
5496                 hovering ? 0.0f : 1.0f);
5497         mPointerSimple.currentProperties.id = 0;
5498         mPointerSimple.currentProperties.toolType =
5499                 mCurrentCookedPointerData.pointerProperties[currentIndex].toolType;
5500     } else {
5501         mPointerVelocityControl.reset();
5502
5503         down = false;
5504         hovering = false;
5505     }
5506
5507     dispatchPointerSimple(when, policyFlags, down, hovering);
5508 }
5509
5510 void TouchInputMapper::abortPointerMouse(nsecs_t when, uint32_t policyFlags) {
5511     abortPointerSimple(when, policyFlags);
5512
5513     mPointerVelocityControl.reset();
5514 }
5515
5516 void TouchInputMapper::dispatchPointerSimple(nsecs_t when, uint32_t policyFlags,
5517         bool down, bool hovering) {
5518     int32_t metaState = getContext()->getGlobalMetaState();
5519
5520     if (mPointerController != NULL) {
5521         if (down || hovering) {
5522             mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_POINTER);
5523             mPointerController->clearSpots();
5524             mPointerController->setButtonState(mCurrentButtonState);
5525             mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
5526         } else if (!down && !hovering && (mPointerSimple.down || mPointerSimple.hovering)) {
5527             mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
5528         }
5529     }
5530
5531     if (mPointerSimple.down && !down) {
5532         mPointerSimple.down = false;
5533
5534         // Send up.
5535         NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
5536                  AMOTION_EVENT_ACTION_UP, 0, metaState, mLastButtonState, 0,
5537                  mViewport.displayId,
5538                  1, &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
5539                  mOrientedXPrecision, mOrientedYPrecision,
5540                  mPointerSimple.downTime);
5541         getListener()->notifyMotion(&args);
5542     }
5543
5544     if (mPointerSimple.hovering && !hovering) {
5545         mPointerSimple.hovering = false;
5546
5547         // Send hover exit.
5548         NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
5549                 AMOTION_EVENT_ACTION_HOVER_EXIT, 0, metaState, mLastButtonState, 0,
5550                 mViewport.displayId,
5551                 1, &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
5552                 mOrientedXPrecision, mOrientedYPrecision,
5553                 mPointerSimple.downTime);
5554         getListener()->notifyMotion(&args);
5555     }
5556
5557     if (down) {
5558         if (!mPointerSimple.down) {
5559             mPointerSimple.down = true;
5560             mPointerSimple.downTime = when;
5561
5562             // Send down.
5563             NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
5564                     AMOTION_EVENT_ACTION_DOWN, 0, metaState, mCurrentButtonState, 0,
5565                     mViewport.displayId,
5566                     1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
5567                     mOrientedXPrecision, mOrientedYPrecision,
5568                     mPointerSimple.downTime);
5569             getListener()->notifyMotion(&args);
5570         }
5571
5572         // Send move.
5573         NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
5574                 AMOTION_EVENT_ACTION_MOVE, 0, metaState, mCurrentButtonState, 0,
5575                 mViewport.displayId,
5576                 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
5577                 mOrientedXPrecision, mOrientedYPrecision,
5578                 mPointerSimple.downTime);
5579         getListener()->notifyMotion(&args);
5580     }
5581
5582     if (hovering) {
5583         if (!mPointerSimple.hovering) {
5584             mPointerSimple.hovering = true;
5585
5586             // Send hover enter.
5587             NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
5588                     AMOTION_EVENT_ACTION_HOVER_ENTER, 0, metaState, mCurrentButtonState, 0,
5589                     mViewport.displayId,
5590                     1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
5591                     mOrientedXPrecision, mOrientedYPrecision,
5592                     mPointerSimple.downTime);
5593             getListener()->notifyMotion(&args);
5594         }
5595
5596         // Send hover move.
5597         NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
5598                 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, metaState, mCurrentButtonState, 0,
5599                 mViewport.displayId,
5600                 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
5601                 mOrientedXPrecision, mOrientedYPrecision,
5602                 mPointerSimple.downTime);
5603         getListener()->notifyMotion(&args);
5604     }
5605
5606     if (mCurrentRawVScroll || mCurrentRawHScroll) {
5607         float vscroll = mCurrentRawVScroll;
5608         float hscroll = mCurrentRawHScroll;
5609         mWheelYVelocityControl.move(when, NULL, &vscroll);
5610         mWheelXVelocityControl.move(when, &hscroll, NULL);
5611
5612         // Send scroll.
5613         PointerCoords pointerCoords;
5614         pointerCoords.copyFrom(mPointerSimple.currentCoords);
5615         pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
5616         pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
5617
5618         NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
5619                 AMOTION_EVENT_ACTION_SCROLL, 0, metaState, mCurrentButtonState, 0,
5620                 mViewport.displayId,
5621                 1, &mPointerSimple.currentProperties, &pointerCoords,
5622                 mOrientedXPrecision, mOrientedYPrecision,
5623                 mPointerSimple.downTime);
5624         getListener()->notifyMotion(&args);
5625     }
5626
5627     // Save state.
5628     if (down || hovering) {
5629         mPointerSimple.lastCoords.copyFrom(mPointerSimple.currentCoords);
5630         mPointerSimple.lastProperties.copyFrom(mPointerSimple.currentProperties);
5631     } else {
5632         mPointerSimple.reset();
5633     }
5634 }
5635
5636 void TouchInputMapper::abortPointerSimple(nsecs_t when, uint32_t policyFlags) {
5637     mPointerSimple.currentCoords.clear();
5638     mPointerSimple.currentProperties.clear();
5639
5640     dispatchPointerSimple(when, policyFlags, false, false);
5641 }
5642
5643 void TouchInputMapper::dispatchMotion(nsecs_t when, uint32_t policyFlags, uint32_t source,
5644         int32_t action, int32_t flags, int32_t metaState, int32_t buttonState, int32_t edgeFlags,
5645         const PointerProperties* properties, const PointerCoords* coords,
5646         const uint32_t* idToIndex, BitSet32 idBits,
5647         int32_t changedId, float xPrecision, float yPrecision, nsecs_t downTime) {
5648     PointerCoords pointerCoords[MAX_POINTERS];
5649     PointerProperties pointerProperties[MAX_POINTERS];
5650     uint32_t pointerCount = 0;
5651     while (!idBits.isEmpty()) {
5652         uint32_t id = idBits.clearFirstMarkedBit();
5653         uint32_t index = idToIndex[id];
5654         pointerProperties[pointerCount].copyFrom(properties[index]);
5655         pointerCoords[pointerCount].copyFrom(coords[index]);
5656
5657         if (changedId >= 0 && id == uint32_t(changedId)) {
5658             action |= pointerCount << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
5659         }
5660
5661         pointerCount += 1;
5662     }
5663
5664     ALOG_ASSERT(pointerCount != 0);
5665
5666     if (changedId >= 0 && pointerCount == 1) {
5667         // Replace initial down and final up action.
5668         // We can compare the action without masking off the changed pointer index
5669         // because we know the index is 0.
5670         if (action == AMOTION_EVENT_ACTION_POINTER_DOWN) {
5671             action = AMOTION_EVENT_ACTION_DOWN;
5672         } else if (action == AMOTION_EVENT_ACTION_POINTER_UP) {
5673             action = AMOTION_EVENT_ACTION_UP;
5674         } else {
5675             // Can't happen.
5676             ALOG_ASSERT(false);
5677         }
5678     }
5679
5680     NotifyMotionArgs args(when, getDeviceId(), source, policyFlags,
5681             action, flags, metaState, buttonState, edgeFlags,
5682             mViewport.displayId, pointerCount, pointerProperties, pointerCoords,
5683             xPrecision, yPrecision, downTime);
5684     getListener()->notifyMotion(&args);
5685 }
5686
5687 bool TouchInputMapper::updateMovedPointers(const PointerProperties* inProperties,
5688         const PointerCoords* inCoords, const uint32_t* inIdToIndex,
5689         PointerProperties* outProperties, PointerCoords* outCoords, const uint32_t* outIdToIndex,
5690         BitSet32 idBits) const {
5691     bool changed = false;
5692     while (!idBits.isEmpty()) {
5693         uint32_t id = idBits.clearFirstMarkedBit();
5694         uint32_t inIndex = inIdToIndex[id];
5695         uint32_t outIndex = outIdToIndex[id];
5696
5697         const PointerProperties& curInProperties = inProperties[inIndex];
5698         const PointerCoords& curInCoords = inCoords[inIndex];
5699         PointerProperties& curOutProperties = outProperties[outIndex];
5700         PointerCoords& curOutCoords = outCoords[outIndex];
5701
5702         if (curInProperties != curOutProperties) {
5703             curOutProperties.copyFrom(curInProperties);
5704             changed = true;
5705         }
5706
5707         if (curInCoords != curOutCoords) {
5708             curOutCoords.copyFrom(curInCoords);
5709             changed = true;
5710         }
5711     }
5712     return changed;
5713 }
5714
5715 void TouchInputMapper::fadePointer() {
5716     if (mPointerController != NULL) {
5717         mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
5718     }
5719 }
5720
5721 bool TouchInputMapper::isPointInsideSurface(int32_t x, int32_t y) {
5722     return x >= mRawPointerAxes.x.minValue && x <= mRawPointerAxes.x.maxValue
5723             && y >= mRawPointerAxes.y.minValue && y <= mRawPointerAxes.y.maxValue;
5724 }
5725
5726 const TouchInputMapper::VirtualKey* TouchInputMapper::findVirtualKeyHit(
5727         int32_t x, int32_t y) {
5728     size_t numVirtualKeys = mVirtualKeys.size();
5729     for (size_t i = 0; i < numVirtualKeys; i++) {
5730         const VirtualKey& virtualKey = mVirtualKeys[i];
5731
5732 #if DEBUG_VIRTUAL_KEYS
5733         ALOGD("VirtualKeys: Hit test (%d, %d): keyCode=%d, scanCode=%d, "
5734                 "left=%d, top=%d, right=%d, bottom=%d",
5735                 x, y,
5736                 virtualKey.keyCode, virtualKey.scanCode,
5737                 virtualKey.hitLeft, virtualKey.hitTop,
5738                 virtualKey.hitRight, virtualKey.hitBottom);
5739 #endif
5740
5741         if (virtualKey.isHit(x, y)) {
5742             return & virtualKey;
5743         }
5744     }
5745
5746     return NULL;
5747 }
5748
5749 void TouchInputMapper::assignPointerIds() {
5750     uint32_t currentPointerCount = mCurrentRawPointerData.pointerCount;
5751     uint32_t lastPointerCount = mLastRawPointerData.pointerCount;
5752
5753     mCurrentRawPointerData.clearIdBits();
5754
5755     if (currentPointerCount == 0) {
5756         // No pointers to assign.
5757         return;
5758     }
5759
5760     if (lastPointerCount == 0) {
5761         // All pointers are new.
5762         for (uint32_t i = 0; i < currentPointerCount; i++) {
5763             uint32_t id = i;
5764             mCurrentRawPointerData.pointers[i].id = id;
5765             mCurrentRawPointerData.idToIndex[id] = i;
5766             mCurrentRawPointerData.markIdBit(id, mCurrentRawPointerData.isHovering(i));
5767         }
5768         return;
5769     }
5770
5771     if (currentPointerCount == 1 && lastPointerCount == 1
5772             && mCurrentRawPointerData.pointers[0].toolType
5773                     == mLastRawPointerData.pointers[0].toolType) {
5774         // Only one pointer and no change in count so it must have the same id as before.
5775         uint32_t id = mLastRawPointerData.pointers[0].id;
5776         mCurrentRawPointerData.pointers[0].id = id;
5777         mCurrentRawPointerData.idToIndex[id] = 0;
5778         mCurrentRawPointerData.markIdBit(id, mCurrentRawPointerData.isHovering(0));
5779         return;
5780     }
5781
5782     // General case.
5783     // We build a heap of squared euclidean distances between current and last pointers
5784     // associated with the current and last pointer indices.  Then, we find the best
5785     // match (by distance) for each current pointer.
5786     // The pointers must have the same tool type but it is possible for them to
5787     // transition from hovering to touching or vice-versa while retaining the same id.
5788     PointerDistanceHeapElement heap[MAX_POINTERS * MAX_POINTERS];
5789
5790     uint32_t heapSize = 0;
5791     for (uint32_t currentPointerIndex = 0; currentPointerIndex < currentPointerCount;
5792             currentPointerIndex++) {
5793         for (uint32_t lastPointerIndex = 0; lastPointerIndex < lastPointerCount;
5794                 lastPointerIndex++) {
5795             const RawPointerData::Pointer& currentPointer =
5796                     mCurrentRawPointerData.pointers[currentPointerIndex];
5797             const RawPointerData::Pointer& lastPointer =
5798                     mLastRawPointerData.pointers[lastPointerIndex];
5799             if (currentPointer.toolType == lastPointer.toolType) {
5800                 int64_t deltaX = currentPointer.x - lastPointer.x;
5801                 int64_t deltaY = currentPointer.y - lastPointer.y;
5802
5803                 uint64_t distance = uint64_t(deltaX * deltaX + deltaY * deltaY);
5804
5805                 // Insert new element into the heap (sift up).
5806                 heap[heapSize].currentPointerIndex = currentPointerIndex;
5807                 heap[heapSize].lastPointerIndex = lastPointerIndex;
5808                 heap[heapSize].distance = distance;
5809                 heapSize += 1;
5810             }
5811         }
5812     }
5813
5814     // Heapify
5815     for (uint32_t startIndex = heapSize / 2; startIndex != 0; ) {
5816         startIndex -= 1;
5817         for (uint32_t parentIndex = startIndex; ;) {
5818             uint32_t childIndex = parentIndex * 2 + 1;
5819             if (childIndex >= heapSize) {
5820                 break;
5821             }
5822
5823             if (childIndex + 1 < heapSize
5824                     && heap[childIndex + 1].distance < heap[childIndex].distance) {
5825                 childIndex += 1;
5826             }
5827
5828             if (heap[parentIndex].distance <= heap[childIndex].distance) {
5829                 break;
5830             }
5831
5832             swap(heap[parentIndex], heap[childIndex]);
5833             parentIndex = childIndex;
5834         }
5835     }
5836
5837 #if DEBUG_POINTER_ASSIGNMENT
5838     ALOGD("assignPointerIds - initial distance min-heap: size=%d", heapSize);
5839     for (size_t i = 0; i < heapSize; i++) {
5840         ALOGD("  heap[%d]: cur=%d, last=%d, distance=%lld",
5841                 i, heap[i].currentPointerIndex, heap[i].lastPointerIndex,
5842                 heap[i].distance);
5843     }
5844 #endif
5845
5846     // Pull matches out by increasing order of distance.
5847     // To avoid reassigning pointers that have already been matched, the loop keeps track
5848     // of which last and current pointers have been matched using the matchedXXXBits variables.
5849     // It also tracks the used pointer id bits.
5850     BitSet32 matchedLastBits(0);
5851     BitSet32 matchedCurrentBits(0);
5852     BitSet32 usedIdBits(0);
5853     bool first = true;
5854     for (uint32_t i = min(currentPointerCount, lastPointerCount); heapSize > 0 && i > 0; i--) {
5855         while (heapSize > 0) {
5856             if (first) {
5857                 // The first time through the loop, we just consume the root element of
5858                 // the heap (the one with smallest distance).
5859                 first = false;
5860             } else {
5861                 // Previous iterations consumed the root element of the heap.
5862                 // Pop root element off of the heap (sift down).
5863                 heap[0] = heap[heapSize];
5864                 for (uint32_t parentIndex = 0; ;) {
5865                     uint32_t childIndex = parentIndex * 2 + 1;
5866                     if (childIndex >= heapSize) {
5867                         break;
5868                     }
5869
5870                     if (childIndex + 1 < heapSize
5871                             && heap[childIndex + 1].distance < heap[childIndex].distance) {
5872                         childIndex += 1;
5873                     }
5874
5875                     if (heap[parentIndex].distance <= heap[childIndex].distance) {
5876                         break;
5877                     }
5878
5879                     swap(heap[parentIndex], heap[childIndex]);
5880                     parentIndex = childIndex;
5881                 }
5882
5883 #if DEBUG_POINTER_ASSIGNMENT
5884                 ALOGD("assignPointerIds - reduced distance min-heap: size=%d", heapSize);
5885                 for (size_t i = 0; i < heapSize; i++) {
5886                     ALOGD("  heap[%d]: cur=%d, last=%d, distance=%lld",
5887                             i, heap[i].currentPointerIndex, heap[i].lastPointerIndex,
5888                             heap[i].distance);
5889                 }
5890 #endif
5891             }
5892
5893             heapSize -= 1;
5894
5895             uint32_t currentPointerIndex = heap[0].currentPointerIndex;
5896             if (matchedCurrentBits.hasBit(currentPointerIndex)) continue; // already matched
5897
5898             uint32_t lastPointerIndex = heap[0].lastPointerIndex;
5899             if (matchedLastBits.hasBit(lastPointerIndex)) continue; // already matched
5900
5901             matchedCurrentBits.markBit(currentPointerIndex);
5902             matchedLastBits.markBit(lastPointerIndex);
5903
5904             uint32_t id = mLastRawPointerData.pointers[lastPointerIndex].id;
5905             mCurrentRawPointerData.pointers[currentPointerIndex].id = id;
5906             mCurrentRawPointerData.idToIndex[id] = currentPointerIndex;
5907             mCurrentRawPointerData.markIdBit(id,
5908                     mCurrentRawPointerData.isHovering(currentPointerIndex));
5909             usedIdBits.markBit(id);
5910
5911 #if DEBUG_POINTER_ASSIGNMENT
5912             ALOGD("assignPointerIds - matched: cur=%d, last=%d, id=%d, distance=%lld",
5913                     lastPointerIndex, currentPointerIndex, id, heap[0].distance);
5914 #endif
5915             break;
5916         }
5917     }
5918
5919     // Assign fresh ids to pointers that were not matched in the process.
5920     for (uint32_t i = currentPointerCount - matchedCurrentBits.count(); i != 0; i--) {
5921         uint32_t currentPointerIndex = matchedCurrentBits.markFirstUnmarkedBit();
5922         uint32_t id = usedIdBits.markFirstUnmarkedBit();
5923
5924         mCurrentRawPointerData.pointers[currentPointerIndex].id = id;
5925         mCurrentRawPointerData.idToIndex[id] = currentPointerIndex;
5926         mCurrentRawPointerData.markIdBit(id,
5927                 mCurrentRawPointerData.isHovering(currentPointerIndex));
5928
5929 #if DEBUG_POINTER_ASSIGNMENT
5930         ALOGD("assignPointerIds - assigned: cur=%d, id=%d",
5931                 currentPointerIndex, id);
5932 #endif
5933     }
5934 }
5935
5936 int32_t TouchInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
5937     if (mCurrentVirtualKey.down && mCurrentVirtualKey.keyCode == keyCode) {
5938         return AKEY_STATE_VIRTUAL;
5939     }
5940
5941     size_t numVirtualKeys = mVirtualKeys.size();
5942     for (size_t i = 0; i < numVirtualKeys; i++) {
5943         const VirtualKey& virtualKey = mVirtualKeys[i];
5944         if (virtualKey.keyCode == keyCode) {
5945             return AKEY_STATE_UP;
5946         }
5947     }
5948
5949     return AKEY_STATE_UNKNOWN;
5950 }
5951
5952 int32_t TouchInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
5953     if (mCurrentVirtualKey.down && mCurrentVirtualKey.scanCode == scanCode) {
5954         return AKEY_STATE_VIRTUAL;
5955     }
5956
5957     size_t numVirtualKeys = mVirtualKeys.size();
5958     for (size_t i = 0; i < numVirtualKeys; i++) {
5959         const VirtualKey& virtualKey = mVirtualKeys[i];
5960         if (virtualKey.scanCode == scanCode) {
5961             return AKEY_STATE_UP;
5962         }
5963     }
5964
5965     return AKEY_STATE_UNKNOWN;
5966 }
5967
5968 bool TouchInputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
5969         const int32_t* keyCodes, uint8_t* outFlags) {
5970     size_t numVirtualKeys = mVirtualKeys.size();
5971     for (size_t i = 0; i < numVirtualKeys; i++) {
5972         const VirtualKey& virtualKey = mVirtualKeys[i];
5973
5974         for (size_t i = 0; i < numCodes; i++) {
5975             if (virtualKey.keyCode == keyCodes[i]) {
5976                 outFlags[i] = 1;
5977             }
5978         }
5979     }
5980
5981     return true;
5982 }
5983
5984
5985 // --- SingleTouchInputMapper ---
5986
5987 SingleTouchInputMapper::SingleTouchInputMapper(InputDevice* device) :
5988         TouchInputMapper(device) {
5989 }
5990
5991 SingleTouchInputMapper::~SingleTouchInputMapper() {
5992 }
5993
5994 void SingleTouchInputMapper::reset(nsecs_t when) {
5995     mSingleTouchMotionAccumulator.reset(getDevice());
5996
5997     TouchInputMapper::reset(when);
5998 }
5999
6000 void SingleTouchInputMapper::process(const RawEvent* rawEvent) {
6001     TouchInputMapper::process(rawEvent);
6002
6003     mSingleTouchMotionAccumulator.process(rawEvent);
6004 }
6005
6006 void SingleTouchInputMapper::syncTouch(nsecs_t when, bool* outHavePointerIds) {
6007     if (mTouchButtonAccumulator.isToolActive()) {
6008         mCurrentRawPointerData.pointerCount = 1;
6009         mCurrentRawPointerData.idToIndex[0] = 0;
6010
6011         bool isHovering = mTouchButtonAccumulator.getToolType() != AMOTION_EVENT_TOOL_TYPE_MOUSE
6012                 && (mTouchButtonAccumulator.isHovering()
6013                         || (mRawPointerAxes.pressure.valid
6014                                 && mSingleTouchMotionAccumulator.getAbsolutePressure() <= 0));
6015         mCurrentRawPointerData.markIdBit(0, isHovering);
6016
6017         RawPointerData::Pointer& outPointer = mCurrentRawPointerData.pointers[0];
6018         outPointer.id = 0;
6019         outPointer.x = mSingleTouchMotionAccumulator.getAbsoluteX();
6020         outPointer.y = mSingleTouchMotionAccumulator.getAbsoluteY();
6021         outPointer.pressure = mSingleTouchMotionAccumulator.getAbsolutePressure();
6022         outPointer.touchMajor = 0;
6023         outPointer.touchMinor = 0;
6024         outPointer.toolMajor = mSingleTouchMotionAccumulator.getAbsoluteToolWidth();
6025         outPointer.toolMinor = mSingleTouchMotionAccumulator.getAbsoluteToolWidth();
6026         outPointer.orientation = 0;
6027         outPointer.distance = mSingleTouchMotionAccumulator.getAbsoluteDistance();
6028         outPointer.tiltX = mSingleTouchMotionAccumulator.getAbsoluteTiltX();
6029         outPointer.tiltY = mSingleTouchMotionAccumulator.getAbsoluteTiltY();
6030         outPointer.toolType = mTouchButtonAccumulator.getToolType();
6031         if (outPointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
6032             outPointer.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
6033         }
6034         outPointer.isHovering = isHovering;
6035     }
6036 }
6037
6038 void SingleTouchInputMapper::configureRawPointerAxes() {
6039     TouchInputMapper::configureRawPointerAxes();
6040
6041     getAbsoluteAxisInfo(ABS_X, &mRawPointerAxes.x);
6042     getAbsoluteAxisInfo(ABS_Y, &mRawPointerAxes.y);
6043     getAbsoluteAxisInfo(ABS_PRESSURE, &mRawPointerAxes.pressure);
6044     getAbsoluteAxisInfo(ABS_TOOL_WIDTH, &mRawPointerAxes.toolMajor);
6045     getAbsoluteAxisInfo(ABS_DISTANCE, &mRawPointerAxes.distance);
6046     getAbsoluteAxisInfo(ABS_TILT_X, &mRawPointerAxes.tiltX);
6047     getAbsoluteAxisInfo(ABS_TILT_Y, &mRawPointerAxes.tiltY);
6048 }
6049
6050 bool SingleTouchInputMapper::hasStylus() const {
6051     return mTouchButtonAccumulator.hasStylus();
6052 }
6053
6054
6055 // --- MultiTouchInputMapper ---
6056
6057 MultiTouchInputMapper::MultiTouchInputMapper(InputDevice* device) :
6058         TouchInputMapper(device) {
6059 }
6060
6061 MultiTouchInputMapper::~MultiTouchInputMapper() {
6062 }
6063
6064 void MultiTouchInputMapper::reset(nsecs_t when) {
6065     mMultiTouchMotionAccumulator.reset(getDevice());
6066
6067     mPointerIdBits.clear();
6068
6069     TouchInputMapper::reset(when);
6070 }
6071
6072 void MultiTouchInputMapper::process(const RawEvent* rawEvent) {
6073     TouchInputMapper::process(rawEvent);
6074
6075     mMultiTouchMotionAccumulator.process(rawEvent);
6076 }
6077
6078 void MultiTouchInputMapper::syncTouch(nsecs_t when, bool* outHavePointerIds) {
6079     size_t inCount = mMultiTouchMotionAccumulator.getSlotCount();
6080     size_t outCount = 0;
6081     BitSet32 newPointerIdBits;
6082
6083     for (size_t inIndex = 0; inIndex < inCount; inIndex++) {
6084         const MultiTouchMotionAccumulator::Slot* inSlot =
6085                 mMultiTouchMotionAccumulator.getSlot(inIndex);
6086         if (!inSlot->isInUse()) {
6087             continue;
6088         }
6089
6090         if (outCount >= MAX_POINTERS) {
6091 #if DEBUG_POINTERS
6092             ALOGD("MultiTouch device %s emitted more than maximum of %d pointers; "
6093                     "ignoring the rest.",
6094                     getDeviceName().string(), MAX_POINTERS);
6095 #endif
6096             break; // too many fingers!
6097         }
6098
6099         RawPointerData::Pointer& outPointer = mCurrentRawPointerData.pointers[outCount];
6100         outPointer.x = inSlot->getX();
6101         outPointer.y = inSlot->getY();
6102         outPointer.pressure = inSlot->getPressure();
6103         outPointer.touchMajor = inSlot->getTouchMajor();
6104         outPointer.touchMinor = inSlot->getTouchMinor();
6105         outPointer.toolMajor = inSlot->getToolMajor();
6106         outPointer.toolMinor = inSlot->getToolMinor();
6107         outPointer.orientation = inSlot->getOrientation();
6108         outPointer.distance = inSlot->getDistance();
6109         outPointer.tiltX = 0;
6110         outPointer.tiltY = 0;
6111
6112         outPointer.toolType = inSlot->getToolType();
6113         if (outPointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
6114             outPointer.toolType = mTouchButtonAccumulator.getToolType();
6115             if (outPointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
6116                 outPointer.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
6117             }
6118         }
6119
6120         bool isHovering = mTouchButtonAccumulator.getToolType() != AMOTION_EVENT_TOOL_TYPE_MOUSE
6121                 && (mTouchButtonAccumulator.isHovering()
6122                         || (mRawPointerAxes.pressure.valid && inSlot->getPressure() <= 0));
6123         outPointer.isHovering = isHovering;
6124
6125         // Assign pointer id using tracking id if available.
6126         if (*outHavePointerIds) {
6127             int32_t trackingId = inSlot->getTrackingId();
6128             int32_t id = -1;
6129             if (trackingId >= 0) {
6130                 for (BitSet32 idBits(mPointerIdBits); !idBits.isEmpty(); ) {
6131                     uint32_t n = idBits.clearFirstMarkedBit();
6132                     if (mPointerTrackingIdMap[n] == trackingId) {
6133                         id = n;
6134                     }
6135                 }
6136
6137                 if (id < 0 && !mPointerIdBits.isFull()) {
6138                     id = mPointerIdBits.markFirstUnmarkedBit();
6139                     mPointerTrackingIdMap[id] = trackingId;
6140                 }
6141             }
6142             if (id < 0) {
6143                 *outHavePointerIds = false;
6144                 mCurrentRawPointerData.clearIdBits();
6145                 newPointerIdBits.clear();
6146             } else {
6147                 outPointer.id = id;
6148                 mCurrentRawPointerData.idToIndex[id] = outCount;
6149                 mCurrentRawPointerData.markIdBit(id, isHovering);
6150                 newPointerIdBits.markBit(id);
6151             }
6152         }
6153
6154         outCount += 1;
6155     }
6156
6157     mCurrentRawPointerData.pointerCount = outCount;
6158     mPointerIdBits = newPointerIdBits;
6159
6160     mMultiTouchMotionAccumulator.finishSync();
6161 }
6162
6163 void MultiTouchInputMapper::configureRawPointerAxes() {
6164     TouchInputMapper::configureRawPointerAxes();
6165
6166     getAbsoluteAxisInfo(ABS_MT_POSITION_X, &mRawPointerAxes.x);
6167     getAbsoluteAxisInfo(ABS_MT_POSITION_Y, &mRawPointerAxes.y);
6168     getAbsoluteAxisInfo(ABS_MT_TOUCH_MAJOR, &mRawPointerAxes.touchMajor);
6169     getAbsoluteAxisInfo(ABS_MT_TOUCH_MINOR, &mRawPointerAxes.touchMinor);
6170     getAbsoluteAxisInfo(ABS_MT_WIDTH_MAJOR, &mRawPointerAxes.toolMajor);
6171     getAbsoluteAxisInfo(ABS_MT_WIDTH_MINOR, &mRawPointerAxes.toolMinor);
6172     getAbsoluteAxisInfo(ABS_MT_ORIENTATION, &mRawPointerAxes.orientation);
6173     getAbsoluteAxisInfo(ABS_MT_PRESSURE, &mRawPointerAxes.pressure);
6174     getAbsoluteAxisInfo(ABS_MT_DISTANCE, &mRawPointerAxes.distance);
6175     getAbsoluteAxisInfo(ABS_MT_TRACKING_ID, &mRawPointerAxes.trackingId);
6176     getAbsoluteAxisInfo(ABS_MT_SLOT, &mRawPointerAxes.slot);
6177
6178     if (mRawPointerAxes.trackingId.valid
6179             && mRawPointerAxes.slot.valid
6180             && mRawPointerAxes.slot.minValue == 0 && mRawPointerAxes.slot.maxValue > 0) {
6181         size_t slotCount = mRawPointerAxes.slot.maxValue + 1;
6182         if (slotCount > MAX_SLOTS) {
6183             ALOGW("MultiTouch Device %s reported %zu slots but the framework "
6184                     "only supports a maximum of %zu slots at this time.",
6185                     getDeviceName().string(), slotCount, MAX_SLOTS);
6186             slotCount = MAX_SLOTS;
6187         }
6188         mMultiTouchMotionAccumulator.configure(getDevice(),
6189                 slotCount, true /*usingSlotsProtocol*/);
6190     } else {
6191         mMultiTouchMotionAccumulator.configure(getDevice(),
6192                 MAX_POINTERS, false /*usingSlotsProtocol*/);
6193     }
6194 }
6195
6196 bool MultiTouchInputMapper::hasStylus() const {
6197     return mMultiTouchMotionAccumulator.hasStylus()
6198             || mTouchButtonAccumulator.hasStylus();
6199 }
6200
6201
6202 // --- JoystickInputMapper ---
6203
6204 JoystickInputMapper::JoystickInputMapper(InputDevice* device) :
6205         InputMapper(device) {
6206 }
6207
6208 JoystickInputMapper::~JoystickInputMapper() {
6209 }
6210
6211 uint32_t JoystickInputMapper::getSources() {
6212     return AINPUT_SOURCE_JOYSTICK;
6213 }
6214
6215 void JoystickInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
6216     InputMapper::populateDeviceInfo(info);
6217
6218     for (size_t i = 0; i < mAxes.size(); i++) {
6219         const Axis& axis = mAxes.valueAt(i);
6220         addMotionRange(axis.axisInfo.axis, axis, info);
6221
6222         if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
6223             addMotionRange(axis.axisInfo.highAxis, axis, info);
6224
6225         }
6226     }
6227 }
6228
6229 void JoystickInputMapper::addMotionRange(int32_t axisId, const Axis& axis,
6230         InputDeviceInfo* info) {
6231     info->addMotionRange(axisId, AINPUT_SOURCE_JOYSTICK,
6232             axis.min, axis.max, axis.flat, axis.fuzz, axis.resolution);
6233     /* In order to ease the transition for developers from using the old axes
6234      * to the newer, more semantically correct axes, we'll continue to register
6235      * the old axes as duplicates of their corresponding new ones.  */
6236     int32_t compatAxis = getCompatAxis(axisId);
6237     if (compatAxis >= 0) {
6238         info->addMotionRange(compatAxis, AINPUT_SOURCE_JOYSTICK,
6239                 axis.min, axis.max, axis.flat, axis.fuzz, axis.resolution);
6240     }
6241 }
6242
6243 /* A mapping from axes the joystick actually has to the axes that should be
6244  * artificially created for compatibility purposes.
6245  * Returns -1 if no compatibility axis is needed. */
6246 int32_t JoystickInputMapper::getCompatAxis(int32_t axis) {
6247     switch(axis) {
6248     case AMOTION_EVENT_AXIS_LTRIGGER:
6249         return AMOTION_EVENT_AXIS_BRAKE;
6250     case AMOTION_EVENT_AXIS_RTRIGGER:
6251         return AMOTION_EVENT_AXIS_GAS;
6252     }
6253     return -1;
6254 }
6255
6256 void JoystickInputMapper::dump(String8& dump) {
6257     dump.append(INDENT2 "Joystick Input Mapper:\n");
6258
6259     dump.append(INDENT3 "Axes:\n");
6260     size_t numAxes = mAxes.size();
6261     for (size_t i = 0; i < numAxes; i++) {
6262         const Axis& axis = mAxes.valueAt(i);
6263         const char* label = getAxisLabel(axis.axisInfo.axis);
6264         if (label) {
6265             dump.appendFormat(INDENT4 "%s", label);
6266         } else {
6267             dump.appendFormat(INDENT4 "%d", axis.axisInfo.axis);
6268         }
6269         if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
6270             label = getAxisLabel(axis.axisInfo.highAxis);
6271             if (label) {
6272                 dump.appendFormat(" / %s (split at %d)", label, axis.axisInfo.splitValue);
6273             } else {
6274                 dump.appendFormat(" / %d (split at %d)", axis.axisInfo.highAxis,
6275                         axis.axisInfo.splitValue);
6276             }
6277         } else if (axis.axisInfo.mode == AxisInfo::MODE_INVERT) {
6278             dump.append(" (invert)");
6279         }
6280
6281         dump.appendFormat(": min=%0.5f, max=%0.5f, flat=%0.5f, fuzz=%0.5f, resolution=%0.5f\n",
6282                 axis.min, axis.max, axis.flat, axis.fuzz, axis.resolution);
6283         dump.appendFormat(INDENT4 "  scale=%0.5f, offset=%0.5f, "
6284                 "highScale=%0.5f, highOffset=%0.5f\n",
6285                 axis.scale, axis.offset, axis.highScale, axis.highOffset);
6286         dump.appendFormat(INDENT4 "  rawAxis=%d, rawMin=%d, rawMax=%d, "
6287                 "rawFlat=%d, rawFuzz=%d, rawResolution=%d\n",
6288                 mAxes.keyAt(i), axis.rawAxisInfo.minValue, axis.rawAxisInfo.maxValue,
6289                 axis.rawAxisInfo.flat, axis.rawAxisInfo.fuzz, axis.rawAxisInfo.resolution);
6290     }
6291 }
6292
6293 void JoystickInputMapper::configure(nsecs_t when,
6294         const InputReaderConfiguration* config, uint32_t changes) {
6295     InputMapper::configure(when, config, changes);
6296
6297     if (!changes) { // first time only
6298         // Collect all axes.
6299         for (int32_t abs = 0; abs <= ABS_MAX; abs++) {
6300             if (!(getAbsAxisUsage(abs, getDevice()->getClasses())
6301                     & INPUT_DEVICE_CLASS_JOYSTICK)) {
6302                 continue; // axis must be claimed by a different device
6303             }
6304
6305             RawAbsoluteAxisInfo rawAxisInfo;
6306             getAbsoluteAxisInfo(abs, &rawAxisInfo);
6307             if (rawAxisInfo.valid) {
6308                 // Map axis.
6309                 AxisInfo axisInfo;
6310                 bool explicitlyMapped = !getEventHub()->mapAxis(getDeviceId(), abs, &axisInfo);
6311                 if (!explicitlyMapped) {
6312                     // Axis is not explicitly mapped, will choose a generic axis later.
6313                     axisInfo.mode = AxisInfo::MODE_NORMAL;
6314                     axisInfo.axis = -1;
6315                 }
6316
6317                 // Apply flat override.
6318                 int32_t rawFlat = axisInfo.flatOverride < 0
6319                         ? rawAxisInfo.flat : axisInfo.flatOverride;
6320
6321                 // Calculate scaling factors and limits.
6322                 Axis axis;
6323                 if (axisInfo.mode == AxisInfo::MODE_SPLIT) {
6324                     float scale = 1.0f / (axisInfo.splitValue - rawAxisInfo.minValue);
6325                     float highScale = 1.0f / (rawAxisInfo.maxValue - axisInfo.splitValue);
6326                     axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
6327                             scale, 0.0f, highScale, 0.0f,
6328                             0.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale,
6329                             rawAxisInfo.resolution * scale);
6330                 } else if (isCenteredAxis(axisInfo.axis)) {
6331                     float scale = 2.0f / (rawAxisInfo.maxValue - rawAxisInfo.minValue);
6332                     float offset = avg(rawAxisInfo.minValue, rawAxisInfo.maxValue) * -scale;
6333                     axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
6334                             scale, offset, scale, offset,
6335                             -1.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale,
6336                             rawAxisInfo.resolution * scale);
6337                 } else {
6338                     float scale = 1.0f / (rawAxisInfo.maxValue - rawAxisInfo.minValue);
6339                     axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
6340                             scale, 0.0f, scale, 0.0f,
6341                             0.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale,
6342                             rawAxisInfo.resolution * scale);
6343                 }
6344
6345                 // To eliminate noise while the joystick is at rest, filter out small variations
6346                 // in axis values up front.
6347                 axis.filter = axis.fuzz ? axis.fuzz : axis.flat * 0.25f;
6348
6349                 mAxes.add(abs, axis);
6350             }
6351         }
6352
6353         // If there are too many axes, start dropping them.
6354         // Prefer to keep explicitly mapped axes.
6355         if (mAxes.size() > PointerCoords::MAX_AXES) {
6356             ALOGI("Joystick '%s' has %zu axes but the framework only supports a maximum of %d.",
6357                     getDeviceName().string(), mAxes.size(), PointerCoords::MAX_AXES);
6358             pruneAxes(true);
6359             pruneAxes(false);
6360         }
6361
6362         // Assign generic axis ids to remaining axes.
6363         int32_t nextGenericAxisId = AMOTION_EVENT_AXIS_GENERIC_1;
6364         size_t numAxes = mAxes.size();
6365         for (size_t i = 0; i < numAxes; i++) {
6366             Axis& axis = mAxes.editValueAt(i);
6367             if (axis.axisInfo.axis < 0) {
6368                 while (nextGenericAxisId <= AMOTION_EVENT_AXIS_GENERIC_16
6369                         && haveAxis(nextGenericAxisId)) {
6370                     nextGenericAxisId += 1;
6371                 }
6372
6373                 if (nextGenericAxisId <= AMOTION_EVENT_AXIS_GENERIC_16) {
6374                     axis.axisInfo.axis = nextGenericAxisId;
6375                     nextGenericAxisId += 1;
6376                 } else {
6377                     ALOGI("Ignoring joystick '%s' axis %d because all of the generic axis ids "
6378                             "have already been assigned to other axes.",
6379                             getDeviceName().string(), mAxes.keyAt(i));
6380                     mAxes.removeItemsAt(i--);
6381                     numAxes -= 1;
6382                 }
6383             }
6384         }
6385     }
6386 }
6387
6388 bool JoystickInputMapper::haveAxis(int32_t axisId) {
6389     size_t numAxes = mAxes.size();
6390     for (size_t i = 0; i < numAxes; i++) {
6391         const Axis& axis = mAxes.valueAt(i);
6392         if (axis.axisInfo.axis == axisId
6393                 || (axis.axisInfo.mode == AxisInfo::MODE_SPLIT
6394                         && axis.axisInfo.highAxis == axisId)) {
6395             return true;
6396         }
6397     }
6398     return false;
6399 }
6400
6401 void JoystickInputMapper::pruneAxes(bool ignoreExplicitlyMappedAxes) {
6402     size_t i = mAxes.size();
6403     while (mAxes.size() > PointerCoords::MAX_AXES && i-- > 0) {
6404         if (ignoreExplicitlyMappedAxes && mAxes.valueAt(i).explicitlyMapped) {
6405             continue;
6406         }
6407         ALOGI("Discarding joystick '%s' axis %d because there are too many axes.",
6408                 getDeviceName().string(), mAxes.keyAt(i));
6409         mAxes.removeItemsAt(i);
6410     }
6411 }
6412
6413 bool JoystickInputMapper::isCenteredAxis(int32_t axis) {
6414     switch (axis) {
6415     case AMOTION_EVENT_AXIS_X:
6416     case AMOTION_EVENT_AXIS_Y:
6417     case AMOTION_EVENT_AXIS_Z:
6418     case AMOTION_EVENT_AXIS_RX:
6419     case AMOTION_EVENT_AXIS_RY:
6420     case AMOTION_EVENT_AXIS_RZ:
6421     case AMOTION_EVENT_AXIS_HAT_X:
6422     case AMOTION_EVENT_AXIS_HAT_Y:
6423     case AMOTION_EVENT_AXIS_ORIENTATION:
6424     case AMOTION_EVENT_AXIS_RUDDER:
6425     case AMOTION_EVENT_AXIS_WHEEL:
6426         return true;
6427     default:
6428         return false;
6429     }
6430 }
6431
6432 void JoystickInputMapper::reset(nsecs_t when) {
6433     // Recenter all axes.
6434     size_t numAxes = mAxes.size();
6435     for (size_t i = 0; i < numAxes; i++) {
6436         Axis& axis = mAxes.editValueAt(i);
6437         axis.resetValue();
6438     }
6439
6440     InputMapper::reset(when);
6441 }
6442
6443 void JoystickInputMapper::process(const RawEvent* rawEvent) {
6444     switch (rawEvent->type) {
6445     case EV_ABS: {
6446         ssize_t index = mAxes.indexOfKey(rawEvent->code);
6447         if (index >= 0) {
6448             Axis& axis = mAxes.editValueAt(index);
6449             float newValue, highNewValue;
6450             switch (axis.axisInfo.mode) {
6451             case AxisInfo::MODE_INVERT:
6452                 newValue = (axis.rawAxisInfo.maxValue - rawEvent->value)
6453                         * axis.scale + axis.offset;
6454                 highNewValue = 0.0f;
6455                 break;
6456             case AxisInfo::MODE_SPLIT:
6457                 if (rawEvent->value < axis.axisInfo.splitValue) {
6458                     newValue = (axis.axisInfo.splitValue - rawEvent->value)
6459                             * axis.scale + axis.offset;
6460                     highNewValue = 0.0f;
6461                 } else if (rawEvent->value > axis.axisInfo.splitValue) {
6462                     newValue = 0.0f;
6463                     highNewValue = (rawEvent->value - axis.axisInfo.splitValue)
6464                             * axis.highScale + axis.highOffset;
6465                 } else {
6466                     newValue = 0.0f;
6467                     highNewValue = 0.0f;
6468                 }
6469                 break;
6470             default:
6471                 newValue = rawEvent->value * axis.scale + axis.offset;
6472                 highNewValue = 0.0f;
6473                 break;
6474             }
6475             axis.newValue = newValue;
6476             axis.highNewValue = highNewValue;
6477         }
6478         break;
6479     }
6480
6481     case EV_SYN:
6482         switch (rawEvent->code) {
6483         case SYN_REPORT:
6484             sync(rawEvent->when, false /*force*/);
6485             break;
6486         }
6487         break;
6488     }
6489 }
6490
6491 void JoystickInputMapper::sync(nsecs_t when, bool force) {
6492     if (!filterAxes(force)) {
6493         return;
6494     }
6495
6496     int32_t metaState = mContext->getGlobalMetaState();
6497     int32_t buttonState = 0;
6498
6499     PointerProperties pointerProperties;
6500     pointerProperties.clear();
6501     pointerProperties.id = 0;
6502     pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
6503
6504     PointerCoords pointerCoords;
6505     pointerCoords.clear();
6506
6507     size_t numAxes = mAxes.size();
6508     for (size_t i = 0; i < numAxes; i++) {
6509         const Axis& axis = mAxes.valueAt(i);
6510         setPointerCoordsAxisValue(&pointerCoords, axis.axisInfo.axis, axis.currentValue);
6511         if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
6512             setPointerCoordsAxisValue(&pointerCoords, axis.axisInfo.highAxis,
6513                     axis.highCurrentValue);
6514         }
6515     }
6516
6517     // Moving a joystick axis should not wake the device because joysticks can
6518     // be fairly noisy even when not in use.  On the other hand, pushing a gamepad
6519     // button will likely wake the device.
6520     // TODO: Use the input device configuration to control this behavior more finely.
6521     uint32_t policyFlags = 0;
6522
6523     NotifyMotionArgs args(when, getDeviceId(), AINPUT_SOURCE_JOYSTICK, policyFlags,
6524             AMOTION_EVENT_ACTION_MOVE, 0, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
6525             ADISPLAY_ID_NONE, 1, &pointerProperties, &pointerCoords, 0, 0, 0);
6526     getListener()->notifyMotion(&args);
6527 }
6528
6529 void JoystickInputMapper::setPointerCoordsAxisValue(PointerCoords* pointerCoords,
6530         int32_t axis, float value) {
6531     pointerCoords->setAxisValue(axis, value);
6532     /* In order to ease the transition for developers from using the old axes
6533      * to the newer, more semantically correct axes, we'll continue to produce
6534      * values for the old axes as mirrors of the value of their corresponding
6535      * new axes. */
6536     int32_t compatAxis = getCompatAxis(axis);
6537     if (compatAxis >= 0) {
6538         pointerCoords->setAxisValue(compatAxis, value);
6539     }
6540 }
6541
6542 bool JoystickInputMapper::filterAxes(bool force) {
6543     bool atLeastOneSignificantChange = force;
6544     size_t numAxes = mAxes.size();
6545     for (size_t i = 0; i < numAxes; i++) {
6546         Axis& axis = mAxes.editValueAt(i);
6547         if (force || hasValueChangedSignificantly(axis.filter,
6548                 axis.newValue, axis.currentValue, axis.min, axis.max)) {
6549             axis.currentValue = axis.newValue;
6550             atLeastOneSignificantChange = true;
6551         }
6552         if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
6553             if (force || hasValueChangedSignificantly(axis.filter,
6554                     axis.highNewValue, axis.highCurrentValue, axis.min, axis.max)) {
6555                 axis.highCurrentValue = axis.highNewValue;
6556                 atLeastOneSignificantChange = true;
6557             }
6558         }
6559     }
6560     return atLeastOneSignificantChange;
6561 }
6562
6563 bool JoystickInputMapper::hasValueChangedSignificantly(
6564         float filter, float newValue, float currentValue, float min, float max) {
6565     if (newValue != currentValue) {
6566         // Filter out small changes in value unless the value is converging on the axis
6567         // bounds or center point.  This is intended to reduce the amount of information
6568         // sent to applications by particularly noisy joysticks (such as PS3).
6569         if (fabs(newValue - currentValue) > filter
6570                 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, min)
6571                 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, max)
6572                 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, 0)) {
6573             return true;
6574         }
6575     }
6576     return false;
6577 }
6578
6579 bool JoystickInputMapper::hasMovedNearerToValueWithinFilteredRange(
6580         float filter, float newValue, float currentValue, float thresholdValue) {
6581     float newDistance = fabs(newValue - thresholdValue);
6582     if (newDistance < filter) {
6583         float oldDistance = fabs(currentValue - thresholdValue);
6584         if (newDistance < oldDistance) {
6585             return true;
6586         }
6587     }
6588     return false;
6589 }
6590
6591 } // namespace android