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