Fix crash on app list start page contents not existing.
[chromium-blink-merge.git] / content / renderer / input / input_handler_proxy.cc
blobf9cc75b9a80aaa2b1e80d9d0bb0ac06501b1eacd
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/renderer/input/input_handler_proxy.h"
7 #include "base/auto_reset.h"
8 #include "base/command_line.h"
9 #include "base/logging.h"
10 #include "base/metrics/histogram.h"
11 #include "base/trace_event/trace_event.h"
12 #include "content/common/input/did_overscroll_params.h"
13 #include "content/common/input/web_input_event_traits.h"
14 #include "content/public/common/content_switches.h"
15 #include "content/renderer/input/input_handler_proxy_client.h"
16 #include "content/renderer/input/input_scroll_elasticity_controller.h"
17 #include "third_party/WebKit/public/platform/Platform.h"
18 #include "third_party/WebKit/public/web/WebInputEvent.h"
19 #include "ui/events/latency_info.h"
20 #include "ui/gfx/frame_time.h"
21 #include "ui/gfx/geometry/point_conversions.h"
23 using blink::WebFloatPoint;
24 using blink::WebFloatSize;
25 using blink::WebGestureEvent;
26 using blink::WebInputEvent;
27 using blink::WebMouseEvent;
28 using blink::WebMouseWheelEvent;
29 using blink::WebPoint;
30 using blink::WebTouchEvent;
31 using blink::WebTouchPoint;
33 namespace {
35 // Maximum time between a fling event's timestamp and the first |Animate| call
36 // for the fling curve to use the fling timestamp as the initial animation time.
37 // Two frames allows a minor delay between event creation and the first animate.
38 const double kMaxSecondsFromFlingTimestampToFirstAnimate = 2. / 60.;
40 // Threshold for determining whether a fling scroll delta should have caused the
41 // client to scroll.
42 const float kScrollEpsilon = 0.1f;
44 // Minimum fling velocity required for the active fling and new fling for the
45 // two to accumulate.
46 const double kMinBoostFlingSpeedSquare = 350. * 350.;
48 // Minimum velocity for the active touch scroll to preserve (boost) an active
49 // fling for which cancellation has been deferred.
50 const double kMinBoostTouchScrollSpeedSquare = 150 * 150.;
52 // Timeout window after which the active fling will be cancelled if no scrolls
53 // or flings of sufficient velocity relative to the current fling are received.
54 // The default value on Android native views is 40ms, but we use a slightly
55 // increased value to accomodate small IPC message delays.
56 const double kFlingBoostTimeoutDelaySeconds = 0.045;
58 gfx::Vector2dF ToClientScrollIncrement(const WebFloatSize& increment) {
59 return gfx::Vector2dF(-increment.width, -increment.height);
62 double InSecondsF(const base::TimeTicks& time) {
63 return (time - base::TimeTicks()).InSecondsF();
66 bool ShouldSuppressScrollForFlingBoosting(
67 const gfx::Vector2dF& current_fling_velocity,
68 const WebGestureEvent& scroll_update_event,
69 double time_since_last_boost_event) {
70 DCHECK_EQ(WebInputEvent::GestureScrollUpdate, scroll_update_event.type);
72 gfx::Vector2dF dx(scroll_update_event.data.scrollUpdate.deltaX,
73 scroll_update_event.data.scrollUpdate.deltaY);
74 if (gfx::DotProduct(current_fling_velocity, dx) <= 0)
75 return false;
77 if (time_since_last_boost_event < 0.001)
78 return true;
80 // TODO(jdduke): Use |scroll_update_event.data.scrollUpdate.velocity{X,Y}|.
81 // The scroll must be of sufficient velocity to maintain the active fling.
82 const gfx::Vector2dF scroll_velocity =
83 gfx::ScaleVector2d(dx, 1. / time_since_last_boost_event);
84 if (scroll_velocity.LengthSquared() < kMinBoostTouchScrollSpeedSquare)
85 return false;
87 return true;
90 bool ShouldBoostFling(const gfx::Vector2dF& current_fling_velocity,
91 const WebGestureEvent& fling_start_event) {
92 DCHECK_EQ(WebInputEvent::GestureFlingStart, fling_start_event.type);
94 gfx::Vector2dF new_fling_velocity(
95 fling_start_event.data.flingStart.velocityX,
96 fling_start_event.data.flingStart.velocityY);
98 if (gfx::DotProduct(current_fling_velocity, new_fling_velocity) <= 0)
99 return false;
101 if (current_fling_velocity.LengthSquared() < kMinBoostFlingSpeedSquare)
102 return false;
104 if (new_fling_velocity.LengthSquared() < kMinBoostFlingSpeedSquare)
105 return false;
107 return true;
110 WebGestureEvent ObtainGestureScrollBegin(const WebGestureEvent& event) {
111 WebGestureEvent scroll_begin_event = event;
112 scroll_begin_event.type = WebInputEvent::GestureScrollBegin;
113 scroll_begin_event.data.scrollBegin.deltaXHint = 0;
114 scroll_begin_event.data.scrollBegin.deltaYHint = 0;
115 return scroll_begin_event;
118 void ReportInputEventLatencyUma(const WebInputEvent& event,
119 const ui::LatencyInfo& latency_info) {
120 if (!(event.type == WebInputEvent::GestureScrollBegin ||
121 event.type == WebInputEvent::GestureScrollUpdate ||
122 event.type == WebInputEvent::GesturePinchBegin ||
123 event.type == WebInputEvent::GesturePinchUpdate ||
124 event.type == WebInputEvent::GestureFlingStart)) {
125 return;
128 ui::LatencyInfo::LatencyMap::const_iterator it =
129 latency_info.latency_components.find(std::make_pair(
130 ui::INPUT_EVENT_LATENCY_ORIGINAL_COMPONENT, 0));
132 if (it == latency_info.latency_components.end())
133 return;
135 base::TimeDelta delta = base::TimeTicks::Now() - it->second.event_time;
136 for (size_t i = 0; i < it->second.event_count; ++i) {
137 switch (event.type) {
138 case blink::WebInputEvent::GestureScrollBegin:
139 UMA_HISTOGRAM_CUSTOM_COUNTS(
140 "Event.Latency.RendererImpl.GestureScrollBegin",
141 delta.InMicroseconds(), 1, 1000000, 100);
142 break;
143 case blink::WebInputEvent::GestureScrollUpdate:
144 UMA_HISTOGRAM_CUSTOM_COUNTS(
145 // So named for historical reasons.
146 "Event.Latency.RendererImpl.GestureScroll2",
147 delta.InMicroseconds(), 1, 1000000, 100);
148 break;
149 case blink::WebInputEvent::GesturePinchBegin:
150 UMA_HISTOGRAM_CUSTOM_COUNTS(
151 "Event.Latency.RendererImpl.GesturePinchBegin",
152 delta.InMicroseconds(), 1, 1000000, 100);
153 break;
154 case blink::WebInputEvent::GesturePinchUpdate:
155 UMA_HISTOGRAM_CUSTOM_COUNTS(
156 "Event.Latency.RendererImpl.GesturePinchUpdate",
157 delta.InMicroseconds(), 1, 1000000, 100);
158 break;
159 case blink::WebInputEvent::GestureFlingStart:
160 UMA_HISTOGRAM_CUSTOM_COUNTS(
161 "Event.Latency.RendererImpl.GestureFlingStart",
162 delta.InMicroseconds(), 1, 1000000, 100);
163 break;
164 default:
165 NOTREACHED();
166 break;
171 } // namespace
173 namespace content {
175 InputHandlerProxy::InputHandlerProxy(cc::InputHandler* input_handler,
176 InputHandlerProxyClient* client)
177 : client_(client),
178 input_handler_(input_handler),
179 deferred_fling_cancel_time_seconds_(0),
180 #ifndef NDEBUG
181 expect_scroll_update_end_(false),
182 #endif
183 gesture_scroll_on_impl_thread_(false),
184 gesture_pinch_on_impl_thread_(false),
185 fling_may_be_active_on_main_thread_(false),
186 disallow_horizontal_fling_scroll_(false),
187 disallow_vertical_fling_scroll_(false),
188 has_fling_animation_started_(false),
189 uma_latency_reporting_enabled_(base::TimeTicks::IsHighResolution()) {
190 DCHECK(client);
191 input_handler_->BindToClient(this);
192 smooth_scroll_enabled_ = base::CommandLine::ForCurrentProcess()->HasSwitch(
193 switches::kEnableSmoothScrolling);
194 cc::ScrollElasticityHelper* scroll_elasticity_helper =
195 input_handler_->CreateScrollElasticityHelper();
196 if (scroll_elasticity_helper) {
197 scroll_elasticity_controller_.reset(
198 new InputScrollElasticityController(scroll_elasticity_helper));
202 InputHandlerProxy::~InputHandlerProxy() {}
204 void InputHandlerProxy::WillShutdown() {
205 scroll_elasticity_controller_.reset();
206 input_handler_ = NULL;
207 client_->WillShutdown();
210 InputHandlerProxy::EventDisposition
211 InputHandlerProxy::HandleInputEventWithLatencyInfo(
212 const WebInputEvent& event,
213 ui::LatencyInfo* latency_info) {
214 DCHECK(input_handler_);
216 if (uma_latency_reporting_enabled_)
217 ReportInputEventLatencyUma(event, *latency_info);
219 TRACE_EVENT_FLOW_STEP0("input,benchmark",
220 "LatencyInfo.Flow",
221 TRACE_ID_DONT_MANGLE(latency_info->trace_id),
222 "HandleInputEventImpl");
224 scoped_ptr<cc::SwapPromiseMonitor> latency_info_swap_promise_monitor =
225 input_handler_->CreateLatencyInfoSwapPromiseMonitor(latency_info);
226 InputHandlerProxy::EventDisposition disposition = HandleInputEvent(event);
227 return disposition;
230 InputHandlerProxy::EventDisposition InputHandlerProxy::HandleInputEvent(
231 const WebInputEvent& event) {
232 DCHECK(input_handler_);
233 TRACE_EVENT1("input,benchmark", "InputHandlerProxy::HandleInputEvent",
234 "type", WebInputEventTraits::GetName(event.type));
236 client_->DidReceiveInputEvent(event);
237 if (FilterInputEventForFlingBoosting(event))
238 return DID_HANDLE;
240 switch (event.type) {
241 case WebInputEvent::MouseWheel:
242 return HandleMouseWheel(static_cast<const WebMouseWheelEvent&>(event));
244 case WebInputEvent::GestureScrollBegin:
245 return HandleGestureScrollBegin(
246 static_cast<const WebGestureEvent&>(event));
248 case WebInputEvent::GestureScrollUpdate:
249 return HandleGestureScrollUpdate(
250 static_cast<const WebGestureEvent&>(event));
252 case WebInputEvent::GestureScrollEnd:
253 return HandleGestureScrollEnd(static_cast<const WebGestureEvent&>(event));
255 case WebInputEvent::GesturePinchBegin: {
256 DCHECK(!gesture_pinch_on_impl_thread_);
257 const WebGestureEvent& gesture_event =
258 static_cast<const WebGestureEvent&>(event);
259 if (gesture_event.sourceDevice == blink::WebGestureDeviceTouchpad &&
260 input_handler_->HaveWheelEventHandlersAt(
261 gfx::Point(gesture_event.x, gesture_event.y))) {
262 return DID_NOT_HANDLE;
263 } else {
264 input_handler_->PinchGestureBegin();
265 gesture_pinch_on_impl_thread_ = true;
266 return DID_HANDLE;
270 case WebInputEvent::GesturePinchEnd:
271 if (gesture_pinch_on_impl_thread_) {
272 gesture_pinch_on_impl_thread_ = false;
273 input_handler_->PinchGestureEnd();
274 return DID_HANDLE;
275 } else {
276 return DID_NOT_HANDLE;
279 case WebInputEvent::GesturePinchUpdate: {
280 if (gesture_pinch_on_impl_thread_) {
281 const WebGestureEvent& gesture_event =
282 static_cast<const WebGestureEvent&>(event);
283 input_handler_->PinchGestureUpdate(
284 gesture_event.data.pinchUpdate.scale,
285 gfx::Point(gesture_event.x, gesture_event.y));
286 return DID_HANDLE;
287 } else {
288 return DID_NOT_HANDLE;
292 case WebInputEvent::GestureFlingStart:
293 return HandleGestureFlingStart(
294 *static_cast<const WebGestureEvent*>(&event));
296 case WebInputEvent::GestureFlingCancel:
297 if (CancelCurrentFling())
298 return DID_HANDLE;
299 else if (!fling_may_be_active_on_main_thread_)
300 return DROP_EVENT;
301 return DID_NOT_HANDLE;
303 case WebInputEvent::TouchStart:
304 return HandleTouchStart(static_cast<const WebTouchEvent&>(event));
306 case WebInputEvent::MouseMove: {
307 const WebMouseEvent& mouse_event =
308 static_cast<const WebMouseEvent&>(event);
309 // TODO(tony): Ignore when mouse buttons are down?
310 // TODO(davemoore): This should never happen, but bug #326635 showed some
311 // surprising crashes.
312 CHECK(input_handler_);
313 input_handler_->MouseMoveAt(gfx::Point(mouse_event.x, mouse_event.y));
314 return DID_NOT_HANDLE;
317 default:
318 if (WebInputEvent::isKeyboardEventType(event.type)) {
319 // Only call |CancelCurrentFling()| if a fling was active, as it will
320 // otherwise disrupt an in-progress touch scroll.
321 if (fling_curve_)
322 CancelCurrentFling();
324 break;
327 return DID_NOT_HANDLE;
330 InputHandlerProxy::EventDisposition InputHandlerProxy::HandleMouseWheel(
331 const WebMouseWheelEvent& wheel_event) {
332 InputHandlerProxy::EventDisposition result = DID_NOT_HANDLE;
333 cc::InputHandlerScrollResult scroll_result;
335 if (wheel_event.scrollByPage) {
336 // TODO(jamesr): We don't properly handle scroll by page in the compositor
337 // thread, so punt it to the main thread. http://crbug.com/236639
338 result = DID_NOT_HANDLE;
339 } else if (!wheel_event.canScroll) {
340 // Wheel events with |canScroll| == false will not trigger scrolling,
341 // only event handlers. Forward to the main thread.
342 result = DID_NOT_HANDLE;
343 } else if (smooth_scroll_enabled_) {
344 cc::InputHandler::ScrollStatus scroll_status =
345 input_handler_->ScrollAnimated(
346 gfx::Point(wheel_event.x, wheel_event.y),
347 gfx::Vector2dF(-wheel_event.deltaX, -wheel_event.deltaY));
348 switch (scroll_status) {
349 case cc::InputHandler::SCROLL_STARTED:
350 result = DID_HANDLE;
351 break;
352 case cc::InputHandler::SCROLL_IGNORED:
353 result = DROP_EVENT;
354 default:
355 result = DID_NOT_HANDLE;
356 break;
358 } else {
359 cc::InputHandler::ScrollStatus scroll_status = input_handler_->ScrollBegin(
360 gfx::Point(wheel_event.x, wheel_event.y), cc::InputHandler::WHEEL);
361 switch (scroll_status) {
362 case cc::InputHandler::SCROLL_STARTED: {
363 TRACE_EVENT_INSTANT2(
364 "input", "InputHandlerProxy::handle_input wheel scroll",
365 TRACE_EVENT_SCOPE_THREAD, "deltaX", -wheel_event.deltaX, "deltaY",
366 -wheel_event.deltaY);
367 gfx::Point scroll_point(wheel_event.x, wheel_event.y);
368 gfx::Vector2dF scroll_delta(-wheel_event.deltaX, -wheel_event.deltaY);
369 scroll_result = input_handler_->ScrollBy(scroll_point, scroll_delta);
370 HandleOverscroll(scroll_point, scroll_result);
371 input_handler_->ScrollEnd();
372 result = scroll_result.did_scroll ? DID_HANDLE : DROP_EVENT;
373 break;
375 case cc::InputHandler::SCROLL_IGNORED:
376 // TODO(jamesr): This should be DROP_EVENT, but in cases where we fail
377 // to properly sync scrollability it's safer to send the event to the
378 // main thread. Change back to DROP_EVENT once we have synchronization
379 // bugs sorted out.
380 result = DID_NOT_HANDLE;
381 break;
382 case cc::InputHandler::SCROLL_UNKNOWN:
383 case cc::InputHandler::SCROLL_ON_MAIN_THREAD:
384 result = DID_NOT_HANDLE;
385 break;
386 case cc::InputHandler::ScrollStatusCount:
387 NOTREACHED();
388 break;
392 // Send the event and its disposition to the elasticity controller to update
393 // the over-scroll animation. If the event is to be handled on the main
394 // thread, the event and its disposition will be sent to the elasticity
395 // controller after being handled on the main thread.
396 if (scroll_elasticity_controller_ && result != DID_NOT_HANDLE) {
397 // Note that the call to the elasticity controller is made asynchronously,
398 // to minimize divergence between main thread and impl thread event
399 // handling paths.
400 base::MessageLoop::current()->PostTask(
401 FROM_HERE,
402 base::Bind(&InputScrollElasticityController::ObserveWheelEventAndResult,
403 scroll_elasticity_controller_->GetWeakPtr(), wheel_event,
404 scroll_result));
406 return result;
409 InputHandlerProxy::EventDisposition InputHandlerProxy::HandleGestureScrollBegin(
410 const WebGestureEvent& gesture_event) {
411 DCHECK(!gesture_scroll_on_impl_thread_);
412 #ifndef NDEBUG
413 DCHECK(!expect_scroll_update_end_);
414 expect_scroll_update_end_ = true;
415 #endif
416 cc::InputHandler::ScrollStatus scroll_status = input_handler_->ScrollBegin(
417 gfx::Point(gesture_event.x, gesture_event.y), cc::InputHandler::GESTURE);
418 UMA_HISTOGRAM_ENUMERATION("Renderer4.CompositorScrollHitTestResult",
419 scroll_status,
420 cc::InputHandler::ScrollStatusCount);
421 switch (scroll_status) {
422 case cc::InputHandler::SCROLL_STARTED:
423 TRACE_EVENT_INSTANT0("input",
424 "InputHandlerProxy::handle_input gesture scroll",
425 TRACE_EVENT_SCOPE_THREAD);
426 gesture_scroll_on_impl_thread_ = true;
427 return DID_HANDLE;
428 case cc::InputHandler::SCROLL_UNKNOWN:
429 case cc::InputHandler::SCROLL_ON_MAIN_THREAD:
430 return DID_NOT_HANDLE;
431 case cc::InputHandler::SCROLL_IGNORED:
432 return DROP_EVENT;
433 case cc::InputHandler::ScrollStatusCount:
434 NOTREACHED();
435 break;
437 return DID_NOT_HANDLE;
440 InputHandlerProxy::EventDisposition
441 InputHandlerProxy::HandleGestureScrollUpdate(
442 const WebGestureEvent& gesture_event) {
443 #ifndef NDEBUG
444 DCHECK(expect_scroll_update_end_);
445 #endif
447 if (!gesture_scroll_on_impl_thread_ && !gesture_pinch_on_impl_thread_)
448 return DID_NOT_HANDLE;
450 gfx::Point scroll_point(gesture_event.x, gesture_event.y);
451 gfx::Vector2dF scroll_delta(-gesture_event.data.scrollUpdate.deltaX,
452 -gesture_event.data.scrollUpdate.deltaY);
453 cc::InputHandlerScrollResult scroll_result = input_handler_->ScrollBy(
454 scroll_point, scroll_delta);
455 HandleOverscroll(scroll_point, scroll_result);
456 return scroll_result.did_scroll ? DID_HANDLE : DROP_EVENT;
459 InputHandlerProxy::EventDisposition InputHandlerProxy::HandleGestureScrollEnd(
460 const WebGestureEvent& gesture_event) {
461 #ifndef NDEBUG
462 DCHECK(expect_scroll_update_end_);
463 expect_scroll_update_end_ = false;
464 #endif
465 input_handler_->ScrollEnd();
466 if (!gesture_scroll_on_impl_thread_)
467 return DID_NOT_HANDLE;
468 gesture_scroll_on_impl_thread_ = false;
469 return DID_HANDLE;
472 InputHandlerProxy::EventDisposition InputHandlerProxy::HandleGestureFlingStart(
473 const WebGestureEvent& gesture_event) {
474 cc::InputHandler::ScrollStatus scroll_status;
476 if (gesture_event.sourceDevice == blink::WebGestureDeviceTouchpad) {
477 scroll_status = input_handler_->ScrollBegin(
478 gfx::Point(gesture_event.x, gesture_event.y),
479 cc::InputHandler::NON_BUBBLING_GESTURE);
480 } else {
481 if (!gesture_scroll_on_impl_thread_)
482 scroll_status = cc::InputHandler::SCROLL_ON_MAIN_THREAD;
483 else
484 scroll_status = input_handler_->FlingScrollBegin();
487 #ifndef NDEBUG
488 expect_scroll_update_end_ = false;
489 #endif
491 switch (scroll_status) {
492 case cc::InputHandler::SCROLL_STARTED: {
493 if (gesture_event.sourceDevice == blink::WebGestureDeviceTouchpad)
494 input_handler_->ScrollEnd();
496 const float vx = gesture_event.data.flingStart.velocityX;
497 const float vy = gesture_event.data.flingStart.velocityY;
498 current_fling_velocity_ = gfx::Vector2dF(vx, vy);
499 DCHECK(!current_fling_velocity_.IsZero());
500 fling_curve_.reset(client_->CreateFlingAnimationCurve(
501 gesture_event.sourceDevice,
502 WebFloatPoint(vx, vy),
503 blink::WebSize()));
504 disallow_horizontal_fling_scroll_ = !vx;
505 disallow_vertical_fling_scroll_ = !vy;
506 TRACE_EVENT_ASYNC_BEGIN2("input",
507 "InputHandlerProxy::HandleGestureFling::started",
508 this,
509 "vx",
511 "vy",
512 vy);
513 // Note that the timestamp will only be used to kickstart the animation if
514 // its sufficiently close to the timestamp of the first call |Animate()|.
515 has_fling_animation_started_ = false;
516 fling_parameters_.startTime = gesture_event.timeStampSeconds;
517 fling_parameters_.delta = WebFloatPoint(vx, vy);
518 fling_parameters_.point = WebPoint(gesture_event.x, gesture_event.y);
519 fling_parameters_.globalPoint =
520 WebPoint(gesture_event.globalX, gesture_event.globalY);
521 fling_parameters_.modifiers = gesture_event.modifiers;
522 fling_parameters_.sourceDevice = gesture_event.sourceDevice;
523 input_handler_->SetNeedsAnimate();
524 return DID_HANDLE;
526 case cc::InputHandler::SCROLL_UNKNOWN:
527 case cc::InputHandler::SCROLL_ON_MAIN_THREAD: {
528 TRACE_EVENT_INSTANT0("input",
529 "InputHandlerProxy::HandleGestureFling::"
530 "scroll_on_main_thread",
531 TRACE_EVENT_SCOPE_THREAD);
532 fling_may_be_active_on_main_thread_ = true;
533 return DID_NOT_HANDLE;
535 case cc::InputHandler::SCROLL_IGNORED: {
536 TRACE_EVENT_INSTANT0(
537 "input",
538 "InputHandlerProxy::HandleGestureFling::ignored",
539 TRACE_EVENT_SCOPE_THREAD);
540 if (gesture_event.sourceDevice == blink::WebGestureDeviceTouchpad) {
541 // We still pass the curve to the main thread if there's nothing
542 // scrollable, in case something
543 // registers a handler before the curve is over.
544 return DID_NOT_HANDLE;
546 return DROP_EVENT;
548 case cc::InputHandler::ScrollStatusCount:
549 NOTREACHED();
550 break;
552 return DID_NOT_HANDLE;
555 InputHandlerProxy::EventDisposition InputHandlerProxy::HandleTouchStart(
556 const blink::WebTouchEvent& touch_event) {
557 for (size_t i = 0; i < touch_event.touchesLength; ++i) {
558 if (touch_event.touches[i].state != WebTouchPoint::StatePressed)
559 continue;
560 if (input_handler_->DoTouchEventsBlockScrollAt(
561 gfx::Point(touch_event.touches[i].position.x,
562 touch_event.touches[i].position.y))) {
563 // TODO(rbyers): We should consider still sending the touch events to
564 // main asynchronously (crbug.com/455539).
565 return DID_NOT_HANDLE;
568 return DROP_EVENT;
571 bool InputHandlerProxy::FilterInputEventForFlingBoosting(
572 const WebInputEvent& event) {
573 if (!WebInputEvent::isGestureEventType(event.type))
574 return false;
576 if (!fling_curve_) {
577 DCHECK(!deferred_fling_cancel_time_seconds_);
578 return false;
581 const WebGestureEvent& gesture_event =
582 static_cast<const WebGestureEvent&>(event);
583 if (gesture_event.type == WebInputEvent::GestureFlingCancel) {
584 if (gesture_event.data.flingCancel.preventBoosting)
585 return false;
587 if (current_fling_velocity_.LengthSquared() < kMinBoostFlingSpeedSquare)
588 return false;
590 TRACE_EVENT_INSTANT0("input",
591 "InputHandlerProxy::FlingBoostStart",
592 TRACE_EVENT_SCOPE_THREAD);
593 deferred_fling_cancel_time_seconds_ =
594 event.timeStampSeconds + kFlingBoostTimeoutDelaySeconds;
595 return true;
598 // A fling is either inactive or is "free spinning", i.e., has yet to be
599 // interrupted by a touch gesture, in which case there is nothing to filter.
600 if (!deferred_fling_cancel_time_seconds_)
601 return false;
603 // Gestures from a different source should immediately interrupt the fling.
604 if (gesture_event.sourceDevice != fling_parameters_.sourceDevice) {
605 CancelCurrentFling();
606 return false;
609 switch (gesture_event.type) {
610 case WebInputEvent::GestureTapCancel:
611 case WebInputEvent::GestureTapDown:
612 return false;
614 case WebInputEvent::GestureScrollBegin:
615 if (!input_handler_->IsCurrentlyScrollingLayerAt(
616 gfx::Point(gesture_event.x, gesture_event.y),
617 fling_parameters_.sourceDevice == blink::WebGestureDeviceTouchpad
618 ? cc::InputHandler::NON_BUBBLING_GESTURE
619 : cc::InputHandler::GESTURE)) {
620 CancelCurrentFling();
621 return false;
624 // TODO(jdduke): Use |gesture_event.data.scrollBegin.delta{X,Y}Hint| to
625 // determine if the ScrollBegin should immediately cancel the fling.
626 ExtendBoostedFlingTimeout(gesture_event);
627 return true;
629 case WebInputEvent::GestureScrollUpdate: {
630 const double time_since_last_boost_event =
631 event.timeStampSeconds - last_fling_boost_event_.timeStampSeconds;
632 if (ShouldSuppressScrollForFlingBoosting(current_fling_velocity_,
633 gesture_event,
634 time_since_last_boost_event)) {
635 ExtendBoostedFlingTimeout(gesture_event);
636 return true;
639 CancelCurrentFling();
640 return false;
643 case WebInputEvent::GestureScrollEnd:
644 // Clear the last fling boost event *prior* to fling cancellation,
645 // preventing insertion of a synthetic GestureScrollBegin.
646 last_fling_boost_event_ = WebGestureEvent();
647 CancelCurrentFling();
648 return true;
650 case WebInputEvent::GestureFlingStart: {
651 DCHECK_EQ(fling_parameters_.sourceDevice, gesture_event.sourceDevice);
653 bool fling_boosted =
654 fling_parameters_.modifiers == gesture_event.modifiers &&
655 ShouldBoostFling(current_fling_velocity_, gesture_event);
657 gfx::Vector2dF new_fling_velocity(
658 gesture_event.data.flingStart.velocityX,
659 gesture_event.data.flingStart.velocityY);
660 DCHECK(!new_fling_velocity.IsZero());
662 if (fling_boosted)
663 current_fling_velocity_ += new_fling_velocity;
664 else
665 current_fling_velocity_ = new_fling_velocity;
667 WebFloatPoint velocity(current_fling_velocity_.x(),
668 current_fling_velocity_.y());
669 deferred_fling_cancel_time_seconds_ = 0;
670 disallow_horizontal_fling_scroll_ = !velocity.x;
671 disallow_vertical_fling_scroll_ = !velocity.y;
672 last_fling_boost_event_ = WebGestureEvent();
673 fling_curve_.reset(client_->CreateFlingAnimationCurve(
674 gesture_event.sourceDevice,
675 velocity,
676 blink::WebSize()));
677 fling_parameters_.startTime = gesture_event.timeStampSeconds;
678 fling_parameters_.delta = velocity;
679 fling_parameters_.point = WebPoint(gesture_event.x, gesture_event.y);
680 fling_parameters_.globalPoint =
681 WebPoint(gesture_event.globalX, gesture_event.globalY);
683 TRACE_EVENT_INSTANT2("input",
684 fling_boosted ? "InputHandlerProxy::FlingBoosted"
685 : "InputHandlerProxy::FlingReplaced",
686 TRACE_EVENT_SCOPE_THREAD,
687 "vx",
688 current_fling_velocity_.x(),
689 "vy",
690 current_fling_velocity_.y());
692 // The client expects balanced calls between a consumed GestureFlingStart
693 // and |DidStopFlinging()|. TODO(jdduke): Provide a count parameter to
694 // |DidStopFlinging()| and only send after the accumulated fling ends.
695 client_->DidStopFlinging();
696 return true;
699 default:
700 // All other types of gestures (taps, presses, etc...) will complete the
701 // deferred fling cancellation.
702 CancelCurrentFling();
703 return false;
707 void InputHandlerProxy::ExtendBoostedFlingTimeout(
708 const blink::WebGestureEvent& event) {
709 TRACE_EVENT_INSTANT0("input",
710 "InputHandlerProxy::ExtendBoostedFlingTimeout",
711 TRACE_EVENT_SCOPE_THREAD);
712 deferred_fling_cancel_time_seconds_ =
713 event.timeStampSeconds + kFlingBoostTimeoutDelaySeconds;
714 last_fling_boost_event_ = event;
717 void InputHandlerProxy::Animate(base::TimeTicks time) {
718 if (scroll_elasticity_controller_)
719 scroll_elasticity_controller_->Animate(time);
721 if (!fling_curve_)
722 return;
724 double monotonic_time_sec = InSecondsF(time);
726 if (deferred_fling_cancel_time_seconds_ &&
727 monotonic_time_sec > deferred_fling_cancel_time_seconds_) {
728 CancelCurrentFling();
729 return;
732 client_->DidAnimateForInput();
734 if (!has_fling_animation_started_) {
735 has_fling_animation_started_ = true;
736 // Guard against invalid, future or sufficiently stale start times, as there
737 // are no guarantees fling event and animation timestamps are compatible.
738 if (!fling_parameters_.startTime ||
739 monotonic_time_sec <= fling_parameters_.startTime ||
740 monotonic_time_sec >= fling_parameters_.startTime +
741 kMaxSecondsFromFlingTimestampToFirstAnimate) {
742 fling_parameters_.startTime = monotonic_time_sec;
743 input_handler_->SetNeedsAnimate();
744 return;
748 bool fling_is_active =
749 fling_curve_->apply(monotonic_time_sec - fling_parameters_.startTime,
750 this);
752 if (disallow_vertical_fling_scroll_ && disallow_horizontal_fling_scroll_)
753 fling_is_active = false;
755 if (fling_is_active) {
756 input_handler_->SetNeedsAnimate();
757 } else {
758 TRACE_EVENT_INSTANT0("input",
759 "InputHandlerProxy::animate::flingOver",
760 TRACE_EVENT_SCOPE_THREAD);
761 CancelCurrentFling();
765 void InputHandlerProxy::MainThreadHasStoppedFlinging() {
766 fling_may_be_active_on_main_thread_ = false;
767 client_->DidStopFlinging();
770 void InputHandlerProxy::ReconcileElasticOverscrollAndRootScroll() {
771 if (scroll_elasticity_controller_)
772 scroll_elasticity_controller_->ReconcileStretchAndScroll();
775 void InputHandlerProxy::HandleOverscroll(
776 const gfx::Point& causal_event_viewport_point,
777 const cc::InputHandlerScrollResult& scroll_result) {
778 DCHECK(client_);
779 if (!scroll_result.did_overscroll_root)
780 return;
782 TRACE_EVENT2("input",
783 "InputHandlerProxy::DidOverscroll",
784 "dx",
785 scroll_result.unused_scroll_delta.x(),
786 "dy",
787 scroll_result.unused_scroll_delta.y());
789 DidOverscrollParams params;
790 params.accumulated_overscroll = scroll_result.accumulated_root_overscroll;
791 params.latest_overscroll_delta = scroll_result.unused_scroll_delta;
792 params.current_fling_velocity =
793 ToClientScrollIncrement(current_fling_velocity_);
794 params.causal_event_viewport_point = causal_event_viewport_point;
796 if (fling_curve_) {
797 static const int kFlingOverscrollThreshold = 1;
798 disallow_horizontal_fling_scroll_ |=
799 std::abs(params.accumulated_overscroll.x()) >=
800 kFlingOverscrollThreshold;
801 disallow_vertical_fling_scroll_ |=
802 std::abs(params.accumulated_overscroll.y()) >=
803 kFlingOverscrollThreshold;
806 client_->DidOverscroll(params);
809 bool InputHandlerProxy::CancelCurrentFling() {
810 if (CancelCurrentFlingWithoutNotifyingClient()) {
811 client_->DidStopFlinging();
812 return true;
814 return false;
817 bool InputHandlerProxy::CancelCurrentFlingWithoutNotifyingClient() {
818 bool had_fling_animation = fling_curve_;
819 if (had_fling_animation &&
820 fling_parameters_.sourceDevice == blink::WebGestureDeviceTouchscreen) {
821 input_handler_->ScrollEnd();
822 TRACE_EVENT_ASYNC_END0(
823 "input",
824 "InputHandlerProxy::HandleGestureFling::started",
825 this);
828 TRACE_EVENT_INSTANT1("input",
829 "InputHandlerProxy::CancelCurrentFling",
830 TRACE_EVENT_SCOPE_THREAD,
831 "had_fling_animation",
832 had_fling_animation);
833 fling_curve_.reset();
834 has_fling_animation_started_ = false;
835 gesture_scroll_on_impl_thread_ = false;
836 current_fling_velocity_ = gfx::Vector2dF();
837 fling_parameters_ = blink::WebActiveWheelFlingParameters();
839 if (deferred_fling_cancel_time_seconds_) {
840 deferred_fling_cancel_time_seconds_ = 0;
842 WebGestureEvent last_fling_boost_event = last_fling_boost_event_;
843 last_fling_boost_event_ = WebGestureEvent();
844 if (last_fling_boost_event.type == WebInputEvent::GestureScrollBegin ||
845 last_fling_boost_event.type == WebInputEvent::GestureScrollUpdate) {
846 // Synthesize a GestureScrollBegin, as the original was suppressed.
847 HandleInputEvent(ObtainGestureScrollBegin(last_fling_boost_event));
851 return had_fling_animation;
854 bool InputHandlerProxy::TouchpadFlingScroll(
855 const WebFloatSize& increment) {
856 WebMouseWheelEvent synthetic_wheel;
857 synthetic_wheel.type = WebInputEvent::MouseWheel;
858 synthetic_wheel.deltaX = increment.width;
859 synthetic_wheel.deltaY = increment.height;
860 synthetic_wheel.hasPreciseScrollingDeltas = true;
861 synthetic_wheel.x = fling_parameters_.point.x;
862 synthetic_wheel.y = fling_parameters_.point.y;
863 synthetic_wheel.globalX = fling_parameters_.globalPoint.x;
864 synthetic_wheel.globalY = fling_parameters_.globalPoint.y;
865 synthetic_wheel.modifiers = fling_parameters_.modifiers;
867 InputHandlerProxy::EventDisposition disposition =
868 HandleInputEvent(synthetic_wheel);
869 switch (disposition) {
870 case DID_HANDLE:
871 return true;
872 case DROP_EVENT:
873 break;
874 case DID_NOT_HANDLE:
875 TRACE_EVENT_INSTANT0("input",
876 "InputHandlerProxy::scrollBy::AbortFling",
877 TRACE_EVENT_SCOPE_THREAD);
878 // If we got a DID_NOT_HANDLE, that means we need to deliver wheels on the
879 // main thread. In this case we need to schedule a commit and transfer the
880 // fling curve over to the main thread and run the rest of the wheels from
881 // there. This can happen when flinging a page that contains a scrollable
882 // subarea that we can't scroll on the thread if the fling starts outside
883 // the subarea but then is flung "under" the pointer.
884 client_->TransferActiveWheelFlingAnimation(fling_parameters_);
885 fling_may_be_active_on_main_thread_ = true;
886 CancelCurrentFlingWithoutNotifyingClient();
887 break;
890 return false;
893 bool InputHandlerProxy::scrollBy(const WebFloatSize& increment,
894 const WebFloatSize& velocity) {
895 WebFloatSize clipped_increment;
896 WebFloatSize clipped_velocity;
897 if (!disallow_horizontal_fling_scroll_) {
898 clipped_increment.width = increment.width;
899 clipped_velocity.width = velocity.width;
901 if (!disallow_vertical_fling_scroll_) {
902 clipped_increment.height = increment.height;
903 clipped_velocity.height = velocity.height;
906 current_fling_velocity_ = clipped_velocity;
908 // Early out if the increment is zero, but avoid early terimination if the
909 // velocity is still non-zero.
910 if (clipped_increment == WebFloatSize())
911 return clipped_velocity != WebFloatSize();
913 TRACE_EVENT2("input",
914 "InputHandlerProxy::scrollBy",
915 "x",
916 clipped_increment.width,
917 "y",
918 clipped_increment.height);
920 bool did_scroll = false;
922 switch (fling_parameters_.sourceDevice) {
923 case blink::WebGestureDeviceTouchpad:
924 did_scroll = TouchpadFlingScroll(clipped_increment);
925 break;
926 case blink::WebGestureDeviceTouchscreen: {
927 clipped_increment = ToClientScrollIncrement(clipped_increment);
928 cc::InputHandlerScrollResult scroll_result = input_handler_->ScrollBy(
929 fling_parameters_.point, clipped_increment);
930 HandleOverscroll(fling_parameters_.point, scroll_result);
931 did_scroll = scroll_result.did_scroll;
932 } break;
935 if (did_scroll) {
936 fling_parameters_.cumulativeScroll.width += clipped_increment.width;
937 fling_parameters_.cumulativeScroll.height += clipped_increment.height;
940 // It's possible the provided |increment| is sufficiently small as to not
941 // trigger a scroll, e.g., with a trivial time delta between fling updates.
942 // Return true in this case to prevent early fling termination.
943 if (std::abs(clipped_increment.width) < kScrollEpsilon &&
944 std::abs(clipped_increment.height) < kScrollEpsilon)
945 return true;
947 return did_scroll;
950 } // namespace content