Battery Status API: add UMA logging for Linux.
[chromium-blink-merge.git] / content / browser / renderer_host / input / touch_event_queue.cc
blob946dd4283a8ce02f4df76124ac15a66da991bb1f
1 // Copyright 2013 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "content/browser/renderer_host/input/touch_event_queue.h"
7 #include "base/auto_reset.h"
8 #include "base/debug/trace_event.h"
9 #include "base/stl_util.h"
10 #include "content/browser/renderer_host/input/timeout_monitor.h"
11 #include "content/common/input/web_touch_event_traits.h"
12 #include "ui/gfx/geometry/point_f.h"
14 using blink::WebInputEvent;
15 using blink::WebTouchEvent;
16 using blink::WebTouchPoint;
17 using ui::LatencyInfo;
19 namespace content {
20 namespace {
22 // Time interval at which touchmove events will be forwarded to the client while
23 // scrolling is active and possible.
24 const double kAsyncTouchMoveIntervalSec = .2;
26 // A slop region just larger than that used by many web applications. When
27 // touchmove's are being sent asynchronously, movement outside this region will
28 // trigger an immediate async touchmove to cancel potential tap-related logic.
29 const double kApplicationSlopRegionLengthDipsSqared = 15. * 15.;
31 // Using a small epsilon when comparing slop distances allows pixel perfect
32 // slop determination when using fractional DIP coordinates (assuming the slop
33 // region and DPI scale are reasonably proportioned).
34 const float kSlopEpsilon = .05f;
36 TouchEventWithLatencyInfo ObtainCancelEventForTouchEvent(
37 const TouchEventWithLatencyInfo& event_to_cancel) {
38 TouchEventWithLatencyInfo event = event_to_cancel;
39 WebTouchEventTraits::ResetTypeAndTouchStates(
40 WebInputEvent::TouchCancel,
41 // TODO(rbyers): Shouldn't we use a fresh timestamp?
42 event.event.timeStampSeconds,
43 &event.event);
44 return event;
47 bool ShouldTouchTriggerTimeout(const WebTouchEvent& event) {
48 return (event.type == WebInputEvent::TouchStart ||
49 event.type == WebInputEvent::TouchMove) &&
50 !WebInputEventTraits::IgnoresAckDisposition(event);
53 bool OutsideApplicationSlopRegion(const WebTouchEvent& event,
54 const gfx::PointF& anchor) {
55 return (gfx::PointF(event.touches[0].position) - anchor).LengthSquared() >
56 kApplicationSlopRegionLengthDipsSqared;
59 } // namespace
62 // Cancels a touch sequence if a touchstart or touchmove ack response is
63 // sufficiently delayed.
64 class TouchEventQueue::TouchTimeoutHandler {
65 public:
66 TouchTimeoutHandler(TouchEventQueue* touch_queue,
67 base::TimeDelta timeout_delay)
68 : touch_queue_(touch_queue),
69 timeout_delay_(timeout_delay),
70 pending_ack_state_(PENDING_ACK_NONE),
71 timeout_monitor_(base::Bind(&TouchTimeoutHandler::OnTimeOut,
72 base::Unretained(this))) {
73 DCHECK(timeout_delay != base::TimeDelta());
76 ~TouchTimeoutHandler() {}
78 void Start(const TouchEventWithLatencyInfo& event) {
79 DCHECK_EQ(pending_ack_state_, PENDING_ACK_NONE);
80 DCHECK(ShouldTouchTriggerTimeout(event.event));
81 timeout_event_ = event;
82 timeout_monitor_.Restart(timeout_delay_);
85 bool ConfirmTouchEvent(InputEventAckState ack_result) {
86 switch (pending_ack_state_) {
87 case PENDING_ACK_NONE:
88 timeout_monitor_.Stop();
89 return false;
90 case PENDING_ACK_ORIGINAL_EVENT:
91 if (AckedTimeoutEventRequiresCancel(ack_result)) {
92 SetPendingAckState(PENDING_ACK_CANCEL_EVENT);
93 TouchEventWithLatencyInfo cancel_event =
94 ObtainCancelEventForTouchEvent(timeout_event_);
95 touch_queue_->SendTouchEventImmediately(cancel_event);
96 } else {
97 SetPendingAckState(PENDING_ACK_NONE);
98 touch_queue_->UpdateTouchAckStates(timeout_event_.event, ack_result);
100 return true;
101 case PENDING_ACK_CANCEL_EVENT:
102 SetPendingAckState(PENDING_ACK_NONE);
103 return true;
105 return false;
108 bool FilterEvent(const WebTouchEvent& event) {
109 return HasTimeoutEvent();
112 bool IsTimeoutTimerRunning() const {
113 return timeout_monitor_.IsRunning();
116 void Reset() {
117 pending_ack_state_ = PENDING_ACK_NONE;
118 timeout_monitor_.Stop();
121 void set_timeout_delay(base::TimeDelta timeout_delay) {
122 timeout_delay_ = timeout_delay;
125 private:
126 enum PendingAckState {
127 PENDING_ACK_NONE,
128 PENDING_ACK_ORIGINAL_EVENT,
129 PENDING_ACK_CANCEL_EVENT,
132 void OnTimeOut() {
133 SetPendingAckState(PENDING_ACK_ORIGINAL_EVENT);
134 touch_queue_->FlushQueue();
137 // Skip a cancel event if the timed-out event had no consumer and was the
138 // initial event in the gesture.
139 bool AckedTimeoutEventRequiresCancel(InputEventAckState ack_result) const {
140 DCHECK(HasTimeoutEvent());
141 if (ack_result != INPUT_EVENT_ACK_STATE_NO_CONSUMER_EXISTS)
142 return true;
143 return !WebTouchEventTraits::IsTouchSequenceStart(timeout_event_.event);
146 void SetPendingAckState(PendingAckState new_pending_ack_state) {
147 DCHECK_NE(pending_ack_state_, new_pending_ack_state);
148 switch (new_pending_ack_state) {
149 case PENDING_ACK_ORIGINAL_EVENT:
150 DCHECK_EQ(pending_ack_state_, PENDING_ACK_NONE);
151 TRACE_EVENT_ASYNC_BEGIN0("input", "TouchEventTimeout", this);
152 break;
153 case PENDING_ACK_CANCEL_EVENT:
154 DCHECK_EQ(pending_ack_state_, PENDING_ACK_ORIGINAL_EVENT);
155 DCHECK(!timeout_monitor_.IsRunning());
156 DCHECK(touch_queue_->empty());
157 TRACE_EVENT_ASYNC_STEP_INTO0(
158 "input", "TouchEventTimeout", this, "CancelEvent");
159 break;
160 case PENDING_ACK_NONE:
161 DCHECK(!timeout_monitor_.IsRunning());
162 DCHECK(touch_queue_->empty());
163 TRACE_EVENT_ASYNC_END0("input", "TouchEventTimeout", this);
164 break;
166 pending_ack_state_ = new_pending_ack_state;
169 bool HasTimeoutEvent() const {
170 return pending_ack_state_ != PENDING_ACK_NONE;
174 TouchEventQueue* touch_queue_;
176 // How long to wait on a touch ack before cancelling the touch sequence.
177 base::TimeDelta timeout_delay_;
179 // The touch event source for which we expect the next ack.
180 PendingAckState pending_ack_state_;
182 // The event for which the ack timeout is triggered.
183 TouchEventWithLatencyInfo timeout_event_;
185 // Provides timeout-based callback behavior.
186 TimeoutMonitor timeout_monitor_;
189 // Provides touchmove slop suppression for a single touch that remains within
190 // a given slop region, unless the touchstart is preventDefault'ed.
191 // TODO(jdduke): Use a flag bundled with each TouchEvent declaring whether it
192 // has exceeded the slop region, removing duplicated slop determination logic.
193 class TouchEventQueue::TouchMoveSlopSuppressor {
194 public:
195 TouchMoveSlopSuppressor(double slop_suppression_length_dips)
196 : slop_suppression_length_dips_squared_(0),
197 suppressing_touchmoves_(false) {
198 if (slop_suppression_length_dips) {
199 slop_suppression_length_dips += kSlopEpsilon;
200 slop_suppression_length_dips_squared_ =
201 slop_suppression_length_dips * slop_suppression_length_dips;
205 bool FilterEvent(const WebTouchEvent& event) {
206 if (WebTouchEventTraits::IsTouchSequenceStart(event)) {
207 touch_sequence_start_position_ =
208 gfx::PointF(event.touches[0].position);
209 suppressing_touchmoves_ = slop_suppression_length_dips_squared_ != 0;
212 if (event.type == WebInputEvent::TouchEnd ||
213 event.type == WebInputEvent::TouchCancel)
214 suppressing_touchmoves_ = false;
216 if (event.type != WebInputEvent::TouchMove)
217 return false;
219 if (suppressing_touchmoves_) {
220 // Movement with a secondary pointer should terminate suppression.
221 if (event.touchesLength > 1) {
222 suppressing_touchmoves_ = false;
223 } else if (event.touchesLength == 1) {
224 // Movement outside of the slop region should terminate suppression.
225 gfx::PointF position(event.touches[0].position);
226 if ((position - touch_sequence_start_position_).LengthSquared() >
227 slop_suppression_length_dips_squared_)
228 suppressing_touchmoves_ = false;
231 return suppressing_touchmoves_;
234 void ConfirmTouchEvent(InputEventAckState ack_result) {
235 if (ack_result == INPUT_EVENT_ACK_STATE_CONSUMED)
236 suppressing_touchmoves_ = false;
239 bool suppressing_touchmoves() const { return suppressing_touchmoves_; }
241 private:
242 double slop_suppression_length_dips_squared_;
243 gfx::PointF touch_sequence_start_position_;
244 bool suppressing_touchmoves_;
246 DISALLOW_COPY_AND_ASSIGN(TouchMoveSlopSuppressor);
249 // This class represents a single coalesced touch event. However, it also keeps
250 // track of all the original touch-events that were coalesced into a single
251 // event. The coalesced event is forwarded to the renderer, while the original
252 // touch-events are sent to the Client (on ACK for the coalesced event) so that
253 // the Client receives the event with their original timestamp.
254 class CoalescedWebTouchEvent {
255 public:
256 // Events for which |async| is true will not be ack'ed to the client after the
257 // corresponding ack is received following dispatch.
258 CoalescedWebTouchEvent(const TouchEventWithLatencyInfo& event, bool async)
259 : coalesced_event_(event) {
260 if (async)
261 coalesced_event_.event.cancelable = false;
262 else
263 events_to_ack_.push_back(event);
265 TRACE_EVENT_ASYNC_BEGIN0("input", "TouchEventQueue::QueueEvent", this);
268 ~CoalescedWebTouchEvent() {
269 TRACE_EVENT_ASYNC_END0("input", "TouchEventQueue::QueueEvent", this);
272 // Coalesces the event with the existing event if possible. Returns whether
273 // the event was coalesced.
274 bool CoalesceEventIfPossible(
275 const TouchEventWithLatencyInfo& event_with_latency) {
276 if (!WillDispatchAckToClient())
277 return false;
279 if (!coalesced_event_.CanCoalesceWith(event_with_latency))
280 return false;
282 TRACE_EVENT_INSTANT0(
283 "input", "TouchEventQueue::MoveCoalesced", TRACE_EVENT_SCOPE_THREAD);
284 coalesced_event_.CoalesceWith(event_with_latency);
285 events_to_ack_.push_back(event_with_latency);
286 return true;
289 void UpdateLatencyInfoForAck(const ui::LatencyInfo& renderer_latency_info) {
290 if (!WillDispatchAckToClient())
291 return;
293 for (WebTouchEventWithLatencyList::iterator iter = events_to_ack_.begin(),
294 end = events_to_ack_.end();
295 iter != end;
296 ++iter) {
297 iter->latency.AddNewLatencyFrom(renderer_latency_info);
301 void DispatchAckToClient(InputEventAckState ack_result,
302 TouchEventQueueClient* client) {
303 DCHECK(client);
304 if (!WillDispatchAckToClient())
305 return;
307 for (WebTouchEventWithLatencyList::const_iterator
308 iter = events_to_ack_.begin(),
309 end = events_to_ack_.end();
310 iter != end;
311 ++iter) {
312 client->OnTouchEventAck(*iter, ack_result);
316 const TouchEventWithLatencyInfo& coalesced_event() const {
317 return coalesced_event_;
320 private:
321 bool WillDispatchAckToClient() const { return !events_to_ack_.empty(); }
323 // This is the event that is forwarded to the renderer.
324 TouchEventWithLatencyInfo coalesced_event_;
326 // This is the list of the original events that were coalesced, each requiring
327 // future ack dispatch to the client.
328 typedef std::vector<TouchEventWithLatencyInfo> WebTouchEventWithLatencyList;
329 WebTouchEventWithLatencyList events_to_ack_;
331 DISALLOW_COPY_AND_ASSIGN(CoalescedWebTouchEvent);
334 TouchEventQueue::Config::Config()
335 : touchmove_slop_suppression_length_dips(0),
336 touch_scrolling_mode(TOUCH_SCROLLING_MODE_DEFAULT),
337 touch_ack_timeout_delay(base::TimeDelta::FromMilliseconds(200)),
338 touch_ack_timeout_supported(false) {
341 TouchEventQueue::TouchEventQueue(TouchEventQueueClient* client,
342 const Config& config)
343 : client_(client),
344 dispatching_touch_ack_(NULL),
345 dispatching_touch_(false),
346 touch_filtering_state_(TOUCH_FILTERING_STATE_DEFAULT),
347 ack_timeout_enabled_(config.touch_ack_timeout_supported),
348 touchmove_slop_suppressor_(new TouchMoveSlopSuppressor(
349 config.touchmove_slop_suppression_length_dips)),
350 send_touch_events_async_(false),
351 needs_async_touchmove_for_outer_slop_region_(false),
352 last_sent_touch_timestamp_sec_(0),
353 touch_scrolling_mode_(config.touch_scrolling_mode) {
354 DCHECK(client);
355 if (ack_timeout_enabled_) {
356 timeout_handler_.reset(
357 new TouchTimeoutHandler(this, config.touch_ack_timeout_delay));
361 TouchEventQueue::~TouchEventQueue() {
362 if (!touch_queue_.empty())
363 STLDeleteElements(&touch_queue_);
366 void TouchEventQueue::QueueEvent(const TouchEventWithLatencyInfo& event) {
367 TRACE_EVENT0("input", "TouchEventQueue::QueueEvent");
369 // If the queueing of |event| was triggered by an ack dispatch, defer
370 // processing the event until the dispatch has finished.
371 if (touch_queue_.empty() && !dispatching_touch_ack_) {
372 // Optimization of the case without touch handlers. Removing this path
373 // yields identical results, but this avoids unnecessary allocations.
374 PreFilterResult filter_result = FilterBeforeForwarding(event.event);
375 if (filter_result != FORWARD_TO_RENDERER) {
376 client_->OnTouchEventAck(event,
377 filter_result == ACK_WITH_NO_CONSUMER_EXISTS
378 ? INPUT_EVENT_ACK_STATE_NO_CONSUMER_EXISTS
379 : INPUT_EVENT_ACK_STATE_NOT_CONSUMED);
380 return;
383 // There is no touch event in the queue. Forward it to the renderer
384 // immediately.
385 touch_queue_.push_back(new CoalescedWebTouchEvent(event, false));
386 ForwardNextEventToRenderer();
387 return;
390 // If the last queued touch-event was a touch-move, and the current event is
391 // also a touch-move, then the events can be coalesced into a single event.
392 if (touch_queue_.size() > 1) {
393 CoalescedWebTouchEvent* last_event = touch_queue_.back();
394 if (last_event->CoalesceEventIfPossible(event))
395 return;
397 touch_queue_.push_back(new CoalescedWebTouchEvent(event, false));
400 void TouchEventQueue::ProcessTouchAck(InputEventAckState ack_result,
401 const LatencyInfo& latency_info) {
402 TRACE_EVENT0("input", "TouchEventQueue::ProcessTouchAck");
404 DCHECK(!dispatching_touch_ack_);
405 dispatching_touch_ = false;
407 if (timeout_handler_ && timeout_handler_->ConfirmTouchEvent(ack_result))
408 return;
410 touchmove_slop_suppressor_->ConfirmTouchEvent(ack_result);
412 if (touch_queue_.empty())
413 return;
415 if (ack_result == INPUT_EVENT_ACK_STATE_CONSUMED &&
416 touch_filtering_state_ == FORWARD_TOUCHES_UNTIL_TIMEOUT) {
417 touch_filtering_state_ = FORWARD_ALL_TOUCHES;
420 PopTouchEventToClient(ack_result, latency_info);
421 TryForwardNextEventToRenderer();
424 void TouchEventQueue::TryForwardNextEventToRenderer() {
425 DCHECK(!dispatching_touch_ack_);
426 // If there are queued touch events, then try to forward them to the renderer
427 // immediately, or ACK the events back to the client if appropriate.
428 while (!touch_queue_.empty()) {
429 PreFilterResult filter_result =
430 FilterBeforeForwarding(touch_queue_.front()->coalesced_event().event);
431 switch (filter_result) {
432 case ACK_WITH_NO_CONSUMER_EXISTS:
433 PopTouchEventToClient(INPUT_EVENT_ACK_STATE_NO_CONSUMER_EXISTS);
434 break;
435 case ACK_WITH_NOT_CONSUMED:
436 PopTouchEventToClient(INPUT_EVENT_ACK_STATE_NOT_CONSUMED);
437 break;
438 case FORWARD_TO_RENDERER:
439 ForwardNextEventToRenderer();
440 return;
445 void TouchEventQueue::ForwardNextEventToRenderer() {
446 TRACE_EVENT0("input", "TouchEventQueue::ForwardNextEventToRenderer");
448 DCHECK(!empty());
449 DCHECK(!dispatching_touch_);
450 DCHECK_NE(touch_filtering_state_, DROP_ALL_TOUCHES);
451 TouchEventWithLatencyInfo touch = touch_queue_.front()->coalesced_event();
453 if (WebTouchEventTraits::IsTouchSequenceStart(touch.event)) {
454 touch_filtering_state_ =
455 ack_timeout_enabled_ ? FORWARD_TOUCHES_UNTIL_TIMEOUT
456 : FORWARD_ALL_TOUCHES;
457 touch_ack_states_.clear();
458 send_touch_events_async_ = false;
459 pending_async_touchmove_.reset();
460 touch_sequence_start_position_ =
461 gfx::PointF(touch.event.touches[0].position);
464 if (send_touch_events_async_ &&
465 touch.event.type == WebInputEvent::TouchMove) {
466 // Throttling touchmove's in a continuous touchmove stream while scrolling
467 // reduces the risk of jank. However, it's still important that the web
468 // application be sent touches at key points in the gesture stream,
469 // e.g., when the application slop region is exceeded or touchmove
470 // coalescing fails because of different modifiers.
471 const bool send_touchmove_now =
472 size() > 1 ||
473 (touch.event.timeStampSeconds >=
474 last_sent_touch_timestamp_sec_ + kAsyncTouchMoveIntervalSec) ||
475 (needs_async_touchmove_for_outer_slop_region_ &&
476 OutsideApplicationSlopRegion(touch.event,
477 touch_sequence_start_position_)) ||
478 (pending_async_touchmove_ &&
479 !pending_async_touchmove_->CanCoalesceWith(touch));
481 if (!send_touchmove_now) {
482 if (!pending_async_touchmove_) {
483 pending_async_touchmove_.reset(new TouchEventWithLatencyInfo(touch));
484 } else {
485 DCHECK(pending_async_touchmove_->CanCoalesceWith(touch));
486 pending_async_touchmove_->CoalesceWith(touch);
488 DCHECK_EQ(1U, size());
489 PopTouchEventToClient(INPUT_EVENT_ACK_STATE_NOT_CONSUMED);
490 // It's possible (though unlikely) that ack'ing the current touch will
491 // trigger the queueing of another touch event (e.g., a touchcancel). As
492 // forwarding of the queued event will be deferred while the ack is being
493 // dispatched (see |OnTouchEvent()|), try forwarding it now.
494 TryForwardNextEventToRenderer();
495 return;
499 last_sent_touch_timestamp_sec_ = touch.event.timeStampSeconds;
501 // Flush any pending async touch move. If it can be combined with the current
502 // (touchmove) event, great, otherwise send it immediately but separately. Its
503 // ack will trigger forwarding of the original |touch| event.
504 if (pending_async_touchmove_) {
505 if (pending_async_touchmove_->CanCoalesceWith(touch)) {
506 pending_async_touchmove_->CoalesceWith(touch);
507 pending_async_touchmove_->event.cancelable = !send_touch_events_async_;
508 touch = *pending_async_touchmove_.Pass();
509 } else {
510 scoped_ptr<TouchEventWithLatencyInfo> async_move =
511 pending_async_touchmove_.Pass();
512 async_move->event.cancelable = false;
513 touch_queue_.push_front(new CoalescedWebTouchEvent(*async_move, true));
514 SendTouchEventImmediately(*async_move);
515 return;
519 // Note: Marking touchstart events as not-cancelable prevents them from
520 // blocking subsequent gestures, but it may not be the best long term solution
521 // for tracking touch point dispatch.
522 if (send_touch_events_async_)
523 touch.event.cancelable = false;
525 // A synchronous ack will reset |dispatching_touch_|, in which case
526 // the touch timeout should not be started.
527 base::AutoReset<bool> dispatching_touch(&dispatching_touch_, true);
528 SendTouchEventImmediately(touch);
529 if (dispatching_touch_ &&
530 touch_filtering_state_ == FORWARD_TOUCHES_UNTIL_TIMEOUT &&
531 ShouldTouchTriggerTimeout(touch.event)) {
532 DCHECK(timeout_handler_);
533 timeout_handler_->Start(touch);
537 void TouchEventQueue::OnGestureScrollEvent(
538 const GestureEventWithLatencyInfo& gesture_event) {
539 if (gesture_event.event.type == blink::WebInputEvent::GestureScrollBegin) {
540 if (touch_filtering_state_ != DROP_ALL_TOUCHES &&
541 touch_filtering_state_ != DROP_TOUCHES_IN_SEQUENCE) {
542 DCHECK(!touchmove_slop_suppressor_->suppressing_touchmoves())
543 << "The renderer should be offered a touchmove before scrolling "
544 "begins";
547 if (touch_scrolling_mode_ == TOUCH_SCROLLING_MODE_ASYNC_TOUCHMOVE &&
548 touch_filtering_state_ != DROP_ALL_TOUCHES &&
549 touch_filtering_state_ != DROP_TOUCHES_IN_SEQUENCE &&
550 (touch_ack_states_.empty() ||
551 AllTouchAckStatesHaveState(
552 INPUT_EVENT_ACK_STATE_NO_CONSUMER_EXISTS))) {
553 // If no touch points have a consumer, prevent all subsequent touch events
554 // received during the scroll from reaching the renderer. This ensures
555 // that the first touchstart the renderer sees in any given sequence can
556 // always be preventDefault'ed (cancelable == true).
557 // TODO(jdduke): Revisit if touchstarts during scroll are made cancelable.
558 touch_filtering_state_ = DROP_TOUCHES_IN_SEQUENCE;
561 if (touch_scrolling_mode_ == TOUCH_SCROLLING_MODE_ASYNC_TOUCHMOVE) {
562 needs_async_touchmove_for_outer_slop_region_ = true;
563 pending_async_touchmove_.reset();
566 return;
569 if (gesture_event.event.type != blink::WebInputEvent::GestureScrollUpdate)
570 return;
572 if (touch_scrolling_mode_ == TOUCH_SCROLLING_MODE_ASYNC_TOUCHMOVE)
573 send_touch_events_async_ = true;
575 if (touch_scrolling_mode_ != TOUCH_SCROLLING_MODE_TOUCHCANCEL)
576 return;
578 // We assume that scroll events are generated synchronously from
579 // dispatching a touch event ack. This allows us to generate a synthetic
580 // cancel event that has the same touch ids as the touch event that
581 // is being acked. Otherwise, we don't perform the touch-cancel optimization.
582 if (!dispatching_touch_ack_)
583 return;
585 if (touch_filtering_state_ == DROP_TOUCHES_IN_SEQUENCE)
586 return;
588 touch_filtering_state_ = DROP_TOUCHES_IN_SEQUENCE;
590 // Fake a TouchCancel to cancel the touch points of the touch event
591 // that is currently being acked.
592 // Note: |dispatching_touch_ack_| is non-null when we reach here, meaning we
593 // are in the scope of PopTouchEventToClient() and that no touch event
594 // in the queue is waiting for ack from renderer. So we can just insert
595 // the touch cancel at the beginning of the queue.
596 touch_queue_.push_front(new CoalescedWebTouchEvent(
597 ObtainCancelEventForTouchEvent(
598 dispatching_touch_ack_->coalesced_event()), true));
601 void TouchEventQueue::OnGestureEventAck(
602 const GestureEventWithLatencyInfo& event,
603 InputEventAckState ack_result) {
604 if (touch_scrolling_mode_ != TOUCH_SCROLLING_MODE_ASYNC_TOUCHMOVE)
605 return;
607 if (event.event.type != blink::WebInputEvent::GestureScrollUpdate)
608 return;
610 // Throttle sending touchmove events as long as the scroll events are handled.
611 // Note that there's no guarantee that this ACK is for the most recent
612 // gesture event (or even part of the current sequence). Worst case, the
613 // delay in updating the absorption state will result in minor UI glitches.
614 // A valid |pending_async_touchmove_| will be flushed when the next event is
615 // forwarded.
616 send_touch_events_async_ = (ack_result == INPUT_EVENT_ACK_STATE_CONSUMED);
617 if (!send_touch_events_async_)
618 needs_async_touchmove_for_outer_slop_region_ = false;
621 void TouchEventQueue::OnHasTouchEventHandlers(bool has_handlers) {
622 DCHECK(!dispatching_touch_ack_);
623 DCHECK(!dispatching_touch_);
625 if (has_handlers) {
626 if (touch_filtering_state_ == DROP_ALL_TOUCHES) {
627 // If no touch handler was previously registered, ensure that we don't
628 // send a partial touch sequence to the renderer.
629 DCHECK(touch_queue_.empty());
630 touch_filtering_state_ = DROP_TOUCHES_IN_SEQUENCE;
632 } else {
633 // TODO(jdduke): Synthesize a TouchCancel if necessary to update Blink touch
634 // state tracking and/or touch-action filtering (e.g., if the touch handler
635 // was removed mid-sequence), crbug.com/375940.
636 touch_filtering_state_ = DROP_ALL_TOUCHES;
637 pending_async_touchmove_.reset();
638 if (timeout_handler_)
639 timeout_handler_->Reset();
640 if (!touch_queue_.empty())
641 ProcessTouchAck(INPUT_EVENT_ACK_STATE_NO_CONSUMER_EXISTS, LatencyInfo());
642 // As there is no touch handler, ack'ing the event should flush the queue.
643 DCHECK(touch_queue_.empty());
647 bool TouchEventQueue::IsPendingAckTouchStart() const {
648 DCHECK(!dispatching_touch_ack_);
649 if (touch_queue_.empty())
650 return false;
652 const blink::WebTouchEvent& event =
653 touch_queue_.front()->coalesced_event().event;
654 return (event.type == WebInputEvent::TouchStart);
657 void TouchEventQueue::SetAckTimeoutEnabled(bool enabled) {
658 // The timeout handler is valid only if explicitly supported in the config.
659 if (!timeout_handler_)
660 return;
662 if (ack_timeout_enabled_ == enabled)
663 return;
665 ack_timeout_enabled_ = enabled;
667 if (enabled)
668 return;
670 if (touch_filtering_state_ == FORWARD_TOUCHES_UNTIL_TIMEOUT)
671 touch_filtering_state_ = FORWARD_ALL_TOUCHES;
672 // Only reset the |timeout_handler_| if the timer is running and has not yet
673 // timed out. This ensures that an already timed out sequence is properly
674 // flushed by the handler.
675 if (timeout_handler_ && timeout_handler_->IsTimeoutTimerRunning())
676 timeout_handler_->Reset();
679 bool TouchEventQueue::HasPendingAsyncTouchMoveForTesting() const {
680 return pending_async_touchmove_;
683 bool TouchEventQueue::IsTimeoutRunningForTesting() const {
684 return timeout_handler_ && timeout_handler_->IsTimeoutTimerRunning();
687 const TouchEventWithLatencyInfo&
688 TouchEventQueue::GetLatestEventForTesting() const {
689 return touch_queue_.back()->coalesced_event();
692 void TouchEventQueue::FlushQueue() {
693 DCHECK(!dispatching_touch_ack_);
694 DCHECK(!dispatching_touch_);
695 pending_async_touchmove_.reset();
696 if (touch_filtering_state_ != DROP_ALL_TOUCHES)
697 touch_filtering_state_ = DROP_TOUCHES_IN_SEQUENCE;
698 while (!touch_queue_.empty())
699 PopTouchEventToClient(INPUT_EVENT_ACK_STATE_NO_CONSUMER_EXISTS);
702 void TouchEventQueue::PopTouchEventToClient(InputEventAckState ack_result) {
703 AckTouchEventToClient(ack_result, PopTouchEvent());
706 void TouchEventQueue::PopTouchEventToClient(
707 InputEventAckState ack_result,
708 const LatencyInfo& renderer_latency_info) {
709 scoped_ptr<CoalescedWebTouchEvent> acked_event = PopTouchEvent();
710 acked_event->UpdateLatencyInfoForAck(renderer_latency_info);
711 AckTouchEventToClient(ack_result, acked_event.Pass());
714 void TouchEventQueue::AckTouchEventToClient(
715 InputEventAckState ack_result,
716 scoped_ptr<CoalescedWebTouchEvent> acked_event) {
717 DCHECK(acked_event);
718 DCHECK(!dispatching_touch_ack_);
719 UpdateTouchAckStates(acked_event->coalesced_event().event, ack_result);
721 // Note that acking the touch-event may result in multiple gestures being sent
722 // to the renderer, or touch-events being queued.
723 base::AutoReset<const CoalescedWebTouchEvent*> dispatching_touch_ack(
724 &dispatching_touch_ack_, acked_event.get());
725 acked_event->DispatchAckToClient(ack_result, client_);
728 scoped_ptr<CoalescedWebTouchEvent> TouchEventQueue::PopTouchEvent() {
729 DCHECK(!touch_queue_.empty());
730 scoped_ptr<CoalescedWebTouchEvent> event(touch_queue_.front());
731 touch_queue_.pop_front();
732 return event.Pass();
735 void TouchEventQueue::SendTouchEventImmediately(
736 const TouchEventWithLatencyInfo& touch) {
737 if (needs_async_touchmove_for_outer_slop_region_) {
738 // Any event other than a touchmove (e.g., touchcancel or secondary
739 // touchstart) after a scroll has started will interrupt the need to send a
740 // an outer slop-region exceeding touchmove.
741 if (touch.event.type != WebInputEvent::TouchMove ||
742 OutsideApplicationSlopRegion(touch.event,
743 touch_sequence_start_position_))
744 needs_async_touchmove_for_outer_slop_region_ = false;
747 client_->SendTouchEventImmediately(touch);
750 TouchEventQueue::PreFilterResult
751 TouchEventQueue::FilterBeforeForwarding(const WebTouchEvent& event) {
752 if (timeout_handler_ && timeout_handler_->FilterEvent(event))
753 return ACK_WITH_NO_CONSUMER_EXISTS;
755 if (touchmove_slop_suppressor_->FilterEvent(event))
756 return ACK_WITH_NOT_CONSUMED;
758 if (touch_filtering_state_ == DROP_ALL_TOUCHES)
759 return ACK_WITH_NO_CONSUMER_EXISTS;
761 if (touch_filtering_state_ == DROP_TOUCHES_IN_SEQUENCE &&
762 event.type != WebInputEvent::TouchCancel) {
763 if (WebTouchEventTraits::IsTouchSequenceStart(event))
764 return FORWARD_TO_RENDERER;
765 return ACK_WITH_NO_CONSUMER_EXISTS;
768 // Touch press events should always be forwarded to the renderer.
769 if (event.type == WebInputEvent::TouchStart)
770 return FORWARD_TO_RENDERER;
772 for (unsigned int i = 0; i < event.touchesLength; ++i) {
773 const WebTouchPoint& point = event.touches[i];
774 // If a point has been stationary, then don't take it into account.
775 if (point.state == WebTouchPoint::StateStationary)
776 continue;
778 if (touch_ack_states_.count(point.id) > 0) {
779 if (touch_ack_states_.find(point.id)->second !=
780 INPUT_EVENT_ACK_STATE_NO_CONSUMER_EXISTS)
781 return FORWARD_TO_RENDERER;
782 } else {
783 // If the ACK status of a point is unknown, then the event should be
784 // forwarded to the renderer.
785 return FORWARD_TO_RENDERER;
789 return ACK_WITH_NO_CONSUMER_EXISTS;
792 void TouchEventQueue::UpdateTouchAckStates(const WebTouchEvent& event,
793 InputEventAckState ack_result) {
794 // Update the ACK status for each touch point in the ACKed event.
795 if (event.type == WebInputEvent::TouchEnd ||
796 event.type == WebInputEvent::TouchCancel) {
797 // The points have been released. Erase the ACK states.
798 for (unsigned i = 0; i < event.touchesLength; ++i) {
799 const WebTouchPoint& point = event.touches[i];
800 if (point.state == WebTouchPoint::StateReleased ||
801 point.state == WebTouchPoint::StateCancelled)
802 touch_ack_states_.erase(point.id);
804 } else if (event.type == WebInputEvent::TouchStart) {
805 for (unsigned i = 0; i < event.touchesLength; ++i) {
806 const WebTouchPoint& point = event.touches[i];
807 if (point.state == WebTouchPoint::StatePressed)
808 touch_ack_states_[point.id] = ack_result;
813 bool TouchEventQueue::AllTouchAckStatesHaveState(
814 InputEventAckState ack_state) const {
815 if (touch_ack_states_.empty())
816 return false;
818 for (TouchPointAckStates::const_iterator iter = touch_ack_states_.begin(),
819 end = touch_ack_states_.end();
820 iter != end;
821 ++iter) {
822 if (iter->second != ack_state)
823 return false;
826 return true;
829 } // namespace content