2 // Copyright 2010 The Android Open Source Project
4 // Provides a shared memory transport for input events.
6 #define LOG_TAG "InputTransport"
10 // Log debug messages about channel messages (send message, receive message)
11 #define DEBUG_CHANNEL_MESSAGES 0
13 // Log debug messages whenever InputChannel objects are created/destroyed
14 #define DEBUG_CHANNEL_LIFECYCLE 0
16 // Log debug messages about transport actions
17 #define DEBUG_TRANSPORT_ACTIONS 0
19 // Log debug messages about touch event resampling
20 #define DEBUG_RESAMPLING 0
26 #include <sys/types.h>
27 #include <sys/socket.h>
30 #include <cutils/log.h>
31 #include <cutils/properties.h>
32 #include <input/InputTransport.h>
37 // Socket buffer size. The default is typically about 128KB, which is much larger than
38 // we really need. So we make it smaller. It just needs to be big enough to hold
39 // a few dozen large multi-finger motion events in the case where an application gets
40 // behind processing touches.
41 static const size_t SOCKET_BUFFER_SIZE = 32 * 1024;
43 // Nanoseconds per milliseconds.
44 static const nsecs_t NANOS_PER_MS = 1000000;
46 // Latency added during resampling. A few milliseconds doesn't hurt much but
47 // reduces the impact of mispredicted touch positions.
48 static const nsecs_t RESAMPLE_LATENCY = 5 * NANOS_PER_MS;
50 // Minimum time difference between consecutive samples before attempting to resample.
51 static const nsecs_t RESAMPLE_MIN_DELTA = 2 * NANOS_PER_MS;
53 // Maximum time to predict forward from the last known state, to avoid predicting too
54 // far into the future. This time is further bounded by 50% of the last time delta.
55 static const nsecs_t RESAMPLE_MAX_PREDICTION = 8 * NANOS_PER_MS;
58 inline static T min(const T& a, const T& b) {
62 inline static float lerp(float a, float b, float alpha) {
63 return a + alpha * (b - a);
66 // --- InputMessage ---
68 bool InputMessage::isValid(size_t actualSize) const {
69 if (size() == actualSize) {
70 switch (header.type) {
74 return body.motion.pointerCount > 0
75 && body.motion.pointerCount <= MAX_POINTERS;
83 size_t InputMessage::size() const {
84 switch (header.type) {
86 return sizeof(Header) + body.key.size();
88 return sizeof(Header) + body.motion.size();
90 return sizeof(Header) + body.finished.size();
92 return sizeof(Header);
96 // --- InputChannel ---
98 InputChannel::InputChannel(const String8& name, int fd) :
99 mName(name), mFd(fd) {
100 #if DEBUG_CHANNEL_LIFECYCLE
101 ALOGD("Input channel constructed: name='%s', fd=%d",
105 int result = fcntl(mFd, F_SETFL, O_NONBLOCK);
106 LOG_ALWAYS_FATAL_IF(result != 0, "channel '%s' ~ Could not make socket "
107 "non-blocking. errno=%d", mName.string(), errno);
110 InputChannel::~InputChannel() {
111 #if DEBUG_CHANNEL_LIFECYCLE
112 ALOGD("Input channel destroyed: name='%s', fd=%d",
113 mName.string(), mFd);
119 status_t InputChannel::openInputChannelPair(const String8& name,
120 sp<InputChannel>& outServerChannel, sp<InputChannel>& outClientChannel) {
122 if (socketpair(AF_UNIX, SOCK_SEQPACKET, 0, sockets)) {
123 status_t result = -errno;
124 ALOGE("channel '%s' ~ Could not create socket pair. errno=%d",
125 name.string(), errno);
126 outServerChannel.clear();
127 outClientChannel.clear();
131 int bufferSize = SOCKET_BUFFER_SIZE;
132 setsockopt(sockets[0], SOL_SOCKET, SO_SNDBUF, &bufferSize, sizeof(bufferSize));
133 setsockopt(sockets[0], SOL_SOCKET, SO_RCVBUF, &bufferSize, sizeof(bufferSize));
134 setsockopt(sockets[1], SOL_SOCKET, SO_SNDBUF, &bufferSize, sizeof(bufferSize));
135 setsockopt(sockets[1], SOL_SOCKET, SO_RCVBUF, &bufferSize, sizeof(bufferSize));
137 String8 serverChannelName = name;
138 serverChannelName.append(" (server)");
139 outServerChannel = new InputChannel(serverChannelName, sockets[0]);
141 String8 clientChannelName = name;
142 clientChannelName.append(" (client)");
143 outClientChannel = new InputChannel(clientChannelName, sockets[1]);
147 status_t InputChannel::sendMessage(const InputMessage* msg) {
148 size_t msgLength = msg->size();
151 nWrite = ::send(mFd, msg, msgLength, MSG_DONTWAIT | MSG_NOSIGNAL);
152 } while (nWrite == -1 && errno == EINTR);
156 #if DEBUG_CHANNEL_MESSAGES
157 ALOGD("channel '%s' ~ error sending message of type %d, errno=%d", mName.string(),
158 msg->header.type, error);
160 if (error == EAGAIN || error == EWOULDBLOCK) {
163 if (error == EPIPE || error == ENOTCONN || error == ECONNREFUSED || error == ECONNRESET) {
169 if (size_t(nWrite) != msgLength) {
170 #if DEBUG_CHANNEL_MESSAGES
171 ALOGD("channel '%s' ~ error sending message type %d, send was incomplete",
172 mName.string(), msg->header.type);
177 #if DEBUG_CHANNEL_MESSAGES
178 ALOGD("channel '%s' ~ sent message of type %d", mName.string(), msg->header.type);
183 status_t InputChannel::receiveMessage(InputMessage* msg) {
186 nRead = ::recv(mFd, msg, sizeof(InputMessage), MSG_DONTWAIT);
187 } while (nRead == -1 && errno == EINTR);
191 #if DEBUG_CHANNEL_MESSAGES
192 ALOGD("channel '%s' ~ receive message failed, errno=%d", mName.string(), errno);
194 if (error == EAGAIN || error == EWOULDBLOCK) {
197 if (error == EPIPE || error == ENOTCONN || error == ECONNREFUSED) {
203 if (nRead == 0) { // check for EOF
204 #if DEBUG_CHANNEL_MESSAGES
205 ALOGD("channel '%s' ~ receive message failed because peer was closed", mName.string());
210 if (!msg->isValid(nRead)) {
211 #if DEBUG_CHANNEL_MESSAGES
212 ALOGD("channel '%s' ~ received invalid message", mName.string());
217 #if DEBUG_CHANNEL_MESSAGES
218 ALOGD("channel '%s' ~ received message of type %d", mName.string(), msg->header.type);
223 sp<InputChannel> InputChannel::dup() const {
224 int fd = ::dup(getFd());
225 return fd >= 0 ? new InputChannel(getName(), fd) : NULL;
229 // --- InputPublisher ---
231 InputPublisher::InputPublisher(const sp<InputChannel>& channel) :
235 InputPublisher::~InputPublisher() {
238 status_t InputPublisher::publishKeyEvent(
250 #if DEBUG_TRANSPORT_ACTIONS
251 ALOGD("channel '%s' publisher ~ publishKeyEvent: seq=%u, deviceId=%d, source=0x%x, "
252 "action=0x%x, flags=0x%x, keyCode=%d, scanCode=%d, metaState=0x%x, repeatCount=%d,"
253 "downTime=%lld, eventTime=%lld",
254 mChannel->getName().string(), seq,
255 deviceId, source, action, flags, keyCode, scanCode, metaState, repeatCount,
256 downTime, eventTime);
260 ALOGE("Attempted to publish a key event with sequence number 0.");
265 msg.header.type = InputMessage::TYPE_KEY;
266 msg.body.key.seq = seq;
267 msg.body.key.deviceId = deviceId;
268 msg.body.key.source = source;
269 msg.body.key.action = action;
270 msg.body.key.flags = flags;
271 msg.body.key.keyCode = keyCode;
272 msg.body.key.scanCode = scanCode;
273 msg.body.key.metaState = metaState;
274 msg.body.key.repeatCount = repeatCount;
275 msg.body.key.downTime = downTime;
276 msg.body.key.eventTime = eventTime;
277 return mChannel->sendMessage(&msg);
280 status_t InputPublisher::publishMotionEvent(
296 const PointerProperties* pointerProperties,
297 const PointerCoords* pointerCoords) {
298 #if DEBUG_TRANSPORT_ACTIONS
299 ALOGD("channel '%s' publisher ~ publishMotionEvent: seq=%u, deviceId=%d, source=0x%x, "
300 "action=0x%x, flags=0x%x, edgeFlags=0x%x, metaState=0x%x, buttonState=0x%x, "
301 "xOffset=%f, yOffset=%f, "
302 "xPrecision=%f, yPrecision=%f, downTime=%lld, eventTime=%lld, "
304 mChannel->getName().string(), seq,
305 deviceId, source, action, flags, edgeFlags, metaState, buttonState,
306 xOffset, yOffset, xPrecision, yPrecision, downTime, eventTime, pointerCount);
310 ALOGE("Attempted to publish a motion event with sequence number 0.");
314 if (pointerCount > MAX_POINTERS || pointerCount < 1) {
315 ALOGE("channel '%s' publisher ~ Invalid number of pointers provided: %d.",
316 mChannel->getName().string(), pointerCount);
321 msg.header.type = InputMessage::TYPE_MOTION;
322 msg.body.motion.seq = seq;
323 msg.body.motion.deviceId = deviceId;
324 msg.body.motion.source = source;
325 msg.body.motion.action = action;
326 msg.body.motion.flags = flags;
327 msg.body.motion.edgeFlags = edgeFlags;
328 msg.body.motion.metaState = metaState;
329 msg.body.motion.buttonState = buttonState;
330 msg.body.motion.xOffset = xOffset;
331 msg.body.motion.yOffset = yOffset;
332 msg.body.motion.xPrecision = xPrecision;
333 msg.body.motion.yPrecision = yPrecision;
334 msg.body.motion.downTime = downTime;
335 msg.body.motion.eventTime = eventTime;
336 msg.body.motion.pointerCount = pointerCount;
337 for (size_t i = 0; i < pointerCount; i++) {
338 msg.body.motion.pointers[i].properties.copyFrom(pointerProperties[i]);
339 msg.body.motion.pointers[i].coords.copyFrom(pointerCoords[i]);
341 return mChannel->sendMessage(&msg);
344 status_t InputPublisher::receiveFinishedSignal(uint32_t* outSeq, bool* outHandled) {
345 #if DEBUG_TRANSPORT_ACTIONS
346 ALOGD("channel '%s' publisher ~ receiveFinishedSignal",
347 mChannel->getName().string());
351 status_t result = mChannel->receiveMessage(&msg);
357 if (msg.header.type != InputMessage::TYPE_FINISHED) {
358 ALOGE("channel '%s' publisher ~ Received unexpected message of type %d from consumer",
359 mChannel->getName().string(), msg.header.type);
360 return UNKNOWN_ERROR;
362 *outSeq = msg.body.finished.seq;
363 *outHandled = msg.body.finished.handled;
367 // --- InputConsumer ---
369 InputConsumer::InputConsumer(const sp<InputChannel>& channel) :
370 mResampleTouch(isTouchResamplingEnabled()),
371 mChannel(channel), mMsgDeferred(false) {
374 InputConsumer::~InputConsumer() {
377 bool InputConsumer::isTouchResamplingEnabled() {
378 char value[PROPERTY_VALUE_MAX];
379 int length = property_get("debug.inputconsumer.resample", value, NULL);
381 if (!strcmp("0", value)) {
384 if (strcmp("1", value)) {
385 ALOGD("Unrecognized property value for 'debug.inputconsumer.resample'. "
392 status_t InputConsumer::consume(InputEventFactoryInterface* factory,
393 bool consumeBatches, nsecs_t frameTime, uint32_t* outSeq, InputEvent** outEvent) {
394 #if DEBUG_TRANSPORT_ACTIONS
395 ALOGD("channel '%s' consumer ~ consume: consumeBatches=%s, frameTime=%lld",
396 mChannel->getName().string(), consumeBatches ? "true" : "false", frameTime);
402 // Fetch the next input message.
403 // Loop until an event can be returned or no additional events are received.
406 // mMsg contains a valid input message from the previous call to consume
407 // that has not yet been processed.
408 mMsgDeferred = false;
410 // Receive a fresh message.
411 status_t result = mChannel->receiveMessage(&mMsg);
413 // Consume the next batched event unless batches are being held for later.
414 if (consumeBatches || result != WOULD_BLOCK) {
415 result = consumeBatch(factory, frameTime, outSeq, outEvent);
417 #if DEBUG_TRANSPORT_ACTIONS
418 ALOGD("channel '%s' consumer ~ consumed batch event, seq=%u",
419 mChannel->getName().string(), *outSeq);
428 switch (mMsg.header.type) {
429 case InputMessage::TYPE_KEY: {
430 KeyEvent* keyEvent = factory->createKeyEvent();
431 if (!keyEvent) return NO_MEMORY;
433 initializeKeyEvent(keyEvent, &mMsg);
434 *outSeq = mMsg.body.key.seq;
435 *outEvent = keyEvent;
436 #if DEBUG_TRANSPORT_ACTIONS
437 ALOGD("channel '%s' consumer ~ consumed key event, seq=%u",
438 mChannel->getName().string(), *outSeq);
443 case AINPUT_EVENT_TYPE_MOTION: {
444 ssize_t batchIndex = findBatch(mMsg.body.motion.deviceId, mMsg.body.motion.source);
445 if (batchIndex >= 0) {
446 Batch& batch = mBatches.editItemAt(batchIndex);
447 if (canAddSample(batch, &mMsg)) {
448 batch.samples.push(mMsg);
449 #if DEBUG_TRANSPORT_ACTIONS
450 ALOGD("channel '%s' consumer ~ appended to batch event",
451 mChannel->getName().string());
455 // We cannot append to the batch in progress, so we need to consume
456 // the previous batch right now and defer the new message until later.
458 status_t result = consumeSamples(factory,
459 batch, batch.samples.size(), outSeq, outEvent);
460 mBatches.removeAt(batchIndex);
464 #if DEBUG_TRANSPORT_ACTIONS
465 ALOGD("channel '%s' consumer ~ consumed batch event and "
466 "deferred current event, seq=%u",
467 mChannel->getName().string(), *outSeq);
473 // Start a new batch if needed.
474 if (mMsg.body.motion.action == AMOTION_EVENT_ACTION_MOVE
475 || mMsg.body.motion.action == AMOTION_EVENT_ACTION_HOVER_MOVE) {
477 Batch& batch = mBatches.editTop();
478 batch.samples.push(mMsg);
479 #if DEBUG_TRANSPORT_ACTIONS
480 ALOGD("channel '%s' consumer ~ started batch event",
481 mChannel->getName().string());
486 MotionEvent* motionEvent = factory->createMotionEvent();
487 if (! motionEvent) return NO_MEMORY;
489 updateTouchState(&mMsg);
490 initializeMotionEvent(motionEvent, &mMsg);
491 *outSeq = mMsg.body.motion.seq;
492 *outEvent = motionEvent;
493 #if DEBUG_TRANSPORT_ACTIONS
494 ALOGD("channel '%s' consumer ~ consumed motion event, seq=%u",
495 mChannel->getName().string(), *outSeq);
501 ALOGE("channel '%s' consumer ~ Received unexpected message of type %d",
502 mChannel->getName().string(), mMsg.header.type);
503 return UNKNOWN_ERROR;
509 status_t InputConsumer::consumeBatch(InputEventFactoryInterface* factory,
510 nsecs_t frameTime, uint32_t* outSeq, InputEvent** outEvent) {
512 for (size_t i = mBatches.size(); i-- > 0; ) {
513 Batch& batch = mBatches.editItemAt(i);
515 result = consumeSamples(factory, batch, batch.samples.size(),
517 mBatches.removeAt(i);
521 nsecs_t sampleTime = frameTime - RESAMPLE_LATENCY;
522 ssize_t split = findSampleNoLaterThan(batch, sampleTime);
527 result = consumeSamples(factory, batch, split + 1, outSeq, outEvent);
528 const InputMessage* next;
529 if (batch.samples.isEmpty()) {
530 mBatches.removeAt(i);
533 next = &batch.samples.itemAt(0);
536 resampleTouchState(sampleTime, static_cast<MotionEvent*>(*outEvent), next);
544 status_t InputConsumer::consumeSamples(InputEventFactoryInterface* factory,
545 Batch& batch, size_t count, uint32_t* outSeq, InputEvent** outEvent) {
546 MotionEvent* motionEvent = factory->createMotionEvent();
547 if (! motionEvent) return NO_MEMORY;
550 for (size_t i = 0; i < count; i++) {
551 InputMessage& msg = batch.samples.editItemAt(i);
552 updateTouchState(&msg);
555 seqChain.seq = msg.body.motion.seq;
556 seqChain.chain = chain;
557 mSeqChains.push(seqChain);
558 addSample(motionEvent, &msg);
560 initializeMotionEvent(motionEvent, &msg);
562 chain = msg.body.motion.seq;
564 batch.samples.removeItemsAt(0, count);
567 *outEvent = motionEvent;
571 void InputConsumer::updateTouchState(InputMessage* msg) {
572 if (!mResampleTouch ||
573 !(msg->body.motion.source & AINPUT_SOURCE_CLASS_POINTER)) {
577 int32_t deviceId = msg->body.motion.deviceId;
578 int32_t source = msg->body.motion.source;
579 nsecs_t eventTime = msg->body.motion.eventTime;
581 // Update the touch state history to incorporate the new input message.
582 // If the message is in the past relative to the most recently produced resampled
583 // touch, then use the resampled time and coordinates instead.
584 switch (msg->body.motion.action & AMOTION_EVENT_ACTION_MASK) {
585 case AMOTION_EVENT_ACTION_DOWN: {
586 ssize_t index = findTouchState(deviceId, source);
589 index = mTouchStates.size() - 1;
591 TouchState& touchState = mTouchStates.editItemAt(index);
592 touchState.initialize(deviceId, source);
593 touchState.addHistory(msg);
597 case AMOTION_EVENT_ACTION_MOVE: {
598 ssize_t index = findTouchState(deviceId, source);
600 TouchState& touchState = mTouchStates.editItemAt(index);
601 touchState.addHistory(msg);
602 if (eventTime < touchState.lastResample.eventTime) {
603 rewriteMessage(touchState, msg);
605 touchState.lastResample.idBits.clear();
611 case AMOTION_EVENT_ACTION_POINTER_DOWN: {
612 ssize_t index = findTouchState(deviceId, source);
614 TouchState& touchState = mTouchStates.editItemAt(index);
615 touchState.lastResample.idBits.clearBit(msg->body.motion.getActionId());
616 rewriteMessage(touchState, msg);
621 case AMOTION_EVENT_ACTION_POINTER_UP: {
622 ssize_t index = findTouchState(deviceId, source);
624 TouchState& touchState = mTouchStates.editItemAt(index);
625 rewriteMessage(touchState, msg);
626 touchState.lastResample.idBits.clearBit(msg->body.motion.getActionId());
631 case AMOTION_EVENT_ACTION_SCROLL: {
632 ssize_t index = findTouchState(deviceId, source);
634 const TouchState& touchState = mTouchStates.itemAt(index);
635 rewriteMessage(touchState, msg);
640 case AMOTION_EVENT_ACTION_UP:
641 case AMOTION_EVENT_ACTION_CANCEL: {
642 ssize_t index = findTouchState(deviceId, source);
644 const TouchState& touchState = mTouchStates.itemAt(index);
645 rewriteMessage(touchState, msg);
646 mTouchStates.removeAt(index);
653 void InputConsumer::rewriteMessage(const TouchState& state, InputMessage* msg) {
654 for (size_t i = 0; i < msg->body.motion.pointerCount; i++) {
655 uint32_t id = msg->body.motion.pointers[i].properties.id;
656 if (state.lastResample.idBits.hasBit(id)) {
657 PointerCoords& msgCoords = msg->body.motion.pointers[i].coords;
658 const PointerCoords& resampleCoords = state.lastResample.getPointerById(id);
660 ALOGD("[%d] - rewrite (%0.3f, %0.3f), old (%0.3f, %0.3f)", id,
661 resampleCoords.getAxisValue(AMOTION_EVENT_AXIS_X),
662 resampleCoords.getAxisValue(AMOTION_EVENT_AXIS_Y),
663 msgCoords.getAxisValue(AMOTION_EVENT_AXIS_X),
664 msgCoords.getAxisValue(AMOTION_EVENT_AXIS_Y));
666 msgCoords.setAxisValue(AMOTION_EVENT_AXIS_X, resampleCoords.getX());
667 msgCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, resampleCoords.getY());
672 void InputConsumer::resampleTouchState(nsecs_t sampleTime, MotionEvent* event,
673 const InputMessage* next) {
675 || !(event->getSource() & AINPUT_SOURCE_CLASS_POINTER)
676 || event->getAction() != AMOTION_EVENT_ACTION_MOVE) {
680 ssize_t index = findTouchState(event->getDeviceId(), event->getSource());
683 ALOGD("Not resampled, no touch state for device.");
688 TouchState& touchState = mTouchStates.editItemAt(index);
689 if (touchState.historySize < 1) {
691 ALOGD("Not resampled, no history for device.");
696 // Ensure that the current sample has all of the pointers that need to be reported.
697 const History* current = touchState.getHistory(0);
698 size_t pointerCount = event->getPointerCount();
699 for (size_t i = 0; i < pointerCount; i++) {
700 uint32_t id = event->getPointerId(i);
701 if (!current->idBits.hasBit(id)) {
703 ALOGD("Not resampled, missing id %d", id);
709 // Find the data to use for resampling.
710 const History* other;
714 // Interpolate between current sample and future sample.
715 // So current->eventTime <= sampleTime <= future.eventTime.
716 future.initializeFrom(next);
718 nsecs_t delta = future.eventTime - current->eventTime;
719 if (delta < RESAMPLE_MIN_DELTA) {
721 ALOGD("Not resampled, delta time is %lld ns.", delta);
725 alpha = float(sampleTime - current->eventTime) / delta;
726 } else if (touchState.historySize >= 2) {
727 // Extrapolate future sample using current sample and past sample.
728 // So other->eventTime <= current->eventTime <= sampleTime.
729 other = touchState.getHistory(1);
730 nsecs_t delta = current->eventTime - other->eventTime;
731 if (delta < RESAMPLE_MIN_DELTA) {
733 ALOGD("Not resampled, delta time is %lld ns.", delta);
737 nsecs_t maxPredict = current->eventTime + min(delta / 2, RESAMPLE_MAX_PREDICTION);
738 if (sampleTime > maxPredict) {
740 ALOGD("Sample time is too far in the future, adjusting prediction "
741 "from %lld to %lld ns.",
742 sampleTime - current->eventTime, maxPredict - current->eventTime);
744 sampleTime = maxPredict;
746 alpha = float(current->eventTime - sampleTime) / delta;
749 ALOGD("Not resampled, insufficient data.");
754 // Resample touch coordinates.
755 touchState.lastResample.eventTime = sampleTime;
756 touchState.lastResample.idBits.clear();
757 for (size_t i = 0; i < pointerCount; i++) {
758 uint32_t id = event->getPointerId(i);
759 touchState.lastResample.idToIndex[id] = i;
760 touchState.lastResample.idBits.markBit(id);
761 PointerCoords& resampledCoords = touchState.lastResample.pointers[i];
762 const PointerCoords& currentCoords = current->getPointerById(id);
763 if (other->idBits.hasBit(id)
764 && shouldResampleTool(event->getToolType(i))) {
765 const PointerCoords& otherCoords = other->getPointerById(id);
766 resampledCoords.copyFrom(currentCoords);
767 resampledCoords.setAxisValue(AMOTION_EVENT_AXIS_X,
768 lerp(currentCoords.getX(), otherCoords.getX(), alpha));
769 resampledCoords.setAxisValue(AMOTION_EVENT_AXIS_Y,
770 lerp(currentCoords.getY(), otherCoords.getY(), alpha));
772 ALOGD("[%d] - out (%0.3f, %0.3f), cur (%0.3f, %0.3f), "
773 "other (%0.3f, %0.3f), alpha %0.3f",
774 id, resampledCoords.getX(), resampledCoords.getY(),
775 currentCoords.getX(), currentCoords.getY(),
776 otherCoords.getX(), otherCoords.getY(),
780 resampledCoords.copyFrom(currentCoords);
782 ALOGD("[%d] - out (%0.3f, %0.3f), cur (%0.3f, %0.3f)",
783 id, resampledCoords.getX(), resampledCoords.getY(),
784 currentCoords.getX(), currentCoords.getY());
789 event->addSample(sampleTime, touchState.lastResample.pointers);
792 bool InputConsumer::shouldResampleTool(int32_t toolType) {
793 return toolType == AMOTION_EVENT_TOOL_TYPE_FINGER
794 || toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
797 status_t InputConsumer::sendFinishedSignal(uint32_t seq, bool handled) {
798 #if DEBUG_TRANSPORT_ACTIONS
799 ALOGD("channel '%s' consumer ~ sendFinishedSignal: seq=%u, handled=%s",
800 mChannel->getName().string(), seq, handled ? "true" : "false");
804 ALOGE("Attempted to send a finished signal with sequence number 0.");
808 // Send finished signals for the batch sequence chain first.
809 size_t seqChainCount = mSeqChains.size();
811 uint32_t currentSeq = seq;
812 uint32_t chainSeqs[seqChainCount];
813 size_t chainIndex = 0;
814 for (size_t i = seqChainCount; i-- > 0; ) {
815 const SeqChain& seqChain = mSeqChains.itemAt(i);
816 if (seqChain.seq == currentSeq) {
817 currentSeq = seqChain.chain;
818 chainSeqs[chainIndex++] = currentSeq;
819 mSeqChains.removeAt(i);
822 status_t status = OK;
823 while (!status && chainIndex-- > 0) {
824 status = sendUnchainedFinishedSignal(chainSeqs[chainIndex], handled);
827 // An error occurred so at least one signal was not sent, reconstruct the chain.
830 seqChain.seq = chainIndex != 0 ? chainSeqs[chainIndex - 1] : seq;
831 seqChain.chain = chainSeqs[chainIndex];
832 mSeqChains.push(seqChain);
833 } while (chainIndex-- > 0);
838 // Send finished signal for the last message in the batch.
839 return sendUnchainedFinishedSignal(seq, handled);
842 status_t InputConsumer::sendUnchainedFinishedSignal(uint32_t seq, bool handled) {
844 msg.header.type = InputMessage::TYPE_FINISHED;
845 msg.body.finished.seq = seq;
846 msg.body.finished.handled = handled;
847 return mChannel->sendMessage(&msg);
850 bool InputConsumer::hasDeferredEvent() const {
854 bool InputConsumer::hasPendingBatch() const {
855 return !mBatches.isEmpty();
858 ssize_t InputConsumer::findBatch(int32_t deviceId, int32_t source) const {
859 for (size_t i = 0; i < mBatches.size(); i++) {
860 const Batch& batch = mBatches.itemAt(i);
861 const InputMessage& head = batch.samples.itemAt(0);
862 if (head.body.motion.deviceId == deviceId && head.body.motion.source == source) {
869 ssize_t InputConsumer::findTouchState(int32_t deviceId, int32_t source) const {
870 for (size_t i = 0; i < mTouchStates.size(); i++) {
871 const TouchState& touchState = mTouchStates.itemAt(i);
872 if (touchState.deviceId == deviceId && touchState.source == source) {
879 void InputConsumer::initializeKeyEvent(KeyEvent* event, const InputMessage* msg) {
881 msg->body.key.deviceId,
882 msg->body.key.source,
883 msg->body.key.action,
885 msg->body.key.keyCode,
886 msg->body.key.scanCode,
887 msg->body.key.metaState,
888 msg->body.key.repeatCount,
889 msg->body.key.downTime,
890 msg->body.key.eventTime);
893 void InputConsumer::initializeMotionEvent(MotionEvent* event, const InputMessage* msg) {
894 size_t pointerCount = msg->body.motion.pointerCount;
895 PointerProperties pointerProperties[pointerCount];
896 PointerCoords pointerCoords[pointerCount];
897 for (size_t i = 0; i < pointerCount; i++) {
898 pointerProperties[i].copyFrom(msg->body.motion.pointers[i].properties);
899 pointerCoords[i].copyFrom(msg->body.motion.pointers[i].coords);
903 msg->body.motion.deviceId,
904 msg->body.motion.source,
905 msg->body.motion.action,
906 msg->body.motion.flags,
907 msg->body.motion.edgeFlags,
908 msg->body.motion.metaState,
909 msg->body.motion.buttonState,
910 msg->body.motion.xOffset,
911 msg->body.motion.yOffset,
912 msg->body.motion.xPrecision,
913 msg->body.motion.yPrecision,
914 msg->body.motion.downTime,
915 msg->body.motion.eventTime,
921 void InputConsumer::addSample(MotionEvent* event, const InputMessage* msg) {
922 size_t pointerCount = msg->body.motion.pointerCount;
923 PointerCoords pointerCoords[pointerCount];
924 for (size_t i = 0; i < pointerCount; i++) {
925 pointerCoords[i].copyFrom(msg->body.motion.pointers[i].coords);
928 event->setMetaState(event->getMetaState() | msg->body.motion.metaState);
929 event->addSample(msg->body.motion.eventTime, pointerCoords);
932 bool InputConsumer::canAddSample(const Batch& batch, const InputMessage *msg) {
933 const InputMessage& head = batch.samples.itemAt(0);
934 size_t pointerCount = msg->body.motion.pointerCount;
935 if (head.body.motion.pointerCount != pointerCount
936 || head.body.motion.action != msg->body.motion.action) {
939 for (size_t i = 0; i < pointerCount; i++) {
940 if (head.body.motion.pointers[i].properties
941 != msg->body.motion.pointers[i].properties) {
948 ssize_t InputConsumer::findSampleNoLaterThan(const Batch& batch, nsecs_t time) {
949 size_t numSamples = batch.samples.size();
951 while (index < numSamples
952 && batch.samples.itemAt(index).body.motion.eventTime <= time) {
955 return ssize_t(index) - 1;
958 } // namespace android