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
22
#include <androidfw/InputTransport.h>
23
#include <cutils/log.h>
24
#include <std/properties.h>
28
#include <sys/types.h>
29
#include <sys/socket.h>
32
#include <boost/throw_exception.hpp>
38
// Nanoseconds per milliseconds.
39
static constexpr const std::chrono::nanoseconds NANOS_PER_MS = std::chrono::nanoseconds(1000000);
41
// Latency added during resampling. A few milliseconds doesn't hurt much but
42
// reduces the impact of mispredicted touch positions.
43
static constexpr const std::chrono::nanoseconds RESAMPLE_LATENCY = std::chrono::nanoseconds(5 * NANOS_PER_MS);
45
// Minimum time difference between consecutive samples before attempting to resample.
46
static constexpr const std::chrono::nanoseconds RESAMPLE_MIN_DELTA = std::chrono::nanoseconds(2 * NANOS_PER_MS);
48
// Maximum time to predict forward from the last known state, to avoid predicting too
49
// far into the future. This time is further bounded by 50% of the last time delta.
50
static constexpr const std::chrono::nanoseconds RESAMPLE_MAX_PREDICTION = std::chrono::nanoseconds(8 * NANOS_PER_MS);
53
inline static T min(const T& a, const T& b) {
57
inline static float lerp(float a, float b, float alpha) {
58
return a + alpha * (b - a);
61
// --- InputMessage ---
63
InputMessage::InputMessage()
65
memset(this, 0, sizeof(InputMessage));
68
InputMessage::InputMessage(uint32_t seq, std::string const& buffer)
70
memset(this, 0, sizeof(InputMessage));
71
header.type = TYPE_BUFFER;
73
header.size = buffer.size();
75
if (raw_event_payload < buffer.size())
76
BOOST_THROW_EXCEPTION(std::runtime_error("raw buffer event exceeds payload"));
77
memcpy(body.buffer.buffer, buffer.data(), header.size);
80
InputMessage::InputMessage(InputMessage const& cp) = default;
82
InputMessage& InputMessage::operator=(InputMessage const& cp) = default;
84
bool InputMessage::isValid(size_t actualSize) const {
85
if (size() == actualSize) {
86
switch (header.type) {
92
return body.motion.pointerCount > 0
93
&& body.motion.pointerCount <= MAX_POINTERS;
99
size_t InputMessage::size() const {
100
switch (header.type) {
102
return sizeof(Header) + body.key.size();
104
return sizeof(Header) + body.motion.size();
106
return sizeof(Header) + body.finished.size();
108
return sizeof(Header) + header.size;
110
return sizeof(Header);
112
// --- InputChannel ---
114
InputChannel::InputChannel(const String8& name, int fd) :
115
mName(name), mFd(fd) {
116
#if DEBUG_CHANNEL_LIFECYCLE
117
ALOGD("Input channel constructed: name='%s', fd=%d",
121
int result = fcntl(mFd, F_SETFL, O_NONBLOCK);
122
LOG_ALWAYS_FATAL_IF(result != 0, "channel '%s' ~ Could not make socket "
123
"non-blocking. errno=%d", c_str(mName), errno);
126
InputChannel::~InputChannel() {
127
#if DEBUG_CHANNEL_LIFECYCLE
128
ALOGD("Input channel destroyed: name='%s', fd=%d",
133
status_t InputChannel::sendMessage(const InputMessage* msg) {
134
size_t msgLength = msg->size();
137
nWrite = ::send(mFd, msg, msgLength, MSG_DONTWAIT | MSG_NOSIGNAL);
138
} while (nWrite == -1 && errno == EINTR);
142
#if DEBUG_CHANNEL_MESSAGES
143
ALOGD("channel '%s' ~ error sending message of type %d, errno=%d", c_str(mName),
144
msg->header.type, error);
146
if (error == EAGAIN || error == EWOULDBLOCK) {
149
if (error == EPIPE || error == ENOTCONN) {
155
if (size_t(nWrite) != msgLength) {
156
#if DEBUG_CHANNEL_MESSAGES
157
ALOGD("channel '%s' ~ error sending message type %d, send was incomplete",
158
c_str(mName), msg->header.type);
163
#if DEBUG_CHANNEL_MESSAGES
164
ALOGD("channel '%s' ~ sent message of type %d", c_str(mName), msg->header.type);
169
status_t InputChannel::receiveMessage(InputMessage* msg) {
172
nRead = ::recv(mFd, msg, sizeof(InputMessage), MSG_DONTWAIT);
173
} while (nRead == -1 && errno == EINTR);
177
#if DEBUG_CHANNEL_MESSAGES
178
ALOGD("channel '%s' ~ receive message failed, errno=%d", c_str(mName), errno);
180
if (error == EAGAIN || error == EWOULDBLOCK) {
183
if (error == EPIPE || error == ENOTCONN) {
189
if (nRead == 0) { // check for EOF
190
#if DEBUG_CHANNEL_MESSAGES
191
ALOGD("channel '%s' ~ receive message failed because peer was closed", c_str(mName));
196
if (!msg->isValid(nRead)) {
197
#if DEBUG_CHANNEL_MESSAGES
198
ALOGD("channel '%s' ~ received invalid message", c_str(mName));
203
#if DEBUG_CHANNEL_MESSAGES
204
ALOGD("channel '%s' ~ received message of type %d", c_str(mName), msg->header.type);
210
// --- InputPublisher ---
212
InputPublisher::InputPublisher(const sp<InputChannel>& channel) :
216
InputPublisher::~InputPublisher() {
219
status_t InputPublisher::publishEventBuffer(uint32_t seq, std::string const& buffer) {
220
#if DEBUG_TRANSPORT_ACTIONS
221
ALOGD("channel '%s' publisher ~ publishInputBuffer: seq=%u", c_str(mChannel->getName()), seq);
225
ALOGE("Attempted to publish a buffer with sequence number 0.");
229
InputMessage msg(seq, buffer);
230
return mChannel->sendMessage(&msg);
233
status_t InputPublisher::publishKeyEvent(
243
mir::cookie::Blob const& cookieBlob,
244
std::chrono::nanoseconds downTime,
245
std::chrono::nanoseconds eventTime) {
246
#if DEBUG_TRANSPORT_ACTIONS
247
ALOGD("channel '%s' publisher ~ publishKeyEvent: seq=%u, deviceId=%d, source=0x%x, "
248
"action=0x%x, flags=0x%x, keyCode=%d, scanCode=%d, metaState=0x%x, repeatCount=%d,"
249
"downTime=%lld, eventTime=%lld",
250
c_str(mChannel->getName()), seq,
251
deviceId, source, action, flags, keyCode, scanCode, metaState, repeatCount,
252
downTime, eventTime);
256
ALOGE("Attempted to publish a key event with sequence number 0.");
261
msg.header.type = InputMessage::TYPE_KEY;
262
msg.header.seq = seq;
263
msg.header.size = sizeof(msg.body.key);
264
msg.body.key.deviceId = deviceId;
265
msg.body.key.source = source;
266
msg.body.key.action = action;
267
msg.body.key.flags = flags;
268
msg.body.key.keyCode = keyCode;
269
msg.body.key.scanCode = scanCode;
270
msg.body.key.metaState = metaState;
271
msg.body.key.repeatCount = repeatCount;
272
msg.body.key.cookieBlob = cookieBlob;
273
msg.body.key.downTime = downTime.count();
274
msg.body.key.eventTime = eventTime.count();
275
return mChannel->sendMessage(&msg);
278
status_t InputPublisher::publishMotionEvent(
291
mir::cookie::Blob const& cookieBlob,
292
std::chrono::nanoseconds downTime,
293
std::chrono::nanoseconds eventTime,
295
const PointerProperties* pointerProperties,
296
const PointerCoords* pointerCoords) {
297
#if DEBUG_TRANSPORT_ACTIONS
298
ALOGD("channel '%s' publisher ~ publishMotionEvent: seq=%u, deviceId=%d, source=0x%x, "
299
"action=0x%x, flags=0x%x, edgeFlags=0x%x, metaState=0x%x, buttonState=0x%x, "
300
"xOffset=%f, yOffset=%f, "
301
"xPrecision=%f, yPrecision=%f,"
302
"downTime=%lld, eventTime=%lld, pointerCount=%d",
303
c_str(mChannel->getName()), seq,
304
deviceId, source, action, flags, edgeFlags, metaState, buttonState,
305
xOffset, yOffset, xPrecision, yPrecision, downTime, eventTime, pointerCount);
309
ALOGE("Attempted to publish a motion event with sequence number 0.");
313
if (pointerCount > MAX_POINTERS || pointerCount < 1) {
314
ALOGE("channel '%s' publisher ~ Invalid number of pointers provided: %d.",
315
c_str(mChannel->getName()), pointerCount);
320
msg.header.type = InputMessage::TYPE_MOTION;
321
msg.header.seq = seq;
322
msg.body.motion.deviceId = deviceId;
323
msg.body.motion.source = source;
324
msg.body.motion.action = action;
325
msg.body.motion.flags = flags;
326
msg.body.motion.edgeFlags = edgeFlags;
327
msg.body.motion.metaState = metaState;
328
msg.body.motion.buttonState = buttonState;
329
msg.body.motion.xOffset = xOffset;
330
msg.body.motion.yOffset = yOffset;
331
msg.body.motion.xPrecision = xPrecision;
332
msg.body.motion.yPrecision = yPrecision;
333
msg.body.motion.cookieBlob = cookieBlob;
334
msg.body.motion.downTime = downTime.count();
335
msg.body.motion.eventTime = eventTime.count();
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]);
342
msg.header.size = msg.body.motion.size();
343
return mChannel->sendMessage(&msg);
346
status_t InputPublisher::receiveFinishedSignal(uint32_t* outSeq, bool* outHandled) {
347
#if DEBUG_TRANSPORT_ACTIONS
348
ALOGD("channel '%s' publisher ~ receiveFinishedSignal",
349
c_str(mChannel->getName()));
353
status_t result = mChannel->receiveMessage(&msg);
359
if (msg.header.type != InputMessage::TYPE_FINISHED) {
360
ALOGE("channel '%s' publisher ~ Received unexpected message of type %d from consumer",
361
c_str(mChannel->getName()), msg.header.type);
362
return UNKNOWN_ERROR;
364
*outSeq = msg.header.seq;
365
*outHandled = msg.body.finished.handled;
369
// --- InputConsumer ---
371
InputConsumer::InputConsumer(const sp<InputChannel>& channel) :
372
mResampleTouch(isTouchResamplingEnabled()),
373
mChannel(channel), mMsgDeferred(false) {
376
InputConsumer::~InputConsumer() {
379
bool InputConsumer::isTouchResamplingEnabled() {
380
char value[PROPERTY_VALUE_MAX];
381
int length = property_get("debug.inputconsumer.resample", value, NULL);
383
if (!strcmp("0", value)) {
386
if (strcmp("1", value)) {
387
ALOGD("Unrecognized property value for 'debug.inputconsumer.resample'. "
394
status_t InputConsumer::consume(InputEventFactoryInterface* factory,
395
bool consumeBatches, std::chrono::nanoseconds frameTime, uint32_t* outSeq, InputEvent** outEvent) {
396
#if DEBUG_TRANSPORT_ACTIONS
397
ALOGD("channel '%s' consumer ~ consume: consumeBatches=%s, frameTime=%lld",
398
c_str(mChannel->getName()), consumeBatches ? "true" : "false", frameTime);
404
// Fetch the next input message.
405
// Loop until an event can be returned or no additional events are received.
408
// mMsg contains a valid input message from the previous call to consume
409
// that has not yet been processed.
410
mMsgDeferred = false;
412
// Receive a fresh message.
413
status_t result = mChannel->receiveMessage(&mMsg);
415
// Consume the next batched event unless batches are being held for later.
416
if (consumeBatches || result != WOULD_BLOCK) {
417
result = consumeBatch(factory, frameTime, outSeq, outEvent);
419
#if DEBUG_TRANSPORT_ACTIONS
420
ALOGD("channel '%s' consumer ~ consumed batch event, seq=%u",
421
c_str(mChannel->getName()), *outSeq);
430
switch (mMsg.header.type) {
431
case InputMessage::TYPE_BUFFER: {
432
RawBufferEvent* bufferEvent = factory->createRawBufferEvent();
433
if (!bufferEvent) return NO_MEMORY;
435
initializeBufferEvent(bufferEvent, &mMsg);
436
*outSeq = mMsg.header.seq;
437
*outEvent = bufferEvent;
438
#if DEBUG_TRANSPORT_ACTIONS
439
ALOGD("channel '%s' consumer ~ consumed buffer event, seq=%u",
440
c_str(mChannel->getName()), *outSeq);
444
case InputMessage::TYPE_KEY: {
445
KeyEvent* keyEvent = factory->createKeyEvent();
446
if (!keyEvent) return NO_MEMORY;
448
initializeKeyEvent(keyEvent, &mMsg);
449
*outSeq = mMsg.header.seq;
450
*outEvent = keyEvent;
451
#if DEBUG_TRANSPORT_ACTIONS
452
ALOGD("channel '%s' consumer ~ consumed key event, seq=%u",
453
c_str(mChannel->getName()), *outSeq);
458
case AINPUT_EVENT_TYPE_MOTION: {
459
ssize_t batchIndex = findBatch(mMsg.body.motion.deviceId, mMsg.body.motion.source);
460
if (batchIndex >= 0) {
461
Batch& batch = mBatches.editItemAt(batchIndex);
462
if (canAddSample(batch, &mMsg)) {
463
batch.samples.push(mMsg);
464
#if DEBUG_TRANSPORT_ACTIONS
465
ALOGD("channel '%s' consumer ~ appended to batch event",
466
c_str(mChannel->getName()));
470
// We cannot append to the batch in progress, so we need to consume
471
// the previous batch right now and defer the new message until later.
473
status_t result = consumeSamples(factory,
474
batch, batch.samples.size(), outSeq, outEvent);
475
mBatches.removeAt(batchIndex);
479
#if DEBUG_TRANSPORT_ACTIONS
480
ALOGD("channel '%s' consumer ~ consumed batch event and "
481
"deferred current event, seq=%u",
482
c_str(mChannel->getName()), *outSeq);
488
// Start a new batch if needed.
489
if ((mMsg.body.motion.action == AMOTION_EVENT_ACTION_MOVE
490
|| mMsg.body.motion.action == AMOTION_EVENT_ACTION_HOVER_MOVE)
491
&& frameTime.count() >= 0) {
493
Batch& batch = mBatches.editTop();
494
batch.samples.push(mMsg);
495
#if DEBUG_TRANSPORT_ACTIONS
496
ALOGD("channel '%s' consumer ~ started batch event",
497
c_str(mChannel->getName()));
502
MotionEvent* motionEvent = factory->createMotionEvent();
503
if (! motionEvent) return NO_MEMORY;
505
updateTouchState(&mMsg);
506
initializeMotionEvent(motionEvent, &mMsg);
507
*outSeq = mMsg.header.seq;
508
*outEvent = motionEvent;
509
#if DEBUG_TRANSPORT_ACTIONS
510
ALOGD("channel '%s' consumer ~ consumed motion event, seq=%u",
511
c_str(mChannel->getName()), *outSeq);
517
ALOGE("channel '%s' consumer ~ Received unexpected message of type %d",
518
c_str(mChannel->getName()), mMsg.header.type);
519
return UNKNOWN_ERROR;
525
status_t InputConsumer::consumeBatch(InputEventFactoryInterface* factory,
526
std::chrono::nanoseconds frameTime, uint32_t* outSeq, InputEvent** outEvent) {
528
for (size_t i = mBatches.size(); i-- > 0; ) {
529
Batch& batch = mBatches.editItemAt(i);
530
if (frameTime < std::chrono::nanoseconds(0)) {
531
result = consumeSamples(factory, batch, batch.samples.size(),
533
mBatches.removeAt(i);
537
std::chrono::nanoseconds sampleTime = frameTime - RESAMPLE_LATENCY;
538
ssize_t split = findSampleNoLaterThan(batch, sampleTime);
543
result = consumeSamples(factory, batch, split + 1, outSeq, outEvent);
544
const InputMessage* next;
545
if (batch.samples.isEmpty()) {
546
mBatches.removeAt(i);
549
next = &batch.samples.itemAt(0);
552
resampleTouchState(sampleTime, static_cast<MotionEvent*>(*outEvent), next);
560
status_t InputConsumer::consumeSamples(InputEventFactoryInterface* factory,
561
Batch& batch, size_t count, uint32_t* outSeq, InputEvent** outEvent) {
562
MotionEvent* motionEvent = factory->createMotionEvent();
563
if (! motionEvent) return NO_MEMORY;
566
for (size_t i = 0; i < count; i++) {
567
InputMessage& msg = batch.samples.editItemAt(i);
568
updateTouchState(&msg);
571
seqChain.seq = msg.header.seq;
572
seqChain.chain = chain;
573
mSeqChains.push(seqChain);
574
addSample(motionEvent, &msg);
576
initializeMotionEvent(motionEvent, &msg);
578
chain = msg.header.seq;
580
batch.samples.removeItemsAt(0, count);
583
*outEvent = motionEvent;
587
void InputConsumer::updateTouchState(InputMessage* msg) {
588
if (!mResampleTouch ||
589
!(msg->body.motion.source & AINPUT_SOURCE_CLASS_POINTER)) {
593
int32_t deviceId = msg->body.motion.deviceId;
594
int32_t source = msg->body.motion.source;
595
std::chrono::nanoseconds eventTime = std::chrono::nanoseconds(msg->body.motion.eventTime);
597
// Update the touch state history to incorporate the new input message.
598
// If the message is in the past relative to the most recently produced resampled
599
// touch, then use the resampled time and coordinates instead.
600
switch (msg->body.motion.action & AMOTION_EVENT_ACTION_MASK) {
601
case AMOTION_EVENT_ACTION_DOWN: {
602
ssize_t index = findTouchState(deviceId, source);
605
index = mTouchStates.size() - 1;
607
TouchState& touchState = mTouchStates.editItemAt(index);
608
touchState.initialize(deviceId, source);
609
touchState.addHistory(msg);
613
case AMOTION_EVENT_ACTION_MOVE: {
614
ssize_t index = findTouchState(deviceId, source);
616
TouchState& touchState = mTouchStates.editItemAt(index);
617
touchState.addHistory(msg);
618
if (eventTime < touchState.lastResample.eventTime) {
619
rewriteMessage(touchState, msg);
621
touchState.lastResample.ids.clear();
627
case AMOTION_EVENT_ACTION_POINTER_DOWN: {
628
ssize_t index = findTouchState(deviceId, source);
630
TouchState& touchState = mTouchStates.editItemAt(index);
631
touchState.lastResample.ids.remove(msg->body.motion.getActionId());
632
rewriteMessage(touchState, msg);
637
case AMOTION_EVENT_ACTION_POINTER_UP: {
638
ssize_t index = findTouchState(deviceId, source);
640
TouchState& touchState = mTouchStates.editItemAt(index);
641
rewriteMessage(touchState, msg);
642
touchState.lastResample.ids.remove(msg->body.motion.getActionId());
647
case AMOTION_EVENT_ACTION_SCROLL: {
648
ssize_t index = findTouchState(deviceId, source);
650
const TouchState& touchState = mTouchStates.itemAt(index);
651
rewriteMessage(touchState, msg);
656
case AMOTION_EVENT_ACTION_UP:
657
case AMOTION_EVENT_ACTION_CANCEL: {
658
ssize_t index = findTouchState(deviceId, source);
660
const TouchState& touchState = mTouchStates.itemAt(index);
661
rewriteMessage(touchState, msg);
662
mTouchStates.removeAt(index);
669
void InputConsumer::rewriteMessage(const TouchState& state, InputMessage* msg) {
670
for (size_t i = 0; i < msg->body.motion.pointerCount; i++) {
671
uint32_t id = msg->body.motion.pointers[i].properties.id;
672
if (state.lastResample.ids.contains(id)) {
673
PointerCoords& msgCoords = msg->body.motion.pointers[i].coords;
674
const PointerCoords& resampleCoords = state.lastResample.getPointerById(id);
676
ALOGD("[%d] - rewrite (%0.3f, %0.3f), old (%0.3f, %0.3f)", id,
677
resampleCoords.getAxisValue(AMOTION_EVENT_AXIS_X),
678
resampleCoords.getAxisValue(AMOTION_EVENT_AXIS_Y),
679
msgCoords.getAxisValue(AMOTION_EVENT_AXIS_X),
680
msgCoords.getAxisValue(AMOTION_EVENT_AXIS_Y));
682
msgCoords.setAxisValue(AMOTION_EVENT_AXIS_X, resampleCoords.getX());
683
msgCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, resampleCoords.getY());
688
void InputConsumer::resampleTouchState(std::chrono::nanoseconds sampleTime, MotionEvent* event,
689
const InputMessage* next) {
691
|| !(event->getSource() & AINPUT_SOURCE_CLASS_POINTER)
692
|| event->getAction() != AMOTION_EVENT_ACTION_MOVE) {
696
ssize_t index = findTouchState(event->getDeviceId(), event->getSource());
699
ALOGD("Not resampled, no touch state for device.");
704
TouchState& touchState = mTouchStates.editItemAt(index);
705
if (touchState.historySize < 1) {
707
ALOGD("Not resampled, no history for device.");
712
// Ensure that the current sample has all of the pointers that need to be reported.
713
const History* current = touchState.getHistory(0);
714
size_t pointerCount = event->getPointerCount();
715
for (size_t i = 0; i < pointerCount; i++) {
716
uint32_t id = event->getPointerId(i);
717
if (!current->ids.contains(id)) {
719
ALOGD("Not resampled, missing id %d", id);
725
// Find the data to use for resampling.
726
const History* other;
730
// Interpolate between current sample and future sample.
731
// So current->eventTime <= sampleTime <= future.eventTime.
732
future.initializeFrom(next);
734
std::chrono::nanoseconds delta = future.eventTime - current->eventTime;
735
if (delta < RESAMPLE_MIN_DELTA) {
737
ALOGD("Not resampled, delta time is %lld ns.", delta);
741
alpha = (float)((sampleTime - current->eventTime).count()) / delta.count();
742
} else if (touchState.historySize >= 2) {
743
// Extrapolate future sample using current sample and past sample.
744
// So other->eventTime <= current->eventTime <= sampleTime.
745
other = touchState.getHistory(1);
746
std::chrono::nanoseconds delta = current->eventTime - other->eventTime;
747
if (delta < RESAMPLE_MIN_DELTA) {
749
ALOGD("Not resampled, delta time is %lld ns.", delta);
753
std::chrono::nanoseconds maxPredict = current->eventTime + std::chrono::nanoseconds(min(delta.count()/2, RESAMPLE_MAX_PREDICTION.count()));
754
if (sampleTime > maxPredict) {
756
ALOGD("Sample time is too far in the future, adjusting prediction "
757
"from %lld to %lld ns.",
758
sampleTime - current->eventTime, maxPredict - current->eventTime);
760
sampleTime = maxPredict;
762
alpha = (float)((current->eventTime - sampleTime).count()) / delta.count();
765
ALOGD("Not resampled, insufficient data.");
770
// Resample touch coordinates.
771
touchState.lastResample.eventTime = sampleTime;
772
touchState.lastResample.ids.clear();
773
bool coords_resampled = false;
774
for (size_t i = 0; i < pointerCount; i++) {
775
uint32_t id = event->getPointerId(i);
776
touchState.lastResample.idToIndex[id] = i;
777
touchState.lastResample.ids.insert(id);
778
PointerCoords& resampledCoords = touchState.lastResample.pointers[i];
779
const PointerCoords& currentCoords = current->getPointerById(id);
780
if (other->ids.contains(id)
781
&& shouldResampleTool(event->getToolType(i))) {
782
const PointerCoords& otherCoords = other->getPointerById(id);
783
resampledCoords.copyFrom(currentCoords);
784
resampledCoords.setAxisValue(AMOTION_EVENT_AXIS_X,
785
lerp(currentCoords.getX(), otherCoords.getX(), alpha));
786
resampledCoords.setAxisValue(AMOTION_EVENT_AXIS_Y,
787
lerp(currentCoords.getY(), otherCoords.getY(), alpha));
788
coords_resampled = true;
789
// No coordinate resampling for tooltype mouse - if we intend to
790
// change that we must also resample RX, RY, HSCROLL, VSCROLL
792
ALOGD("[%d] - out (%0.3f, %0.3f), cur (%0.3f, %0.3f), "
793
"other (%0.3f, %0.3f), alpha %0.3f",
794
id, resampledCoords.getX(), resampledCoords.getY(),
795
currentCoords.getX(), currentCoords.getY(),
796
otherCoords.getX(), otherCoords.getY(),
800
// Before calling this method currentCoords was already part of the
801
// event -> no need to add them to the event.
802
resampledCoords.copyFrom(currentCoords);
804
ALOGD("[%d] - out (%0.3f, %0.3f), cur (%0.3f, %0.3f)",
805
id, resampledCoords.getX(), resampledCoords.getY(),
806
currentCoords.getX(), currentCoords.getY());
811
if (coords_resampled)
812
event->addSample(sampleTime, touchState.lastResample.pointers);
815
bool InputConsumer::shouldResampleTool(int32_t toolType) {
816
return toolType == AMOTION_EVENT_TOOL_TYPE_FINGER
817
|| toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
820
status_t InputConsumer::sendFinishedSignal(uint32_t seq, bool handled) {
821
#if DEBUG_TRANSPORT_ACTIONS
822
ALOGD("channel '%s' consumer ~ sendFinishedSignal: seq=%u, handled=%s",
823
c_str(mChannel->getName()), seq, handled ? "true" : "false");
827
ALOGE("Attempted to send a finished signal with sequence number 0.");
831
// Send finished signals for the batch sequence chain first.
832
size_t seqChainCount = mSeqChains.size();
834
uint32_t currentSeq = seq;
835
uint32_t chainSeqs[seqChainCount];
836
size_t chainIndex = 0;
837
for (size_t i = seqChainCount; i-- > 0; ) {
838
const SeqChain& seqChain = mSeqChains.itemAt(i);
839
if (seqChain.seq == currentSeq) {
840
currentSeq = seqChain.chain;
841
chainSeqs[chainIndex++] = currentSeq;
842
mSeqChains.removeAt(i);
845
status_t status = OK;
846
while (!status && chainIndex-- > 0) {
847
status = sendUnchainedFinishedSignal(chainSeqs[chainIndex], handled);
850
// An error occurred so at least one signal was not sent, reconstruct the chain.
853
seqChain.seq = chainIndex != 0 ? chainSeqs[chainIndex - 1] : seq;
854
seqChain.chain = chainSeqs[chainIndex];
855
mSeqChains.push(seqChain);
856
} while (chainIndex-- > 0);
861
// Send finished signal for the last message in the batch.
862
return sendUnchainedFinishedSignal(seq, handled);
865
status_t InputConsumer::sendUnchainedFinishedSignal(uint32_t seq, bool handled) {
867
msg.header.type = InputMessage::TYPE_FINISHED;
868
msg.header.size = sizeof(msg.body.finished);
869
msg.header.seq = seq;
870
msg.body.finished.handled = handled;
871
return mChannel->sendMessage(&msg);
874
bool InputConsumer::hasDeferredEvent() const {
878
bool InputConsumer::hasPendingBatch() const {
879
return !mBatches.isEmpty();
882
ssize_t InputConsumer::findBatch(int32_t deviceId, int32_t source) const {
883
for (size_t i = 0; i < mBatches.size(); i++) {
884
const Batch& batch = mBatches.itemAt(i);
885
const InputMessage& head = batch.samples.itemAt(0);
886
if (head.body.motion.deviceId == deviceId && head.body.motion.source == source) {
893
ssize_t InputConsumer::findTouchState(int32_t deviceId, int32_t source) const {
894
for (size_t i = 0; i < mTouchStates.size(); i++) {
895
const TouchState& touchState = mTouchStates.itemAt(i);
896
if (touchState.deviceId == deviceId && touchState.source == source) {
903
void InputConsumer::initializeBufferEvent(RawBufferEvent* event, const InputMessage* msg) {
904
event->buffer.assign(msg->body.buffer.buffer, msg->body.buffer.buffer + msg->header.size);
907
void InputConsumer::initializeKeyEvent(KeyEvent* event, const InputMessage* msg) {
909
msg->body.key.deviceId,
910
msg->body.key.source,
911
msg->body.key.action,
913
msg->body.key.keyCode,
914
msg->body.key.scanCode,
915
msg->body.key.metaState,
916
msg->body.key.repeatCount,
917
msg->body.key.cookieBlob,
918
std::chrono::nanoseconds(msg->body.key.downTime),
919
std::chrono::nanoseconds(msg->body.key.eventTime));
922
void InputConsumer::initializeMotionEvent(MotionEvent* event, const InputMessage* msg) {
923
size_t pointerCount = msg->body.motion.pointerCount;
924
PointerProperties pointerProperties[pointerCount];
925
PointerCoords pointerCoords[pointerCount];
926
for (size_t i = 0; i < pointerCount; i++) {
927
pointerProperties[i].copyFrom(msg->body.motion.pointers[i].properties);
928
pointerCoords[i].copyFrom(msg->body.motion.pointers[i].coords);
932
msg->body.motion.deviceId,
933
msg->body.motion.source,
934
msg->body.motion.action,
935
msg->body.motion.flags,
936
msg->body.motion.edgeFlags,
937
msg->body.motion.metaState,
938
msg->body.motion.buttonState,
939
msg->body.motion.xOffset,
940
msg->body.motion.yOffset,
941
msg->body.motion.xPrecision,
942
msg->body.motion.yPrecision,
943
msg->body.motion.cookieBlob,
944
std::chrono::nanoseconds(msg->body.motion.downTime),
945
std::chrono::nanoseconds(msg->body.motion.eventTime),
951
void InputConsumer::addSample(MotionEvent* event, const InputMessage* msg) {
952
size_t pointerCount = msg->body.motion.pointerCount;
953
PointerCoords pointerCoords[pointerCount];
954
for (size_t i = 0; i < pointerCount; i++) {
955
pointerCoords[i].copyFrom(msg->body.motion.pointers[i].coords);
958
event->setMetaState(event->getMetaState() | msg->body.motion.metaState);
959
event->addSample(std::chrono::nanoseconds(msg->body.motion.eventTime), pointerCoords);
962
bool InputConsumer::canAddSample(const Batch& batch, const InputMessage *msg) {
963
const InputMessage& head = batch.samples.itemAt(0);
964
size_t pointerCount = msg->body.motion.pointerCount;
965
if (head.body.motion.pointerCount != pointerCount
966
|| head.body.motion.action != msg->body.motion.action) {
969
for (size_t i = 0; i < pointerCount; i++) {
970
if (head.body.motion.pointers[i].properties
971
!= msg->body.motion.pointers[i].properties) {
978
ssize_t InputConsumer::findSampleNoLaterThan(const Batch& batch, std::chrono::nanoseconds time) {
979
size_t numSamples = batch.samples.size();
981
while (index < numSamples
982
&& batch.samples.itemAt(index).body.motion.eventTime <= time.count()) {
985
return ssize_t(index) - 1;
988
} // namespace android