1 /* 2 * Copyright (C) 2010 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 #ifndef _LIBINPUT_INPUT_TRANSPORT_H 18 #define _LIBINPUT_INPUT_TRANSPORT_H 19 20 /** 21 * Native input transport. 22 * 23 * The InputChannel provides a mechanism for exchanging InputMessage structures across processes. 24 * 25 * The InputPublisher and InputConsumer each handle one end-point of an input channel. 26 * The InputPublisher is used by the input dispatcher to send events to the application. 27 * The InputConsumer is used by the application to receive events from the input dispatcher. 28 */ 29 30 #include <input/Input.h> 31 #include <utils/Errors.h> 32 #include <utils/Timers.h> 33 #include <utils/RefBase.h> 34 #include <utils/String8.h> 35 #include <utils/Vector.h> 36 #include <utils/BitSet.h> 37 38 namespace android { 39 40 /* 41 * Intermediate representation used to send input events and related signals. 42 * 43 * Note that this structure is used for IPCs so its layout must be identical 44 * on 64 and 32 bit processes. This is tested in StructLayout_test.cpp. 45 * 46 * Since the struct must be aligned to an 8-byte boundary, there could be uninitialized bytes 47 * in-between the defined fields. This padding data should be explicitly accounted for by adding 48 * "empty" fields into the struct. This data is memset to zero before sending the struct across 49 * the socket. Adding the explicit fields ensures that the memset is not optimized away by the 50 * compiler. When a new field is added to the struct, the corresponding change 51 * in StructLayout_test should be made. 52 */ 53 struct InputMessage { 54 enum { 55 TYPE_KEY = 1, 56 TYPE_MOTION = 2, 57 TYPE_FINISHED = 3, 58 }; 59 60 struct Header { 61 uint32_t type; 62 // We don't need this field in order to align the body below but we 63 // leave it here because InputMessage::size() and other functions 64 // compute the size of this structure as sizeof(Header) + sizeof(Body). 65 uint32_t padding; 66 } header; 67 68 // Body *must* be 8 byte aligned. 69 union Body { 70 struct Key { 71 uint32_t seq; 72 uint32_t empty1; 73 nsecs_t eventTime __attribute__((aligned(8))); 74 int32_t deviceId; 75 int32_t source; 76 int32_t displayId; 77 int32_t action; 78 int32_t flags; 79 int32_t keyCode; 80 int32_t scanCode; 81 int32_t metaState; 82 int32_t repeatCount; 83 uint32_t empty2; 84 nsecs_t downTime __attribute__((aligned(8))); 85 sizeInputMessage::Body::Key86 inline size_t size() const { 87 return sizeof(Key); 88 } 89 } key; 90 91 struct Motion { 92 uint32_t seq; 93 uint32_t empty1; 94 nsecs_t eventTime __attribute__((aligned(8))); 95 int32_t deviceId; 96 int32_t source; 97 int32_t displayId; 98 int32_t action; 99 int32_t actionButton; 100 int32_t flags; 101 int32_t metaState; 102 int32_t buttonState; 103 int32_t edgeFlags; 104 uint32_t empty2; 105 nsecs_t downTime __attribute__((aligned(8))); 106 float xOffset; 107 float yOffset; 108 float xPrecision; 109 float yPrecision; 110 uint32_t pointerCount; 111 uint32_t empty3; 112 // Note that PointerCoords requires 8 byte alignment. 113 struct Pointer { 114 PointerProperties properties; 115 PointerCoords coords; 116 } pointers[MAX_POINTERS]; 117 getActionIdInputMessage::Body::Motion118 int32_t getActionId() const { 119 uint32_t index = (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) 120 >> AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT; 121 return pointers[index].properties.id; 122 } 123 sizeInputMessage::Body::Motion124 inline size_t size() const { 125 return sizeof(Motion) - sizeof(Pointer) * MAX_POINTERS 126 + sizeof(Pointer) * pointerCount; 127 } 128 } motion; 129 130 struct Finished { 131 uint32_t seq; 132 bool handled; 133 sizeInputMessage::Body::Finished134 inline size_t size() const { 135 return sizeof(Finished); 136 } 137 } finished; 138 } __attribute__((aligned(8))) body; 139 140 bool isValid(size_t actualSize) const; 141 size_t size() const; 142 void getSanitizedCopy(InputMessage* msg) const; 143 }; 144 145 /* 146 * An input channel consists of a local unix domain socket used to send and receive 147 * input messages across processes. Each channel has a descriptive name for debugging purposes. 148 * 149 * Each endpoint has its own InputChannel object that specifies its file descriptor. 150 * 151 * The input channel is closed when all references to it are released. 152 */ 153 class InputChannel : public RefBase { 154 protected: 155 virtual ~InputChannel(); 156 157 public: 158 InputChannel(const String8& name, int fd); 159 160 /* Creates a pair of input channels. 161 * 162 * Returns OK on success. 163 */ 164 static status_t openInputChannelPair(const String8& name, 165 sp<InputChannel>& outServerChannel, sp<InputChannel>& outClientChannel); 166 getName()167 inline String8 getName() const { return mName; } getFd()168 inline int getFd() const { return mFd; } 169 170 /* Sends a message to the other endpoint. 171 * 172 * If the channel is full then the message is guaranteed not to have been sent at all. 173 * Try again after the consumer has sent a finished signal indicating that it has 174 * consumed some of the pending messages from the channel. 175 * 176 * Returns OK on success. 177 * Returns WOULD_BLOCK if the channel is full. 178 * Returns DEAD_OBJECT if the channel's peer has been closed. 179 * Other errors probably indicate that the channel is broken. 180 */ 181 status_t sendMessage(const InputMessage* msg); 182 183 /* Receives a message sent by the other endpoint. 184 * 185 * If there is no message present, try again after poll() indicates that the fd 186 * is readable. 187 * 188 * Returns OK on success. 189 * Returns WOULD_BLOCK if there is no message present. 190 * Returns DEAD_OBJECT if the channel's peer has been closed. 191 * Other errors probably indicate that the channel is broken. 192 */ 193 status_t receiveMessage(InputMessage* msg); 194 195 /* Returns a new object that has a duplicate of this channel's fd. */ 196 sp<InputChannel> dup() const; 197 198 private: 199 String8 mName; 200 int mFd; 201 }; 202 203 /* 204 * Publishes input events to an input channel. 205 */ 206 class InputPublisher { 207 public: 208 /* Creates a publisher associated with an input channel. */ 209 explicit InputPublisher(const sp<InputChannel>& channel); 210 211 /* Destroys the publisher and releases its input channel. */ 212 ~InputPublisher(); 213 214 /* Gets the underlying input channel. */ getChannel()215 inline sp<InputChannel> getChannel() { return mChannel; } 216 217 /* Publishes a key event to the input channel. 218 * 219 * Returns OK on success. 220 * Returns WOULD_BLOCK if the channel is full. 221 * Returns DEAD_OBJECT if the channel's peer has been closed. 222 * Returns BAD_VALUE if seq is 0. 223 * Other errors probably indicate that the channel is broken. 224 */ 225 status_t publishKeyEvent( 226 uint32_t seq, 227 int32_t deviceId, 228 int32_t source, 229 int32_t action, 230 int32_t flags, 231 int32_t keyCode, 232 int32_t scanCode, 233 int32_t metaState, 234 int32_t repeatCount, 235 nsecs_t downTime, 236 nsecs_t eventTime); 237 238 /* Publishes a motion event to the input channel. 239 * 240 * Returns OK on success. 241 * Returns WOULD_BLOCK if the channel is full. 242 * Returns DEAD_OBJECT if the channel's peer has been closed. 243 * Returns BAD_VALUE if seq is 0 or if pointerCount is less than 1 or greater than MAX_POINTERS. 244 * Other errors probably indicate that the channel is broken. 245 */ 246 status_t publishMotionEvent( 247 uint32_t seq, 248 int32_t deviceId, 249 int32_t source, 250 int32_t displayId, 251 int32_t action, 252 int32_t actionButton, 253 int32_t flags, 254 int32_t edgeFlags, 255 int32_t metaState, 256 int32_t buttonState, 257 float xOffset, 258 float yOffset, 259 float xPrecision, 260 float yPrecision, 261 nsecs_t downTime, 262 nsecs_t eventTime, 263 uint32_t pointerCount, 264 const PointerProperties* pointerProperties, 265 const PointerCoords* pointerCoords); 266 267 /* Receives the finished signal from the consumer in reply to the original dispatch signal. 268 * If a signal was received, returns the message sequence number, 269 * and whether the consumer handled the message. 270 * 271 * The returned sequence number is never 0 unless the operation failed. 272 * 273 * Returns OK on success. 274 * Returns WOULD_BLOCK if there is no signal present. 275 * Returns DEAD_OBJECT if the channel's peer has been closed. 276 * Other errors probably indicate that the channel is broken. 277 */ 278 status_t receiveFinishedSignal(uint32_t* outSeq, bool* outHandled); 279 280 private: 281 sp<InputChannel> mChannel; 282 }; 283 284 /* 285 * Consumes input events from an input channel. 286 */ 287 class InputConsumer { 288 public: 289 /* Creates a consumer associated with an input channel. */ 290 explicit InputConsumer(const sp<InputChannel>& channel); 291 292 /* Destroys the consumer and releases its input channel. */ 293 ~InputConsumer(); 294 295 /* Gets the underlying input channel. */ getChannel()296 inline sp<InputChannel> getChannel() { return mChannel; } 297 298 /* Consumes an input event from the input channel and copies its contents into 299 * an InputEvent object created using the specified factory. 300 * 301 * Tries to combine a series of move events into larger batches whenever possible. 302 * 303 * If consumeBatches is false, then defers consuming pending batched events if it 304 * is possible for additional samples to be added to them later. Call hasPendingBatch() 305 * to determine whether a pending batch is available to be consumed. 306 * 307 * If consumeBatches is true, then events are still batched but they are consumed 308 * immediately as soon as the input channel is exhausted. 309 * 310 * The frameTime parameter specifies the time when the current display frame started 311 * rendering in the CLOCK_MONOTONIC time base, or -1 if unknown. 312 * 313 * The returned sequence number is never 0 unless the operation failed. 314 * 315 * Returns OK on success. 316 * Returns WOULD_BLOCK if there is no event present. 317 * Returns DEAD_OBJECT if the channel's peer has been closed. 318 * Returns NO_MEMORY if the event could not be created. 319 * Other errors probably indicate that the channel is broken. 320 */ 321 status_t consume(InputEventFactoryInterface* factory, bool consumeBatches, 322 nsecs_t frameTime, uint32_t* outSeq, InputEvent** outEvent, int32_t* displayId); 323 324 /* Sends a finished signal to the publisher to inform it that the message 325 * with the specified sequence number has finished being process and whether 326 * the message was handled by the consumer. 327 * 328 * Returns OK on success. 329 * Returns BAD_VALUE if seq is 0. 330 * Other errors probably indicate that the channel is broken. 331 */ 332 status_t sendFinishedSignal(uint32_t seq, bool handled); 333 334 /* Returns true if there is a deferred event waiting. 335 * 336 * Should be called after calling consume() to determine whether the consumer 337 * has a deferred event to be processed. Deferred events are somewhat special in 338 * that they have already been removed from the input channel. If the input channel 339 * becomes empty, the client may need to do extra work to ensure that it processes 340 * the deferred event despite the fact that the input channel's file descriptor 341 * is not readable. 342 * 343 * One option is simply to call consume() in a loop until it returns WOULD_BLOCK. 344 * This guarantees that all deferred events will be processed. 345 * 346 * Alternately, the caller can call hasDeferredEvent() to determine whether there is 347 * a deferred event waiting and then ensure that its event loop wakes up at least 348 * one more time to consume the deferred event. 349 */ 350 bool hasDeferredEvent() const; 351 352 /* Returns true if there is a pending batch. 353 * 354 * Should be called after calling consume() with consumeBatches == false to determine 355 * whether consume() should be called again later on with consumeBatches == true. 356 */ 357 bool hasPendingBatch() const; 358 359 private: 360 // True if touch resampling is enabled. 361 const bool mResampleTouch; 362 363 // The input channel. 364 sp<InputChannel> mChannel; 365 366 // The current input message. 367 InputMessage mMsg; 368 369 // True if mMsg contains a valid input message that was deferred from the previous 370 // call to consume and that still needs to be handled. 371 bool mMsgDeferred; 372 373 // Batched motion events per device and source. 374 struct Batch { 375 Vector<InputMessage> samples; 376 }; 377 Vector<Batch> mBatches; 378 379 // Touch state per device and source, only for sources of class pointer. 380 struct History { 381 nsecs_t eventTime; 382 BitSet32 idBits; 383 int32_t idToIndex[MAX_POINTER_ID + 1]; 384 PointerCoords pointers[MAX_POINTERS]; 385 initializeFromHistory386 void initializeFrom(const InputMessage& msg) { 387 eventTime = msg.body.motion.eventTime; 388 idBits.clear(); 389 for (uint32_t i = 0; i < msg.body.motion.pointerCount; i++) { 390 uint32_t id = msg.body.motion.pointers[i].properties.id; 391 idBits.markBit(id); 392 idToIndex[id] = i; 393 pointers[i].copyFrom(msg.body.motion.pointers[i].coords); 394 } 395 } 396 getPointerByIdHistory397 const PointerCoords& getPointerById(uint32_t id) const { 398 return pointers[idToIndex[id]]; 399 } 400 hasPointerIdHistory401 bool hasPointerId(uint32_t id) const { 402 return idBits.hasBit(id); 403 } 404 }; 405 struct TouchState { 406 int32_t deviceId; 407 int32_t source; 408 size_t historyCurrent; 409 size_t historySize; 410 History history[2]; 411 History lastResample; 412 initializeTouchState413 void initialize(int32_t deviceId, int32_t source) { 414 this->deviceId = deviceId; 415 this->source = source; 416 historyCurrent = 0; 417 historySize = 0; 418 lastResample.eventTime = 0; 419 lastResample.idBits.clear(); 420 } 421 addHistoryTouchState422 void addHistory(const InputMessage& msg) { 423 historyCurrent ^= 1; 424 if (historySize < 2) { 425 historySize += 1; 426 } 427 history[historyCurrent].initializeFrom(msg); 428 } 429 getHistoryTouchState430 const History* getHistory(size_t index) const { 431 return &history[(historyCurrent + index) & 1]; 432 } 433 recentCoordinatesAreIdenticalTouchState434 bool recentCoordinatesAreIdentical(uint32_t id) const { 435 // Return true if the two most recently received "raw" coordinates are identical 436 if (historySize < 2) { 437 return false; 438 } 439 if (!getHistory(0)->hasPointerId(id) || !getHistory(1)->hasPointerId(id)) { 440 return false; 441 } 442 float currentX = getHistory(0)->getPointerById(id).getX(); 443 float currentY = getHistory(0)->getPointerById(id).getY(); 444 float previousX = getHistory(1)->getPointerById(id).getX(); 445 float previousY = getHistory(1)->getPointerById(id).getY(); 446 if (currentX == previousX && currentY == previousY) { 447 return true; 448 } 449 return false; 450 } 451 }; 452 Vector<TouchState> mTouchStates; 453 454 // Chain of batched sequence numbers. When multiple input messages are combined into 455 // a batch, we append a record here that associates the last sequence number in the 456 // batch with the previous one. When the finished signal is sent, we traverse the 457 // chain to individually finish all input messages that were part of the batch. 458 struct SeqChain { 459 uint32_t seq; // sequence number of batched input message 460 uint32_t chain; // sequence number of previous batched input message 461 }; 462 Vector<SeqChain> mSeqChains; 463 464 status_t consumeBatch(InputEventFactoryInterface* factory, 465 nsecs_t frameTime, uint32_t* outSeq, InputEvent** outEvent, int32_t* displayId); 466 status_t consumeSamples(InputEventFactoryInterface* factory, 467 Batch& batch, size_t count, uint32_t* outSeq, InputEvent** outEvent, 468 int32_t* displayId); 469 470 void updateTouchState(InputMessage& msg); 471 bool rewriteMessage(const TouchState& state, InputMessage& msg); 472 void resampleTouchState(nsecs_t frameTime, MotionEvent* event, 473 const InputMessage *next); 474 475 ssize_t findBatch(int32_t deviceId, int32_t source) const; 476 ssize_t findTouchState(int32_t deviceId, int32_t source) const; 477 478 status_t sendUnchainedFinishedSignal(uint32_t seq, bool handled); 479 480 static void initializeKeyEvent(KeyEvent* event, const InputMessage* msg); 481 static void initializeMotionEvent(MotionEvent* event, const InputMessage* msg); 482 static void addSample(MotionEvent* event, const InputMessage* msg); 483 static bool canAddSample(const Batch& batch, const InputMessage* msg); 484 static ssize_t findSampleNoLaterThan(const Batch& batch, nsecs_t time); 485 static bool shouldResampleTool(int32_t toolType); 486 487 static bool isTouchResamplingEnabled(); 488 }; 489 490 } // namespace android 491 492 #endif // _LIBINPUT_INPUT_TRANSPORT_H 493