/services/input/InputReader.cpp

https://github.com/aizuzi/platform_frameworks_base · C++ · 6530 lines · 5241 code · 841 blank · 448 comment · 1190 complexity · 19fa9db18105ec4a4b7b381c61b853b7 MD5 · raw file

Large files are truncated click here to view the full file

  1. /*
  2. * Copyright (C) 2010 The Android Open Source Project
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #define LOG_TAG "InputReader"
  17. //#define LOG_NDEBUG 0
  18. // Log debug messages for each raw event received from the EventHub.
  19. #define DEBUG_RAW_EVENTS 0
  20. // Log debug messages about touch screen filtering hacks.
  21. #define DEBUG_HACKS 0
  22. // Log debug messages about virtual key processing.
  23. #define DEBUG_VIRTUAL_KEYS 0
  24. // Log debug messages about pointers.
  25. #define DEBUG_POINTERS 0
  26. // Log debug messages about pointer assignment calculations.
  27. #define DEBUG_POINTER_ASSIGNMENT 0
  28. // Log debug messages about gesture detection.
  29. #define DEBUG_GESTURES 0
  30. // Log debug messages about the vibrator.
  31. #define DEBUG_VIBRATOR 0
  32. #include "InputReader.h"
  33. #include <cutils/log.h>
  34. #include <input/Keyboard.h>
  35. #include <input/VirtualKeyMap.h>
  36. #include <stddef.h>
  37. #include <stdlib.h>
  38. #include <unistd.h>
  39. #include <errno.h>
  40. #include <limits.h>
  41. #include <math.h>
  42. #define INDENT " "
  43. #define INDENT2 " "
  44. #define INDENT3 " "
  45. #define INDENT4 " "
  46. #define INDENT5 " "
  47. namespace android {
  48. // --- Constants ---
  49. // Maximum number of slots supported when using the slot-based Multitouch Protocol B.
  50. static const size_t MAX_SLOTS = 32;
  51. // --- Static Functions ---
  52. template<typename T>
  53. inline static T abs(const T& value) {
  54. return value < 0 ? - value : value;
  55. }
  56. template<typename T>
  57. inline static T min(const T& a, const T& b) {
  58. return a < b ? a : b;
  59. }
  60. template<typename T>
  61. inline static void swap(T& a, T& b) {
  62. T temp = a;
  63. a = b;
  64. b = temp;
  65. }
  66. inline static float avg(float x, float y) {
  67. return (x + y) / 2;
  68. }
  69. inline static float distance(float x1, float y1, float x2, float y2) {
  70. return hypotf(x1 - x2, y1 - y2);
  71. }
  72. inline static int32_t signExtendNybble(int32_t value) {
  73. return value >= 8 ? value - 16 : value;
  74. }
  75. static inline const char* toString(bool value) {
  76. return value ? "true" : "false";
  77. }
  78. static int32_t rotateValueUsingRotationMap(int32_t value, int32_t orientation,
  79. const int32_t map[][4], size_t mapSize) {
  80. if (orientation != DISPLAY_ORIENTATION_0) {
  81. for (size_t i = 0; i < mapSize; i++) {
  82. if (value == map[i][0]) {
  83. return map[i][orientation];
  84. }
  85. }
  86. }
  87. return value;
  88. }
  89. static const int32_t keyCodeRotationMap[][4] = {
  90. // key codes enumerated counter-clockwise with the original (unrotated) key first
  91. // no rotation, 90 degree rotation, 180 degree rotation, 270 degree rotation
  92. { AKEYCODE_DPAD_DOWN, AKEYCODE_DPAD_RIGHT, AKEYCODE_DPAD_UP, AKEYCODE_DPAD_LEFT },
  93. { AKEYCODE_DPAD_RIGHT, AKEYCODE_DPAD_UP, AKEYCODE_DPAD_LEFT, AKEYCODE_DPAD_DOWN },
  94. { AKEYCODE_DPAD_UP, AKEYCODE_DPAD_LEFT, AKEYCODE_DPAD_DOWN, AKEYCODE_DPAD_RIGHT },
  95. { AKEYCODE_DPAD_LEFT, AKEYCODE_DPAD_DOWN, AKEYCODE_DPAD_RIGHT, AKEYCODE_DPAD_UP },
  96. };
  97. static const size_t keyCodeRotationMapSize =
  98. sizeof(keyCodeRotationMap) / sizeof(keyCodeRotationMap[0]);
  99. static int32_t rotateKeyCode(int32_t keyCode, int32_t orientation) {
  100. return rotateValueUsingRotationMap(keyCode, orientation,
  101. keyCodeRotationMap, keyCodeRotationMapSize);
  102. }
  103. static void rotateDelta(int32_t orientation, float* deltaX, float* deltaY) {
  104. float temp;
  105. switch (orientation) {
  106. case DISPLAY_ORIENTATION_90:
  107. temp = *deltaX;
  108. *deltaX = *deltaY;
  109. *deltaY = -temp;
  110. break;
  111. case DISPLAY_ORIENTATION_180:
  112. *deltaX = -*deltaX;
  113. *deltaY = -*deltaY;
  114. break;
  115. case DISPLAY_ORIENTATION_270:
  116. temp = *deltaX;
  117. *deltaX = -*deltaY;
  118. *deltaY = temp;
  119. break;
  120. }
  121. }
  122. static inline bool sourcesMatchMask(uint32_t sources, uint32_t sourceMask) {
  123. return (sources & sourceMask & ~ AINPUT_SOURCE_CLASS_MASK) != 0;
  124. }
  125. // Returns true if the pointer should be reported as being down given the specified
  126. // button states. This determines whether the event is reported as a touch event.
  127. static bool isPointerDown(int32_t buttonState) {
  128. return buttonState &
  129. (AMOTION_EVENT_BUTTON_PRIMARY | AMOTION_EVENT_BUTTON_SECONDARY
  130. | AMOTION_EVENT_BUTTON_TERTIARY);
  131. }
  132. static float calculateCommonVector(float a, float b) {
  133. if (a > 0 && b > 0) {
  134. return a < b ? a : b;
  135. } else if (a < 0 && b < 0) {
  136. return a > b ? a : b;
  137. } else {
  138. return 0;
  139. }
  140. }
  141. static void synthesizeButtonKey(InputReaderContext* context, int32_t action,
  142. nsecs_t when, int32_t deviceId, uint32_t source,
  143. uint32_t policyFlags, int32_t lastButtonState, int32_t currentButtonState,
  144. int32_t buttonState, int32_t keyCode) {
  145. if (
  146. (action == AKEY_EVENT_ACTION_DOWN
  147. && !(lastButtonState & buttonState)
  148. && (currentButtonState & buttonState))
  149. || (action == AKEY_EVENT_ACTION_UP
  150. && (lastButtonState & buttonState)
  151. && !(currentButtonState & buttonState))) {
  152. NotifyKeyArgs args(when, deviceId, source, policyFlags,
  153. action, 0, keyCode, 0, context->getGlobalMetaState(), when);
  154. context->getListener()->notifyKey(&args);
  155. }
  156. }
  157. static void synthesizeButtonKeys(InputReaderContext* context, int32_t action,
  158. nsecs_t when, int32_t deviceId, uint32_t source,
  159. uint32_t policyFlags, int32_t lastButtonState, int32_t currentButtonState) {
  160. synthesizeButtonKey(context, action, when, deviceId, source, policyFlags,
  161. lastButtonState, currentButtonState,
  162. AMOTION_EVENT_BUTTON_BACK, AKEYCODE_BACK);
  163. synthesizeButtonKey(context, action, when, deviceId, source, policyFlags,
  164. lastButtonState, currentButtonState,
  165. AMOTION_EVENT_BUTTON_FORWARD, AKEYCODE_FORWARD);
  166. }
  167. // --- InputReaderConfiguration ---
  168. bool InputReaderConfiguration::getDisplayInfo(bool external, DisplayViewport* outViewport) const {
  169. const DisplayViewport& viewport = external ? mExternalDisplay : mInternalDisplay;
  170. if (viewport.displayId >= 0) {
  171. *outViewport = viewport;
  172. return true;
  173. }
  174. return false;
  175. }
  176. void InputReaderConfiguration::setDisplayInfo(bool external, const DisplayViewport& viewport) {
  177. DisplayViewport& v = external ? mExternalDisplay : mInternalDisplay;
  178. v = viewport;
  179. }
  180. // --- InputReader ---
  181. InputReader::InputReader(const sp<EventHubInterface>& eventHub,
  182. const sp<InputReaderPolicyInterface>& policy,
  183. const sp<InputListenerInterface>& listener) :
  184. mContext(this), mEventHub(eventHub), mPolicy(policy),
  185. mGlobalMetaState(0), mGeneration(1),
  186. mDisableVirtualKeysTimeout(LLONG_MIN), mNextTimeout(LLONG_MAX),
  187. mConfigurationChangesToRefresh(0) {
  188. mQueuedListener = new QueuedInputListener(listener);
  189. { // acquire lock
  190. AutoMutex _l(mLock);
  191. refreshConfigurationLocked(0);
  192. updateGlobalMetaStateLocked();
  193. } // release lock
  194. }
  195. InputReader::~InputReader() {
  196. for (size_t i = 0; i < mDevices.size(); i++) {
  197. delete mDevices.valueAt(i);
  198. }
  199. }
  200. void InputReader::loopOnce() {
  201. int32_t oldGeneration;
  202. int32_t timeoutMillis;
  203. bool inputDevicesChanged = false;
  204. Vector<InputDeviceInfo> inputDevices;
  205. { // acquire lock
  206. AutoMutex _l(mLock);
  207. oldGeneration = mGeneration;
  208. timeoutMillis = -1;
  209. uint32_t changes = mConfigurationChangesToRefresh;
  210. if (changes) {
  211. mConfigurationChangesToRefresh = 0;
  212. timeoutMillis = 0;
  213. refreshConfigurationLocked(changes);
  214. } else if (mNextTimeout != LLONG_MAX) {
  215. nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
  216. timeoutMillis = toMillisecondTimeoutDelay(now, mNextTimeout);
  217. }
  218. } // release lock
  219. size_t count = mEventHub->getEvents(timeoutMillis, mEventBuffer, EVENT_BUFFER_SIZE);
  220. { // acquire lock
  221. AutoMutex _l(mLock);
  222. mReaderIsAliveCondition.broadcast();
  223. if (count) {
  224. processEventsLocked(mEventBuffer, count);
  225. }
  226. if (mNextTimeout != LLONG_MAX) {
  227. nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
  228. if (now >= mNextTimeout) {
  229. #if DEBUG_RAW_EVENTS
  230. ALOGD("Timeout expired, latency=%0.3fms", (now - mNextTimeout) * 0.000001f);
  231. #endif
  232. mNextTimeout = LLONG_MAX;
  233. timeoutExpiredLocked(now);
  234. }
  235. }
  236. if (oldGeneration != mGeneration) {
  237. inputDevicesChanged = true;
  238. getInputDevicesLocked(inputDevices);
  239. }
  240. } // release lock
  241. // Send out a message that the describes the changed input devices.
  242. if (inputDevicesChanged) {
  243. mPolicy->notifyInputDevicesChanged(inputDevices);
  244. }
  245. // Flush queued events out to the listener.
  246. // This must happen outside of the lock because the listener could potentially call
  247. // back into the InputReader's methods, such as getScanCodeState, or become blocked
  248. // on another thread similarly waiting to acquire the InputReader lock thereby
  249. // resulting in a deadlock. This situation is actually quite plausible because the
  250. // listener is actually the input dispatcher, which calls into the window manager,
  251. // which occasionally calls into the input reader.
  252. mQueuedListener->flush();
  253. }
  254. void InputReader::processEventsLocked(const RawEvent* rawEvents, size_t count) {
  255. for (const RawEvent* rawEvent = rawEvents; count;) {
  256. int32_t type = rawEvent->type;
  257. size_t batchSize = 1;
  258. if (type < EventHubInterface::FIRST_SYNTHETIC_EVENT) {
  259. int32_t deviceId = rawEvent->deviceId;
  260. while (batchSize < count) {
  261. if (rawEvent[batchSize].type >= EventHubInterface::FIRST_SYNTHETIC_EVENT
  262. || rawEvent[batchSize].deviceId != deviceId) {
  263. break;
  264. }
  265. batchSize += 1;
  266. }
  267. #if DEBUG_RAW_EVENTS
  268. ALOGD("BatchSize: %d Count: %d", batchSize, count);
  269. #endif
  270. processEventsForDeviceLocked(deviceId, rawEvent, batchSize);
  271. } else {
  272. switch (rawEvent->type) {
  273. case EventHubInterface::DEVICE_ADDED:
  274. addDeviceLocked(rawEvent->when, rawEvent->deviceId);
  275. break;
  276. case EventHubInterface::DEVICE_REMOVED:
  277. removeDeviceLocked(rawEvent->when, rawEvent->deviceId);
  278. break;
  279. case EventHubInterface::FINISHED_DEVICE_SCAN:
  280. handleConfigurationChangedLocked(rawEvent->when);
  281. break;
  282. default:
  283. ALOG_ASSERT(false); // can't happen
  284. break;
  285. }
  286. }
  287. count -= batchSize;
  288. rawEvent += batchSize;
  289. }
  290. }
  291. void InputReader::addDeviceLocked(nsecs_t when, int32_t deviceId) {
  292. ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
  293. if (deviceIndex >= 0) {
  294. ALOGW("Ignoring spurious device added event for deviceId %d.", deviceId);
  295. return;
  296. }
  297. InputDeviceIdentifier identifier = mEventHub->getDeviceIdentifier(deviceId);
  298. uint32_t classes = mEventHub->getDeviceClasses(deviceId);
  299. int32_t controllerNumber = mEventHub->getDeviceControllerNumber(deviceId);
  300. InputDevice* device = createDeviceLocked(deviceId, controllerNumber, identifier, classes);
  301. device->configure(when, &mConfig, 0);
  302. device->reset(when);
  303. if (device->isIgnored()) {
  304. ALOGI("Device added: id=%d, name='%s' (ignored non-input device)", deviceId,
  305. identifier.name.string());
  306. } else {
  307. ALOGI("Device added: id=%d, name='%s', sources=0x%08x", deviceId,
  308. identifier.name.string(), device->getSources());
  309. }
  310. mDevices.add(deviceId, device);
  311. bumpGenerationLocked();
  312. }
  313. void InputReader::removeDeviceLocked(nsecs_t when, int32_t deviceId) {
  314. InputDevice* device = NULL;
  315. ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
  316. if (deviceIndex < 0) {
  317. ALOGW("Ignoring spurious device removed event for deviceId %d.", deviceId);
  318. return;
  319. }
  320. device = mDevices.valueAt(deviceIndex);
  321. mDevices.removeItemsAt(deviceIndex, 1);
  322. bumpGenerationLocked();
  323. if (device->isIgnored()) {
  324. ALOGI("Device removed: id=%d, name='%s' (ignored non-input device)",
  325. device->getId(), device->getName().string());
  326. } else {
  327. ALOGI("Device removed: id=%d, name='%s', sources=0x%08x",
  328. device->getId(), device->getName().string(), device->getSources());
  329. }
  330. device->reset(when);
  331. delete device;
  332. }
  333. InputDevice* InputReader::createDeviceLocked(int32_t deviceId, int32_t controllerNumber,
  334. const InputDeviceIdentifier& identifier, uint32_t classes) {
  335. InputDevice* device = new InputDevice(&mContext, deviceId, bumpGenerationLocked(),
  336. controllerNumber, identifier, classes);
  337. // External devices.
  338. if (classes & INPUT_DEVICE_CLASS_EXTERNAL) {
  339. device->setExternal(true);
  340. }
  341. // Switch-like devices.
  342. if (classes & INPUT_DEVICE_CLASS_SWITCH) {
  343. device->addMapper(new SwitchInputMapper(device));
  344. }
  345. // Vibrator-like devices.
  346. if (classes & INPUT_DEVICE_CLASS_VIBRATOR) {
  347. device->addMapper(new VibratorInputMapper(device));
  348. }
  349. // Keyboard-like devices.
  350. uint32_t keyboardSource = 0;
  351. int32_t keyboardType = AINPUT_KEYBOARD_TYPE_NON_ALPHABETIC;
  352. if (classes & INPUT_DEVICE_CLASS_KEYBOARD) {
  353. keyboardSource |= AINPUT_SOURCE_KEYBOARD;
  354. }
  355. if (classes & INPUT_DEVICE_CLASS_ALPHAKEY) {
  356. keyboardType = AINPUT_KEYBOARD_TYPE_ALPHABETIC;
  357. }
  358. if (classes & INPUT_DEVICE_CLASS_DPAD) {
  359. keyboardSource |= AINPUT_SOURCE_DPAD;
  360. }
  361. if (classes & INPUT_DEVICE_CLASS_GAMEPAD) {
  362. keyboardSource |= AINPUT_SOURCE_GAMEPAD;
  363. }
  364. if (keyboardSource != 0) {
  365. device->addMapper(new KeyboardInputMapper(device, keyboardSource, keyboardType));
  366. }
  367. // Cursor-like devices.
  368. if (classes & INPUT_DEVICE_CLASS_CURSOR) {
  369. device->addMapper(new CursorInputMapper(device));
  370. }
  371. // Touchscreens and touchpad devices.
  372. if (classes & INPUT_DEVICE_CLASS_TOUCH_MT) {
  373. device->addMapper(new MultiTouchInputMapper(device));
  374. } else if (classes & INPUT_DEVICE_CLASS_TOUCH) {
  375. device->addMapper(new SingleTouchInputMapper(device));
  376. }
  377. // Joystick-like devices.
  378. if (classes & INPUT_DEVICE_CLASS_JOYSTICK) {
  379. device->addMapper(new JoystickInputMapper(device));
  380. }
  381. return device;
  382. }
  383. void InputReader::processEventsForDeviceLocked(int32_t deviceId,
  384. const RawEvent* rawEvents, size_t count) {
  385. ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
  386. if (deviceIndex < 0) {
  387. ALOGW("Discarding event for unknown deviceId %d.", deviceId);
  388. return;
  389. }
  390. InputDevice* device = mDevices.valueAt(deviceIndex);
  391. if (device->isIgnored()) {
  392. //ALOGD("Discarding event for ignored deviceId %d.", deviceId);
  393. return;
  394. }
  395. device->process(rawEvents, count);
  396. }
  397. void InputReader::timeoutExpiredLocked(nsecs_t when) {
  398. for (size_t i = 0; i < mDevices.size(); i++) {
  399. InputDevice* device = mDevices.valueAt(i);
  400. if (!device->isIgnored()) {
  401. device->timeoutExpired(when);
  402. }
  403. }
  404. }
  405. void InputReader::handleConfigurationChangedLocked(nsecs_t when) {
  406. // Reset global meta state because it depends on the list of all configured devices.
  407. updateGlobalMetaStateLocked();
  408. // Enqueue configuration changed.
  409. NotifyConfigurationChangedArgs args(when);
  410. mQueuedListener->notifyConfigurationChanged(&args);
  411. }
  412. void InputReader::refreshConfigurationLocked(uint32_t changes) {
  413. mPolicy->getReaderConfiguration(&mConfig);
  414. mEventHub->setExcludedDevices(mConfig.excludedDeviceNames);
  415. if (changes) {
  416. ALOGI("Reconfiguring input devices. changes=0x%08x", changes);
  417. nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
  418. if (changes & InputReaderConfiguration::CHANGE_MUST_REOPEN) {
  419. mEventHub->requestReopenDevices();
  420. } else {
  421. for (size_t i = 0; i < mDevices.size(); i++) {
  422. InputDevice* device = mDevices.valueAt(i);
  423. device->configure(now, &mConfig, changes);
  424. }
  425. }
  426. }
  427. }
  428. void InputReader::updateGlobalMetaStateLocked() {
  429. mGlobalMetaState = 0;
  430. for (size_t i = 0; i < mDevices.size(); i++) {
  431. InputDevice* device = mDevices.valueAt(i);
  432. mGlobalMetaState |= device->getMetaState();
  433. }
  434. }
  435. int32_t InputReader::getGlobalMetaStateLocked() {
  436. return mGlobalMetaState;
  437. }
  438. void InputReader::disableVirtualKeysUntilLocked(nsecs_t time) {
  439. mDisableVirtualKeysTimeout = time;
  440. }
  441. bool InputReader::shouldDropVirtualKeyLocked(nsecs_t now,
  442. InputDevice* device, int32_t keyCode, int32_t scanCode) {
  443. if (now < mDisableVirtualKeysTimeout) {
  444. ALOGI("Dropping virtual key from device %s because virtual keys are "
  445. "temporarily disabled for the next %0.3fms. keyCode=%d, scanCode=%d",
  446. device->getName().string(),
  447. (mDisableVirtualKeysTimeout - now) * 0.000001,
  448. keyCode, scanCode);
  449. return true;
  450. } else {
  451. return false;
  452. }
  453. }
  454. void InputReader::fadePointerLocked() {
  455. for (size_t i = 0; i < mDevices.size(); i++) {
  456. InputDevice* device = mDevices.valueAt(i);
  457. device->fadePointer();
  458. }
  459. }
  460. void InputReader::requestTimeoutAtTimeLocked(nsecs_t when) {
  461. if (when < mNextTimeout) {
  462. mNextTimeout = when;
  463. mEventHub->wake();
  464. }
  465. }
  466. int32_t InputReader::bumpGenerationLocked() {
  467. return ++mGeneration;
  468. }
  469. void InputReader::getInputDevices(Vector<InputDeviceInfo>& outInputDevices) {
  470. AutoMutex _l(mLock);
  471. getInputDevicesLocked(outInputDevices);
  472. }
  473. void InputReader::getInputDevicesLocked(Vector<InputDeviceInfo>& outInputDevices) {
  474. outInputDevices.clear();
  475. size_t numDevices = mDevices.size();
  476. for (size_t i = 0; i < numDevices; i++) {
  477. InputDevice* device = mDevices.valueAt(i);
  478. if (!device->isIgnored()) {
  479. outInputDevices.push();
  480. device->getDeviceInfo(&outInputDevices.editTop());
  481. }
  482. }
  483. }
  484. int32_t InputReader::getKeyCodeState(int32_t deviceId, uint32_t sourceMask,
  485. int32_t keyCode) {
  486. AutoMutex _l(mLock);
  487. return getStateLocked(deviceId, sourceMask, keyCode, &InputDevice::getKeyCodeState);
  488. }
  489. int32_t InputReader::getScanCodeState(int32_t deviceId, uint32_t sourceMask,
  490. int32_t scanCode) {
  491. AutoMutex _l(mLock);
  492. return getStateLocked(deviceId, sourceMask, scanCode, &InputDevice::getScanCodeState);
  493. }
  494. int32_t InputReader::getSwitchState(int32_t deviceId, uint32_t sourceMask, int32_t switchCode) {
  495. AutoMutex _l(mLock);
  496. return getStateLocked(deviceId, sourceMask, switchCode, &InputDevice::getSwitchState);
  497. }
  498. int32_t InputReader::getStateLocked(int32_t deviceId, uint32_t sourceMask, int32_t code,
  499. GetStateFunc getStateFunc) {
  500. int32_t result = AKEY_STATE_UNKNOWN;
  501. if (deviceId >= 0) {
  502. ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
  503. if (deviceIndex >= 0) {
  504. InputDevice* device = mDevices.valueAt(deviceIndex);
  505. if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
  506. result = (device->*getStateFunc)(sourceMask, code);
  507. }
  508. }
  509. } else {
  510. size_t numDevices = mDevices.size();
  511. for (size_t i = 0; i < numDevices; i++) {
  512. InputDevice* device = mDevices.valueAt(i);
  513. if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
  514. // If any device reports AKEY_STATE_DOWN or AKEY_STATE_VIRTUAL, return that
  515. // value. Otherwise, return AKEY_STATE_UP as long as one device reports it.
  516. int32_t currentResult = (device->*getStateFunc)(sourceMask, code);
  517. if (currentResult >= AKEY_STATE_DOWN) {
  518. return currentResult;
  519. } else if (currentResult == AKEY_STATE_UP) {
  520. result = currentResult;
  521. }
  522. }
  523. }
  524. }
  525. return result;
  526. }
  527. bool InputReader::hasKeys(int32_t deviceId, uint32_t sourceMask,
  528. size_t numCodes, const int32_t* keyCodes, uint8_t* outFlags) {
  529. AutoMutex _l(mLock);
  530. memset(outFlags, 0, numCodes);
  531. return markSupportedKeyCodesLocked(deviceId, sourceMask, numCodes, keyCodes, outFlags);
  532. }
  533. bool InputReader::markSupportedKeyCodesLocked(int32_t deviceId, uint32_t sourceMask,
  534. size_t numCodes, const int32_t* keyCodes, uint8_t* outFlags) {
  535. bool result = false;
  536. if (deviceId >= 0) {
  537. ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
  538. if (deviceIndex >= 0) {
  539. InputDevice* device = mDevices.valueAt(deviceIndex);
  540. if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
  541. result = device->markSupportedKeyCodes(sourceMask,
  542. numCodes, keyCodes, outFlags);
  543. }
  544. }
  545. } else {
  546. size_t numDevices = mDevices.size();
  547. for (size_t i = 0; i < numDevices; i++) {
  548. InputDevice* device = mDevices.valueAt(i);
  549. if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
  550. result |= device->markSupportedKeyCodes(sourceMask,
  551. numCodes, keyCodes, outFlags);
  552. }
  553. }
  554. }
  555. return result;
  556. }
  557. void InputReader::requestRefreshConfiguration(uint32_t changes) {
  558. AutoMutex _l(mLock);
  559. if (changes) {
  560. bool needWake = !mConfigurationChangesToRefresh;
  561. mConfigurationChangesToRefresh |= changes;
  562. if (needWake) {
  563. mEventHub->wake();
  564. }
  565. }
  566. }
  567. void InputReader::vibrate(int32_t deviceId, const nsecs_t* pattern, size_t patternSize,
  568. ssize_t repeat, int32_t token) {
  569. AutoMutex _l(mLock);
  570. ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
  571. if (deviceIndex >= 0) {
  572. InputDevice* device = mDevices.valueAt(deviceIndex);
  573. device->vibrate(pattern, patternSize, repeat, token);
  574. }
  575. }
  576. void InputReader::cancelVibrate(int32_t deviceId, int32_t token) {
  577. AutoMutex _l(mLock);
  578. ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
  579. if (deviceIndex >= 0) {
  580. InputDevice* device = mDevices.valueAt(deviceIndex);
  581. device->cancelVibrate(token);
  582. }
  583. }
  584. void InputReader::dump(String8& dump) {
  585. AutoMutex _l(mLock);
  586. mEventHub->dump(dump);
  587. dump.append("\n");
  588. dump.append("Input Reader State:\n");
  589. for (size_t i = 0; i < mDevices.size(); i++) {
  590. mDevices.valueAt(i)->dump(dump);
  591. }
  592. dump.append(INDENT "Configuration:\n");
  593. dump.append(INDENT2 "ExcludedDeviceNames: [");
  594. for (size_t i = 0; i < mConfig.excludedDeviceNames.size(); i++) {
  595. if (i != 0) {
  596. dump.append(", ");
  597. }
  598. dump.append(mConfig.excludedDeviceNames.itemAt(i).string());
  599. }
  600. dump.append("]\n");
  601. dump.appendFormat(INDENT2 "VirtualKeyQuietTime: %0.1fms\n",
  602. mConfig.virtualKeyQuietTime * 0.000001f);
  603. dump.appendFormat(INDENT2 "PointerVelocityControlParameters: "
  604. "scale=%0.3f, lowThreshold=%0.3f, highThreshold=%0.3f, acceleration=%0.3f\n",
  605. mConfig.pointerVelocityControlParameters.scale,
  606. mConfig.pointerVelocityControlParameters.lowThreshold,
  607. mConfig.pointerVelocityControlParameters.highThreshold,
  608. mConfig.pointerVelocityControlParameters.acceleration);
  609. dump.appendFormat(INDENT2 "WheelVelocityControlParameters: "
  610. "scale=%0.3f, lowThreshold=%0.3f, highThreshold=%0.3f, acceleration=%0.3f\n",
  611. mConfig.wheelVelocityControlParameters.scale,
  612. mConfig.wheelVelocityControlParameters.lowThreshold,
  613. mConfig.wheelVelocityControlParameters.highThreshold,
  614. mConfig.wheelVelocityControlParameters.acceleration);
  615. dump.appendFormat(INDENT2 "PointerGesture:\n");
  616. dump.appendFormat(INDENT3 "Enabled: %s\n",
  617. toString(mConfig.pointerGesturesEnabled));
  618. dump.appendFormat(INDENT3 "QuietInterval: %0.1fms\n",
  619. mConfig.pointerGestureQuietInterval * 0.000001f);
  620. dump.appendFormat(INDENT3 "DragMinSwitchSpeed: %0.1fpx/s\n",
  621. mConfig.pointerGestureDragMinSwitchSpeed);
  622. dump.appendFormat(INDENT3 "TapInterval: %0.1fms\n",
  623. mConfig.pointerGestureTapInterval * 0.000001f);
  624. dump.appendFormat(INDENT3 "TapDragInterval: %0.1fms\n",
  625. mConfig.pointerGestureTapDragInterval * 0.000001f);
  626. dump.appendFormat(INDENT3 "TapSlop: %0.1fpx\n",
  627. mConfig.pointerGestureTapSlop);
  628. dump.appendFormat(INDENT3 "MultitouchSettleInterval: %0.1fms\n",
  629. mConfig.pointerGestureMultitouchSettleInterval * 0.000001f);
  630. dump.appendFormat(INDENT3 "MultitouchMinDistance: %0.1fpx\n",
  631. mConfig.pointerGestureMultitouchMinDistance);
  632. dump.appendFormat(INDENT3 "SwipeTransitionAngleCosine: %0.1f\n",
  633. mConfig.pointerGestureSwipeTransitionAngleCosine);
  634. dump.appendFormat(INDENT3 "SwipeMaxWidthRatio: %0.1f\n",
  635. mConfig.pointerGestureSwipeMaxWidthRatio);
  636. dump.appendFormat(INDENT3 "MovementSpeedRatio: %0.1f\n",
  637. mConfig.pointerGestureMovementSpeedRatio);
  638. dump.appendFormat(INDENT3 "ZoomSpeedRatio: %0.1f\n",
  639. mConfig.pointerGestureZoomSpeedRatio);
  640. }
  641. void InputReader::monitor() {
  642. // Acquire and release the lock to ensure that the reader has not deadlocked.
  643. mLock.lock();
  644. mEventHub->wake();
  645. mReaderIsAliveCondition.wait(mLock);
  646. mLock.unlock();
  647. // Check the EventHub
  648. mEventHub->monitor();
  649. }
  650. // --- InputReader::ContextImpl ---
  651. InputReader::ContextImpl::ContextImpl(InputReader* reader) :
  652. mReader(reader) {
  653. }
  654. void InputReader::ContextImpl::updateGlobalMetaState() {
  655. // lock is already held by the input loop
  656. mReader->updateGlobalMetaStateLocked();
  657. }
  658. int32_t InputReader::ContextImpl::getGlobalMetaState() {
  659. // lock is already held by the input loop
  660. return mReader->getGlobalMetaStateLocked();
  661. }
  662. void InputReader::ContextImpl::disableVirtualKeysUntil(nsecs_t time) {
  663. // lock is already held by the input loop
  664. mReader->disableVirtualKeysUntilLocked(time);
  665. }
  666. bool InputReader::ContextImpl::shouldDropVirtualKey(nsecs_t now,
  667. InputDevice* device, int32_t keyCode, int32_t scanCode) {
  668. // lock is already held by the input loop
  669. return mReader->shouldDropVirtualKeyLocked(now, device, keyCode, scanCode);
  670. }
  671. void InputReader::ContextImpl::fadePointer() {
  672. // lock is already held by the input loop
  673. mReader->fadePointerLocked();
  674. }
  675. void InputReader::ContextImpl::requestTimeoutAtTime(nsecs_t when) {
  676. // lock is already held by the input loop
  677. mReader->requestTimeoutAtTimeLocked(when);
  678. }
  679. int32_t InputReader::ContextImpl::bumpGeneration() {
  680. // lock is already held by the input loop
  681. return mReader->bumpGenerationLocked();
  682. }
  683. InputReaderPolicyInterface* InputReader::ContextImpl::getPolicy() {
  684. return mReader->mPolicy.get();
  685. }
  686. InputListenerInterface* InputReader::ContextImpl::getListener() {
  687. return mReader->mQueuedListener.get();
  688. }
  689. EventHubInterface* InputReader::ContextImpl::getEventHub() {
  690. return mReader->mEventHub.get();
  691. }
  692. // --- InputReaderThread ---
  693. InputReaderThread::InputReaderThread(const sp<InputReaderInterface>& reader) :
  694. Thread(/*canCallJava*/ true), mReader(reader) {
  695. }
  696. InputReaderThread::~InputReaderThread() {
  697. }
  698. bool InputReaderThread::threadLoop() {
  699. mReader->loopOnce();
  700. return true;
  701. }
  702. // --- InputDevice ---
  703. InputDevice::InputDevice(InputReaderContext* context, int32_t id, int32_t generation,
  704. int32_t controllerNumber, const InputDeviceIdentifier& identifier, uint32_t classes) :
  705. mContext(context), mId(id), mGeneration(generation), mControllerNumber(controllerNumber),
  706. mIdentifier(identifier), mClasses(classes),
  707. mSources(0), mIsExternal(false), mDropUntilNextSync(false) {
  708. }
  709. InputDevice::~InputDevice() {
  710. size_t numMappers = mMappers.size();
  711. for (size_t i = 0; i < numMappers; i++) {
  712. delete mMappers[i];
  713. }
  714. mMappers.clear();
  715. }
  716. void InputDevice::dump(String8& dump) {
  717. InputDeviceInfo deviceInfo;
  718. getDeviceInfo(& deviceInfo);
  719. dump.appendFormat(INDENT "Device %d: %s\n", deviceInfo.getId(),
  720. deviceInfo.getDisplayName().string());
  721. dump.appendFormat(INDENT2 "Generation: %d\n", mGeneration);
  722. dump.appendFormat(INDENT2 "IsExternal: %s\n", toString(mIsExternal));
  723. dump.appendFormat(INDENT2 "Sources: 0x%08x\n", deviceInfo.getSources());
  724. dump.appendFormat(INDENT2 "KeyboardType: %d\n", deviceInfo.getKeyboardType());
  725. const Vector<InputDeviceInfo::MotionRange>& ranges = deviceInfo.getMotionRanges();
  726. if (!ranges.isEmpty()) {
  727. dump.append(INDENT2 "Motion Ranges:\n");
  728. for (size_t i = 0; i < ranges.size(); i++) {
  729. const InputDeviceInfo::MotionRange& range = ranges.itemAt(i);
  730. const char* label = getAxisLabel(range.axis);
  731. char name[32];
  732. if (label) {
  733. strncpy(name, label, sizeof(name));
  734. name[sizeof(name) - 1] = '\0';
  735. } else {
  736. snprintf(name, sizeof(name), "%d", range.axis);
  737. }
  738. dump.appendFormat(INDENT3 "%s: source=0x%08x, "
  739. "min=%0.3f, max=%0.3f, flat=%0.3f, fuzz=%0.3f, resolution=%0.3f\n",
  740. name, range.source, range.min, range.max, range.flat, range.fuzz,
  741. range.resolution);
  742. }
  743. }
  744. size_t numMappers = mMappers.size();
  745. for (size_t i = 0; i < numMappers; i++) {
  746. InputMapper* mapper = mMappers[i];
  747. mapper->dump(dump);
  748. }
  749. }
  750. void InputDevice::addMapper(InputMapper* mapper) {
  751. mMappers.add(mapper);
  752. }
  753. void InputDevice::configure(nsecs_t when, const InputReaderConfiguration* config, uint32_t changes) {
  754. mSources = 0;
  755. if (!isIgnored()) {
  756. if (!changes) { // first time only
  757. mContext->getEventHub()->getConfiguration(mId, &mConfiguration);
  758. }
  759. if (!changes || (changes & InputReaderConfiguration::CHANGE_KEYBOARD_LAYOUTS)) {
  760. if (!(mClasses & INPUT_DEVICE_CLASS_VIRTUAL)) {
  761. sp<KeyCharacterMap> keyboardLayout =
  762. mContext->getPolicy()->getKeyboardLayoutOverlay(mIdentifier.descriptor);
  763. if (mContext->getEventHub()->setKeyboardLayoutOverlay(mId, keyboardLayout)) {
  764. bumpGeneration();
  765. }
  766. }
  767. }
  768. if (!changes || (changes & InputReaderConfiguration::CHANGE_DEVICE_ALIAS)) {
  769. if (!(mClasses & INPUT_DEVICE_CLASS_VIRTUAL)) {
  770. String8 alias = mContext->getPolicy()->getDeviceAlias(mIdentifier);
  771. if (mAlias != alias) {
  772. mAlias = alias;
  773. bumpGeneration();
  774. }
  775. }
  776. }
  777. size_t numMappers = mMappers.size();
  778. for (size_t i = 0; i < numMappers; i++) {
  779. InputMapper* mapper = mMappers[i];
  780. mapper->configure(when, config, changes);
  781. mSources |= mapper->getSources();
  782. }
  783. }
  784. }
  785. void InputDevice::reset(nsecs_t when) {
  786. size_t numMappers = mMappers.size();
  787. for (size_t i = 0; i < numMappers; i++) {
  788. InputMapper* mapper = mMappers[i];
  789. mapper->reset(when);
  790. }
  791. mContext->updateGlobalMetaState();
  792. notifyReset(when);
  793. }
  794. void InputDevice::process(const RawEvent* rawEvents, size_t count) {
  795. // Process all of the events in order for each mapper.
  796. // We cannot simply ask each mapper to process them in bulk because mappers may
  797. // have side-effects that must be interleaved. For example, joystick movement events and
  798. // gamepad button presses are handled by different mappers but they should be dispatched
  799. // in the order received.
  800. size_t numMappers = mMappers.size();
  801. for (const RawEvent* rawEvent = rawEvents; count--; rawEvent++) {
  802. #if DEBUG_RAW_EVENTS
  803. ALOGD("Input event: device=%d type=0x%04x code=0x%04x value=0x%08x when=%lld",
  804. rawEvent->deviceId, rawEvent->type, rawEvent->code, rawEvent->value,
  805. rawEvent->when);
  806. #endif
  807. if (mDropUntilNextSync) {
  808. if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
  809. mDropUntilNextSync = false;
  810. #if DEBUG_RAW_EVENTS
  811. ALOGD("Recovered from input event buffer overrun.");
  812. #endif
  813. } else {
  814. #if DEBUG_RAW_EVENTS
  815. ALOGD("Dropped input event while waiting for next input sync.");
  816. #endif
  817. }
  818. } else if (rawEvent->type == EV_SYN && rawEvent->code == SYN_DROPPED) {
  819. ALOGI("Detected input event buffer overrun for device %s.", getName().string());
  820. mDropUntilNextSync = true;
  821. reset(rawEvent->when);
  822. } else {
  823. for (size_t i = 0; i < numMappers; i++) {
  824. InputMapper* mapper = mMappers[i];
  825. mapper->process(rawEvent);
  826. }
  827. }
  828. }
  829. }
  830. void InputDevice::timeoutExpired(nsecs_t when) {
  831. size_t numMappers = mMappers.size();
  832. for (size_t i = 0; i < numMappers; i++) {
  833. InputMapper* mapper = mMappers[i];
  834. mapper->timeoutExpired(when);
  835. }
  836. }
  837. void InputDevice::getDeviceInfo(InputDeviceInfo* outDeviceInfo) {
  838. outDeviceInfo->initialize(mId, mGeneration, mControllerNumber, mIdentifier, mAlias,
  839. mIsExternal);
  840. size_t numMappers = mMappers.size();
  841. for (size_t i = 0; i < numMappers; i++) {
  842. InputMapper* mapper = mMappers[i];
  843. mapper->populateDeviceInfo(outDeviceInfo);
  844. }
  845. }
  846. int32_t InputDevice::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
  847. return getState(sourceMask, keyCode, & InputMapper::getKeyCodeState);
  848. }
  849. int32_t InputDevice::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
  850. return getState(sourceMask, scanCode, & InputMapper::getScanCodeState);
  851. }
  852. int32_t InputDevice::getSwitchState(uint32_t sourceMask, int32_t switchCode) {
  853. return getState(sourceMask, switchCode, & InputMapper::getSwitchState);
  854. }
  855. int32_t InputDevice::getState(uint32_t sourceMask, int32_t code, GetStateFunc getStateFunc) {
  856. int32_t result = AKEY_STATE_UNKNOWN;
  857. size_t numMappers = mMappers.size();
  858. for (size_t i = 0; i < numMappers; i++) {
  859. InputMapper* mapper = mMappers[i];
  860. if (sourcesMatchMask(mapper->getSources(), sourceMask)) {
  861. // If any mapper reports AKEY_STATE_DOWN or AKEY_STATE_VIRTUAL, return that
  862. // value. Otherwise, return AKEY_STATE_UP as long as one mapper reports it.
  863. int32_t currentResult = (mapper->*getStateFunc)(sourceMask, code);
  864. if (currentResult >= AKEY_STATE_DOWN) {
  865. return currentResult;
  866. } else if (currentResult == AKEY_STATE_UP) {
  867. result = currentResult;
  868. }
  869. }
  870. }
  871. return result;
  872. }
  873. bool InputDevice::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
  874. const int32_t* keyCodes, uint8_t* outFlags) {
  875. bool result = false;
  876. size_t numMappers = mMappers.size();
  877. for (size_t i = 0; i < numMappers; i++) {
  878. InputMapper* mapper = mMappers[i];
  879. if (sourcesMatchMask(mapper->getSources(), sourceMask)) {
  880. result |= mapper->markSupportedKeyCodes(sourceMask, numCodes, keyCodes, outFlags);
  881. }
  882. }
  883. return result;
  884. }
  885. void InputDevice::vibrate(const nsecs_t* pattern, size_t patternSize, ssize_t repeat,
  886. int32_t token) {
  887. size_t numMappers = mMappers.size();
  888. for (size_t i = 0; i < numMappers; i++) {
  889. InputMapper* mapper = mMappers[i];
  890. mapper->vibrate(pattern, patternSize, repeat, token);
  891. }
  892. }
  893. void InputDevice::cancelVibrate(int32_t token) {
  894. size_t numMappers = mMappers.size();
  895. for (size_t i = 0; i < numMappers; i++) {
  896. InputMapper* mapper = mMappers[i];
  897. mapper->cancelVibrate(token);
  898. }
  899. }
  900. int32_t InputDevice::getMetaState() {
  901. int32_t result = 0;
  902. size_t numMappers = mMappers.size();
  903. for (size_t i = 0; i < numMappers; i++) {
  904. InputMapper* mapper = mMappers[i];
  905. result |= mapper->getMetaState();
  906. }
  907. return result;
  908. }
  909. void InputDevice::fadePointer() {
  910. size_t numMappers = mMappers.size();
  911. for (size_t i = 0; i < numMappers; i++) {
  912. InputMapper* mapper = mMappers[i];
  913. mapper->fadePointer();
  914. }
  915. }
  916. void InputDevice::bumpGeneration() {
  917. mGeneration = mContext->bumpGeneration();
  918. }
  919. void InputDevice::notifyReset(nsecs_t when) {
  920. NotifyDeviceResetArgs args(when, mId);
  921. mContext->getListener()->notifyDeviceReset(&args);
  922. }
  923. // --- CursorButtonAccumulator ---
  924. CursorButtonAccumulator::CursorButtonAccumulator() {
  925. clearButtons();
  926. }
  927. void CursorButtonAccumulator::reset(InputDevice* device) {
  928. mBtnLeft = device->isKeyPressed(BTN_LEFT);
  929. mBtnRight = device->isKeyPressed(BTN_RIGHT);
  930. mBtnMiddle = device->isKeyPressed(BTN_MIDDLE);
  931. mBtnBack = device->isKeyPressed(BTN_BACK);
  932. mBtnSide = device->isKeyPressed(BTN_SIDE);
  933. mBtnForward = device->isKeyPressed(BTN_FORWARD);
  934. mBtnExtra = device->isKeyPressed(BTN_EXTRA);
  935. mBtnTask = device->isKeyPressed(BTN_TASK);
  936. }
  937. void CursorButtonAccumulator::clearButtons() {
  938. mBtnLeft = 0;
  939. mBtnRight = 0;
  940. mBtnMiddle = 0;
  941. mBtnBack = 0;
  942. mBtnSide = 0;
  943. mBtnForward = 0;
  944. mBtnExtra = 0;
  945. mBtnTask = 0;
  946. }
  947. void CursorButtonAccumulator::process(const RawEvent* rawEvent) {
  948. if (rawEvent->type == EV_KEY) {
  949. switch (rawEvent->code) {
  950. case BTN_LEFT:
  951. mBtnLeft = rawEvent->value;
  952. break;
  953. case BTN_RIGHT:
  954. mBtnRight = rawEvent->value;
  955. break;
  956. case BTN_MIDDLE:
  957. mBtnMiddle = rawEvent->value;
  958. break;
  959. case BTN_BACK:
  960. mBtnBack = rawEvent->value;
  961. break;
  962. case BTN_SIDE:
  963. mBtnSide = rawEvent->value;
  964. break;
  965. case BTN_FORWARD:
  966. mBtnForward = rawEvent->value;
  967. break;
  968. case BTN_EXTRA:
  969. mBtnExtra = rawEvent->value;
  970. break;
  971. case BTN_TASK:
  972. mBtnTask = rawEvent->value;
  973. break;
  974. }
  975. }
  976. }
  977. uint32_t CursorButtonAccumulator::getButtonState() const {
  978. uint32_t result = 0;
  979. if (mBtnLeft) {
  980. result |= AMOTION_EVENT_BUTTON_PRIMARY;
  981. }
  982. if (mBtnRight) {
  983. result |= AMOTION_EVENT_BUTTON_SECONDARY;
  984. }
  985. if (mBtnMiddle) {
  986. result |= AMOTION_EVENT_BUTTON_TERTIARY;
  987. }
  988. if (mBtnBack || mBtnSide) {
  989. result |= AMOTION_EVENT_BUTTON_BACK;
  990. }
  991. if (mBtnForward || mBtnExtra) {
  992. result |= AMOTION_EVENT_BUTTON_FORWARD;
  993. }
  994. return result;
  995. }
  996. // --- CursorMotionAccumulator ---
  997. CursorMotionAccumulator::CursorMotionAccumulator() {
  998. clearRelativeAxes();
  999. }
  1000. void CursorMotionAccumulator::reset(InputDevice* device) {
  1001. clearRelativeAxes();
  1002. }
  1003. void CursorMotionAccumulator::clearRelativeAxes() {
  1004. mRelX = 0;
  1005. mRelY = 0;
  1006. }
  1007. void CursorMotionAccumulator::process(const RawEvent* rawEvent) {
  1008. if (rawEvent->type == EV_REL) {
  1009. switch (rawEvent->code) {
  1010. case REL_X:
  1011. mRelX = rawEvent->value;
  1012. break;
  1013. case REL_Y:
  1014. mRelY = rawEvent->value;
  1015. break;
  1016. }
  1017. }
  1018. }
  1019. void CursorMotionAccumulator::finishSync() {
  1020. clearRelativeAxes();
  1021. }
  1022. // --- CursorScrollAccumulator ---
  1023. CursorScrollAccumulator::CursorScrollAccumulator() :
  1024. mHaveRelWheel(false), mHaveRelHWheel(false) {
  1025. clearRelativeAxes();
  1026. }
  1027. void CursorScrollAccumulator::configure(InputDevice* device) {
  1028. mHaveRelWheel = device->getEventHub()->hasRelativeAxis(device->getId(), REL_WHEEL);
  1029. mHaveRelHWheel = device->getEventHub()->hasRelativeAxis(device->getId(), REL_HWHEEL);
  1030. }
  1031. void CursorScrollAccumulator::reset(InputDevice* device) {
  1032. clearRelativeAxes();
  1033. }
  1034. void CursorScrollAccumulator::clearRelativeAxes() {
  1035. mRelWheel = 0;
  1036. mRelHWheel = 0;
  1037. }
  1038. void CursorScrollAccumulator::process(const RawEvent* rawEvent) {
  1039. if (rawEvent->type == EV_REL) {
  1040. switch (rawEvent->code) {
  1041. case REL_WHEEL:
  1042. mRelWheel = rawEvent->value;
  1043. break;
  1044. case REL_HWHEEL:
  1045. mRelHWheel = rawEvent->value;
  1046. break;
  1047. }
  1048. }
  1049. }
  1050. void CursorScrollAccumulator::finishSync() {
  1051. clearRelativeAxes();
  1052. }
  1053. // --- TouchButtonAccumulator ---
  1054. TouchButtonAccumulator::TouchButtonAccumulator() :
  1055. mHaveBtnTouch(false), mHaveStylus(false) {
  1056. clearButtons();
  1057. }
  1058. void TouchButtonAccumulator::configure(InputDevice* device) {
  1059. mHaveBtnTouch = device->hasKey(BTN_TOUCH);
  1060. mHaveStylus = device->hasKey(BTN_TOOL_PEN)
  1061. || device->hasKey(BTN_TOOL_RUBBER)
  1062. || device->hasKey(BTN_TOOL_BRUSH)
  1063. || device->hasKey(BTN_TOOL_PENCIL)
  1064. || device->hasKey(BTN_TOOL_AIRBRUSH);
  1065. }
  1066. void TouchButtonAccumulator::reset(InputDevice* device) {
  1067. mBtnTouch = device->isKeyPressed(BTN_TOUCH);
  1068. mBtnStylus = device->isKeyPressed(BTN_STYLUS);
  1069. mBtnStylus2 = device->isKeyPressed(BTN_STYLUS);
  1070. mBtnToolFinger = device->isKeyPressed(BTN_TOOL_FINGER);
  1071. mBtnToolPen = device->isKeyPressed(BTN_TOOL_PEN);
  1072. mBtnToolRubber = device->isKeyPressed(BTN_TOOL_RUBBER);
  1073. mBtnToolBrush = device->isKeyPressed(BTN_TOOL_BRUSH);
  1074. mBtnToolPencil = device->isKeyPressed(BTN_TOOL_PENCIL);
  1075. mBtnToolAirbrush = device->isKeyPressed(BTN_TOOL_AIRBRUSH);
  1076. mBtnToolMouse = device->isKeyPressed(BTN_TOOL_MOUSE);
  1077. mBtnToolLens = device->isKeyPressed(BTN_TOOL_LENS);
  1078. mBtnToolDoubleTap = device->isKeyPressed(BTN_TOOL_DOUBLETAP);
  1079. mBtnToolTripleTap = device->isKeyPressed(BTN_TOOL_TRIPLETAP);
  1080. mBtnToolQuadTap = device->isKeyPressed(BTN_TOOL_QUADTAP);
  1081. }
  1082. void TouchButtonAccumulator::clearButtons() {
  1083. mBtnTouch = 0;
  1084. mBtnStylus = 0;
  1085. mBtnStylus2 = 0;
  1086. mBtnToolFinger = 0;
  1087. mBtnToolPen = 0;
  1088. mBtnToolRubber = 0;
  1089. mBtnToolBrush = 0;
  1090. mBtnToolPencil = 0;
  1091. mBtnToolAirbrush = 0;
  1092. mBtnToolMouse = 0;
  1093. mBtnToolLens = 0;
  1094. mBtnToolDoubleTap = 0;
  1095. mBtnToolTripleTap = 0;
  1096. mBtnToolQuadTap = 0;
  1097. }
  1098. void TouchButtonAccumulator::process(const RawEvent* rawEvent) {
  1099. if (rawEvent->type == EV_KEY) {
  1100. switch (rawEvent->code) {
  1101. case BTN_TOUCH:
  1102. mBtnTouch = rawEvent->value;
  1103. break;
  1104. case BTN_STYLUS:
  1105. mBtnStylus = rawEvent->value;
  1106. break;
  1107. case BTN_STYLUS2:
  1108. mBtnStylus2 = rawEvent->value;
  1109. break;
  1110. case BTN_TOOL_FINGER:
  1111. mBtnToolFinger = rawEvent->value;
  1112. break;
  1113. case BTN_TOOL_PEN:
  1114. mBtnToolPen = rawEvent->value;
  1115. break;
  1116. case BTN_TOOL_RUBBER:
  1117. mBtnToolRubber = rawEvent->value;
  1118. break;
  1119. case BTN_TOOL_BRUSH:
  1120. mBtnToolBrush = rawEvent->value;
  1121. break;
  1122. case BTN_TOOL_PENCIL:
  1123. mBtnToolPencil = rawEvent->value;
  1124. break;
  1125. case BTN_TOOL_AIRBRUSH:
  1126. mBtnToolAirbrush = rawEvent->value;
  1127. break;
  1128. case BTN_TOOL_MOUSE:
  1129. mBtnToolMouse = rawEvent->value;
  1130. break;
  1131. case BTN_TOOL_LENS:
  1132. mBtnToolLens = rawEvent->value;
  1133. break;
  1134. case BTN_TOOL_DOUBLETAP:
  1135. mBtnToolDoubleTap = rawEvent->value;
  1136. break;
  1137. case BTN_TOOL_TRIPLETAP:
  1138. mBtnToolTripleTap = rawEvent->value;
  1139. break;
  1140. case BTN_TOOL_QUADTAP:
  1141. mBtnToolQuadTap = rawEvent->value;
  1142. break;
  1143. }
  1144. }
  1145. }
  1146. uint32_t TouchButtonAccumulator::getButtonState() const {
  1147. uint32_t result = 0;
  1148. if (mBtnStylus) {
  1149. result |= AMOTION_EVENT_BUTTON_SECONDARY;
  1150. }
  1151. if (mBtnStylus2) {
  1152. result |= AMOTION_EVENT_BUTTON_TERTIARY;
  1153. }
  1154. return result;
  1155. }
  1156. int32_t TouchButtonAccumulator::getToolType() const {
  1157. if (mBtnToolMouse || mBtnToolLens) {
  1158. return AMOTION_EVENT_TOOL_TYPE_MOUSE;
  1159. }
  1160. if (mBtnToolRubber) {
  1161. return AMOTION_EVENT_TOOL_TYPE_ERASER;
  1162. }
  1163. if (mBtnToolPen || mBtnToolBrush || mBtnToolPencil || mBtnToolAirbrush) {
  1164. return AMOTION_EVENT_TOOL_TYPE_STYLUS;
  1165. }
  1166. if (mBtnToolFinger || mBtnToolDoubleTap || mBtnToolTripleTap || mBtnToolQuadTap) {
  1167. return AMOTION_EVENT_TOOL_TYPE_FINGER;
  1168. }
  1169. return AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
  1170. }
  1171. bool TouchButtonAccumulator::isToolActive() const {
  1172. return mBtnTouch || mBtnToolFinger || mBtnToolPen || mBtnToolRubber
  1173. || mBtnToolBrush || mBtnToolPencil || mBtnToolAirbrush
  1174. || mBtnToolMouse || mBtnToolLens
  1175. || mBtnToolDoubleTap || mBtnToolTripleTap || mBtnToolQuadTap;
  1176. }
  1177. bool TouchButtonAccumulator::isHovering() const {
  1178. return mHaveBtnTouch && !mBtnTouch;
  1179. }
  1180. bool TouchButtonAccumulator::hasStylus() const {
  1181. return mHaveStylus;
  1182. }
  1183. // --- RawPointerAxes ---
  1184. RawPointerAxes::RawPointerAxes() {
  1185. clear();
  1186. }
  1187. void RawPointerAxes::clear() {
  1188. x.clear();
  1189. y.clear();
  1190. pressure.clear();
  1191. touchMajor.clear();
  1192. touchMinor.clear();
  1193. toolMajor.clear();
  1194. toolMinor.clear();
  1195. orientation.clear();
  1196. distance.clear();
  1197. tiltX.clear();
  1198. tiltY.clear();
  1199. trackingId.clear();
  1200. slot.clear();
  1201. }
  1202. // --- RawPointerData ---
  1203. RawPointerData::RawPointerData() {
  1204. clear();
  1205. }
  1206. void RawPointerData::clear() {
  1207. pointerCount = 0;
  1208. clearIdBits();
  1209. }
  1210. void RawPointerData::copyFrom(const RawPointerData& other) {
  1211. pointerCount = other.pointerCount;
  1212. hoveringIdBits = other.hoveringIdBits;
  1213. touchingIdBits = other.touchingIdBits;
  1214. for (uint32_t i = 0; i < pointerCount; i++) {
  1215. pointers[i] = other.pointers[i];
  1216. int id = pointers[i].id;
  1217. idToIndex[id] = other.idToIndex[id];
  1218. }
  1219. }
  1220. void RawPointerData::getCentroidOfTouchingPointers(float* outX, float* outY) const {
  1221. float x = 0, y = 0;
  1222. uint32_t count = touchingIdBits.count();
  1223. if (count) {
  1224. for (BitSet32 idBits(touchingIdBits); !idBits.isEmpty(); ) {
  1225. uint32_t id = idBits.clearFirstMarkedBit();
  1226. const Pointer& pointer = pointerForId(id);
  1227. x += pointer.x;
  1228. y += pointer.y;
  1229. }
  1230. x /= count;
  1231. y /= count;
  1232. }
  1233. *outX = x;
  1234. *outY = y;
  1235. }
  1236. // --- CookedPointerData ---
  1237. CookedPointerData::CookedPointerData() {
  1238. clear();
  1239. }
  1240. void CookedPointerData::clear() {
  1241. pointerCount = 0;
  1242. hoveringIdBits.clear();
  1243. touchingIdBits.clear();
  1244. }
  1245. void CookedPointerData::copyFrom(const CookedPointerData& other) {
  1246. pointerCount = other.pointerCount;
  1247. hoveringIdBits = other.hoveringIdBits;
  1248. touchingIdBits = other.touchingIdBits;
  1249. for (uint32_t i = 0; i < pointerCount; i++) {
  1250. pointerProperties[i].copyFrom(other.pointerProperties[i]);
  1251. pointerCoords[i].copyFrom(other.pointerCoords[i]);
  1252. int id = pointerProperties[i].id;
  1253. idToIndex[id] = other.idToIndex[id];
  1254. }
  1255. }
  1256. // --- SingleTouchMotionAccumulator ---
  1257. SingleTouchMotionAccumulator::SingleTouchMotionAccumulator() {
  1258. clearAbsoluteAxes();
  1259. }
  1260. void SingleTouchMotionAccumulator::reset(InputDevice* device) {
  1261. mAbsX = device->getAbsoluteAxisValue(ABS_X);
  1262. mAbsY = device->getAbsoluteAxisValue(ABS_Y);
  1263. mAbsPressure = device->getAbsoluteAxisValue(ABS_PRESSURE);
  1264. mAbsToolWidth = device->getAbsoluteAxisValue(ABS_TOOL_WIDTH);
  1265. mAbsDistance = device->getAbsoluteAxisValue(ABS_DISTANCE);
  1266. mAbsTiltX = device->getAbsoluteAxisValue(ABS_TILT_X);
  1267. mAbsTiltY = device->getAbsoluteAxisValue(ABS_TILT_Y);
  1268. }
  1269. void SingleTouchMotionAccumulator::clearAbsoluteAxes() {
  1270. mAbsX = 0;
  1271. mAbsY = 0;
  1272. mAbsPressure = 0;
  1273. mAbsToolWidth = 0;
  1274. mAbsDistance = 0;
  1275. mAbsTiltX = 0;
  1276. mAbsTiltY = 0;
  1277. }
  1278. void SingleTouchMotionAccumulator::process(const RawEvent* rawEvent) {
  1279. if (rawEvent->type == EV_ABS) {
  1280. switch (rawEvent->code) {
  1281. case ABS_X:
  1282. mAbsX = rawEvent->value;
  1283. break;
  1284. case ABS_Y:
  1285. mAbsY = rawEvent->value;
  1286. break;
  1287. case ABS_PRESSURE:
  1288. mAbsPressure = rawEvent->value;
  1289. break;
  1290. case ABS_TOOL_WIDTH:
  1291. mAbsToolWidth = rawEvent->value;
  1292. break;
  1293. case ABS_DISTANCE:
  1294. mAbsDistance = rawEvent->value;
  1295. break;
  1296. case ABS_TILT_X:
  1297. mAbsTiltX = rawEvent->value;
  1298. break;
  1299. case ABS_TILT_Y:
  1300. mAbsTiltY = rawEvent->value;
  1301. break;
  1302. }
  1303. }
  1304. }
  1305. // --- MultiTouchMotionAccumulator ---
  1306. MultiTouchMotionAccumulator::MultiTouchMotionAccumulator() :
  1307. mCurrentSlot(-1), mSlots(NULL), mSlotCount(0), mUsingSlotsProtocol(false),
  1308. mHaveStylus(false) {
  1309. }
  1310. MultiTouchMotionAccumulator::~MultiTouchMotionAccumulator() {
  1311. delete[] mSlots;
  1312. }
  1313. void MultiTouchMotionAccumulator::configure(InputDevice* device,
  1314. size_t slotCount, bool usingSlotsProtocol) {
  1315. mSlotCount = slotCount;
  1316. mUsingSlotsProtocol = usingSlotsProtocol;
  1317. mHaveStylus = device->hasAbsoluteAxis(ABS_MT_TOOL_TYPE);
  1318. delete[] mSlots;
  1319. mSlots = ne