Revert of Roll src/third_party/WebKit e0eac24:489c548 (svn 193311:193320) (patchset...
[chromium-blink-merge.git] / ui / events / gesture_detection / gesture_detector.cc
blob3dc8283db65ba6935d64826956af8f2dba0d3596
1 // Copyright 2014 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 // MSVC++ requires this to be set before any other includes to get M_PI.
6 #define _USE_MATH_DEFINES
8 #include "ui/events/gesture_detection/gesture_detector.h"
10 #include <cmath>
12 #include "base/timer/timer.h"
13 #include "ui/events/gesture_detection/gesture_listeners.h"
14 #include "ui/events/gesture_detection/motion_event.h"
16 namespace ui {
17 namespace {
19 // Using a small epsilon when comparing slop distances allows pixel perfect
20 // slop determination when using fractional DIP coordinates (assuming the slop
21 // region and DPI scale are reasonably proportioned).
22 const float kSlopEpsilon = .05f;
24 // Minimum distance a scroll must have traveled from the last scroll/focal point
25 // to trigger an |OnScroll| callback.
26 const float kScrollEpsilon = .1f;
28 const float kDegreesToRadians = static_cast<float>(M_PI) / 180.0f;
30 // Constants used by TimeoutGestureHandler.
31 enum TimeoutEvent {
32 SHOW_PRESS = 0,
33 LONG_PRESS,
34 TAP,
35 TIMEOUT_EVENT_COUNT
38 } // namespace
40 // Note: These constants were taken directly from the default (unscaled)
41 // versions found in Android's ViewConfiguration. Do not change these default
42 // values without explicitly consulting an OWNER.
43 GestureDetector::Config::Config()
44 : longpress_timeout(base::TimeDelta::FromMilliseconds(500)),
45 showpress_timeout(base::TimeDelta::FromMilliseconds(180)),
46 double_tap_timeout(base::TimeDelta::FromMilliseconds(300)),
47 double_tap_min_time(base::TimeDelta::FromMilliseconds(40)),
48 touch_slop(8),
49 double_tap_slop(100),
50 minimum_fling_velocity(50),
51 maximum_fling_velocity(8000),
52 swipe_enabled(false),
53 minimum_swipe_velocity(20),
54 maximum_swipe_deviation_angle(20.f),
55 two_finger_tap_enabled(false),
56 two_finger_tap_max_separation(300),
57 two_finger_tap_timeout(base::TimeDelta::FromMilliseconds(700)),
58 velocity_tracker_strategy(VelocityTracker::Strategy::STRATEGY_DEFAULT) {
61 GestureDetector::Config::~Config() {}
63 class GestureDetector::TimeoutGestureHandler {
64 public:
65 TimeoutGestureHandler(const Config& config, GestureDetector* gesture_detector)
66 : gesture_detector_(gesture_detector) {
67 DCHECK(config.showpress_timeout <= config.longpress_timeout);
69 timeout_callbacks_[SHOW_PRESS] = &GestureDetector::OnShowPressTimeout;
70 timeout_delays_[SHOW_PRESS] = config.showpress_timeout;
72 timeout_callbacks_[LONG_PRESS] = &GestureDetector::OnLongPressTimeout;
73 timeout_delays_[LONG_PRESS] =
74 config.longpress_timeout + config.showpress_timeout;
76 timeout_callbacks_[TAP] = &GestureDetector::OnTapTimeout;
77 timeout_delays_[TAP] = config.double_tap_timeout;
80 ~TimeoutGestureHandler() {
81 Stop();
84 void StartTimeout(TimeoutEvent event) {
85 timeout_timers_[event].Start(FROM_HERE,
86 timeout_delays_[event],
87 gesture_detector_,
88 timeout_callbacks_[event]);
91 void StopTimeout(TimeoutEvent event) { timeout_timers_[event].Stop(); }
93 void Stop() {
94 for (size_t i = SHOW_PRESS; i < TIMEOUT_EVENT_COUNT; ++i)
95 timeout_timers_[i].Stop();
98 bool HasTimeout(TimeoutEvent event) const {
99 return timeout_timers_[event].IsRunning();
102 private:
103 typedef void (GestureDetector::*ReceiverMethod)();
105 GestureDetector* const gesture_detector_;
106 base::OneShotTimer<GestureDetector> timeout_timers_[TIMEOUT_EVENT_COUNT];
107 ReceiverMethod timeout_callbacks_[TIMEOUT_EVENT_COUNT];
108 base::TimeDelta timeout_delays_[TIMEOUT_EVENT_COUNT];
111 GestureDetector::GestureDetector(
112 const Config& config,
113 GestureListener* listener,
114 DoubleTapListener* optional_double_tap_listener)
115 : timeout_handler_(new TimeoutGestureHandler(config, this)),
116 listener_(listener),
117 double_tap_listener_(optional_double_tap_listener),
118 touch_slop_square_(0),
119 double_tap_touch_slop_square_(0),
120 double_tap_slop_square_(0),
121 two_finger_tap_distance_square_(0),
122 min_fling_velocity_(1),
123 max_fling_velocity_(1),
124 min_swipe_velocity_(0),
125 min_swipe_direction_component_ratio_(0),
126 still_down_(false),
127 defer_confirm_single_tap_(false),
128 always_in_tap_region_(false),
129 always_in_bigger_tap_region_(false),
130 two_finger_tap_allowed_for_gesture_(false),
131 is_double_tapping_(false),
132 last_focus_x_(0),
133 last_focus_y_(0),
134 down_focus_x_(0),
135 down_focus_y_(0),
136 longpress_enabled_(true),
137 showpress_enabled_(true),
138 swipe_enabled_(false),
139 two_finger_tap_enabled_(false),
140 velocity_tracker_(config.velocity_tracker_strategy) {
141 DCHECK(listener_);
142 Init(config);
145 GestureDetector::~GestureDetector() {}
147 bool GestureDetector::OnTouchEvent(const MotionEvent& ev) {
148 const MotionEvent::Action action = ev.GetAction();
150 velocity_tracker_.AddMovement(ev);
152 const bool pointer_up = action == MotionEvent::ACTION_POINTER_UP;
153 const int skip_index = pointer_up ? ev.GetActionIndex() : -1;
155 // Determine focal point.
156 float sum_x = 0, sum_y = 0;
157 const int count = static_cast<int>(ev.GetPointerCount());
158 for (int i = 0; i < count; i++) {
159 if (skip_index == i)
160 continue;
161 sum_x += ev.GetX(i);
162 sum_y += ev.GetY(i);
164 const int div = pointer_up ? count - 1 : count;
165 const float focus_x = sum_x / div;
166 const float focus_y = sum_y / div;
168 bool handled = false;
170 switch (action) {
171 case MotionEvent::ACTION_POINTER_DOWN: {
172 down_focus_x_ = last_focus_x_ = focus_x;
173 down_focus_y_ = last_focus_y_ = focus_y;
174 // Cancel long press and taps.
175 CancelTaps();
177 if (!two_finger_tap_allowed_for_gesture_)
178 break;
180 const int action_index = ev.GetActionIndex();
181 const float dx = ev.GetX(action_index) - current_down_event_->GetX();
182 const float dy = ev.GetY(action_index) - current_down_event_->GetY();
184 if (ev.GetPointerCount() == 2 &&
185 dx * dx + dy * dy < two_finger_tap_distance_square_) {
186 secondary_pointer_down_event_ = ev.Clone();
187 } else {
188 two_finger_tap_allowed_for_gesture_ = false;
190 } break;
192 case MotionEvent::ACTION_POINTER_UP: {
193 down_focus_x_ = last_focus_x_ = focus_x;
194 down_focus_y_ = last_focus_y_ = focus_y;
196 // Check the dot product of current velocities.
197 // If the pointer that left was opposing another velocity vector, clear.
198 velocity_tracker_.ComputeCurrentVelocity(1000, max_fling_velocity_);
199 const int up_index = ev.GetActionIndex();
200 const int id1 = ev.GetPointerId(up_index);
201 const float vx1 = velocity_tracker_.GetXVelocity(id1);
202 const float vy1 = velocity_tracker_.GetYVelocity(id1);
203 float vx_total = vx1;
204 float vy_total = vy1;
205 for (int i = 0; i < count; i++) {
206 if (i == up_index)
207 continue;
209 const int id2 = ev.GetPointerId(i);
210 const float vx2 = velocity_tracker_.GetXVelocity(id2);
211 const float vy2 = velocity_tracker_.GetYVelocity(id2);
212 const float dot = vx1 * vx2 + vy1 * vy2;
213 if (dot < 0) {
214 vx_total = 0;
215 vy_total = 0;
216 velocity_tracker_.Clear();
217 break;
219 vx_total += vx2;
220 vy_total += vy2;
223 handled = HandleSwipeIfNeeded(ev, vx_total / count, vy_total / count);
225 if (two_finger_tap_allowed_for_gesture_ && ev.GetPointerCount() == 2 &&
226 (ev.GetEventTime() - secondary_pointer_down_event_->GetEventTime() <=
227 two_finger_tap_timeout_)) {
228 handled = listener_->OnTwoFingerTap(*current_down_event_, ev);
230 two_finger_tap_allowed_for_gesture_ = false;
231 } break;
233 case MotionEvent::ACTION_DOWN:
234 if (double_tap_listener_) {
235 bool had_tap_message = timeout_handler_->HasTimeout(TAP);
236 if (had_tap_message)
237 timeout_handler_->StopTimeout(TAP);
238 if (current_down_event_ && previous_up_event_ && had_tap_message &&
239 IsConsideredDoubleTap(
240 *current_down_event_, *previous_up_event_, ev)) {
241 // This is a second tap.
242 is_double_tapping_ = true;
243 // Give a callback with the first tap of the double-tap.
244 handled |= double_tap_listener_->OnDoubleTap(*current_down_event_);
245 // Give a callback with down event of the double-tap.
246 handled |= double_tap_listener_->OnDoubleTapEvent(ev);
247 } else {
248 // This is a first tap.
249 DCHECK(double_tap_timeout_ > base::TimeDelta());
250 timeout_handler_->StartTimeout(TAP);
254 down_focus_x_ = last_focus_x_ = focus_x;
255 down_focus_y_ = last_focus_y_ = focus_y;
256 current_down_event_ = ev.Clone();
258 secondary_pointer_down_event_.reset();
259 always_in_tap_region_ = true;
260 always_in_bigger_tap_region_ = true;
261 still_down_ = true;
262 defer_confirm_single_tap_ = false;
263 two_finger_tap_allowed_for_gesture_ = two_finger_tap_enabled_;
265 // Always start the SHOW_PRESS timer before the LONG_PRESS timer to ensure
266 // proper timeout ordering.
267 if (showpress_enabled_)
268 timeout_handler_->StartTimeout(SHOW_PRESS);
269 if (longpress_enabled_)
270 timeout_handler_->StartTimeout(LONG_PRESS);
271 handled |= listener_->OnDown(ev);
272 break;
274 case MotionEvent::ACTION_MOVE:
276 const float scroll_x = last_focus_x_ - focus_x;
277 const float scroll_y = last_focus_y_ - focus_y;
278 if (is_double_tapping_) {
279 // Give the move events of the double-tap.
280 DCHECK(double_tap_listener_);
281 handled |= double_tap_listener_->OnDoubleTapEvent(ev);
282 } else if (always_in_tap_region_) {
283 const float delta_x = focus_x - down_focus_x_;
284 const float delta_y = focus_y - down_focus_y_;
285 const float distance_square = delta_x * delta_x + delta_y * delta_y;
286 if (distance_square > touch_slop_square_) {
287 handled = listener_->OnScroll(
288 *current_down_event_, ev, scroll_x, scroll_y);
289 last_focus_x_ = focus_x;
290 last_focus_y_ = focus_y;
291 always_in_tap_region_ = false;
292 timeout_handler_->Stop();
294 if (distance_square > double_tap_touch_slop_square_)
295 always_in_bigger_tap_region_ = false;
296 } else if (std::abs(scroll_x) > kScrollEpsilon ||
297 std::abs(scroll_y) > kScrollEpsilon) {
298 handled =
299 listener_->OnScroll(*current_down_event_, ev, scroll_x, scroll_y);
300 last_focus_x_ = focus_x;
301 last_focus_y_ = focus_y;
304 if (!two_finger_tap_allowed_for_gesture_)
305 break;
307 // Two-finger tap should be prevented if either pointer exceeds its
308 // (independent) slop region.
309 const int id0 = current_down_event_->GetPointerId(0);
310 const int ev_idx0 = ev.GetPointerId(0) == id0 ? 0 : 1;
312 // Check if the primary pointer exceeded the slop region.
313 float dx = current_down_event_->GetX() - ev.GetX(ev_idx0);
314 float dy = current_down_event_->GetY() - ev.GetY(ev_idx0);
315 if (dx * dx + dy * dy > touch_slop_square_) {
316 two_finger_tap_allowed_for_gesture_ = false;
317 break;
319 if (ev.GetPointerCount() == 2) {
320 // Check if the secondary pointer exceeded the slop region.
321 const int ev_idx1 = ev_idx0 == 0 ? 1 : 0;
322 const int idx1 = secondary_pointer_down_event_->GetActionIndex();
323 dx = secondary_pointer_down_event_->GetX(idx1) - ev.GetX(ev_idx1);
324 dy = secondary_pointer_down_event_->GetY(idx1) - ev.GetY(ev_idx1);
325 if (dx * dx + dy * dy > touch_slop_square_)
326 two_finger_tap_allowed_for_gesture_ = false;
329 break;
331 case MotionEvent::ACTION_UP:
332 still_down_ = false;
334 if (is_double_tapping_) {
335 // Finally, give the up event of the double-tap.
336 DCHECK(double_tap_listener_);
337 handled |= double_tap_listener_->OnDoubleTapEvent(ev);
338 } else if (always_in_tap_region_) {
339 handled = listener_->OnSingleTapUp(ev);
340 if (defer_confirm_single_tap_ && double_tap_listener_ != NULL) {
341 double_tap_listener_->OnSingleTapConfirmed(ev);
343 } else {
345 // A fling must travel the minimum tap distance.
346 const int pointer_id = ev.GetPointerId(0);
347 velocity_tracker_.ComputeCurrentVelocity(1000, max_fling_velocity_);
348 const float velocity_y = velocity_tracker_.GetYVelocity(pointer_id);
349 const float velocity_x = velocity_tracker_.GetXVelocity(pointer_id);
351 if ((std::abs(velocity_y) > min_fling_velocity_) ||
352 (std::abs(velocity_x) > min_fling_velocity_)) {
353 handled = listener_->OnFling(
354 *current_down_event_, ev, velocity_x, velocity_y);
357 handled |= HandleSwipeIfNeeded(ev, velocity_x, velocity_y);
360 previous_up_event_ = ev.Clone();
362 velocity_tracker_.Clear();
363 is_double_tapping_ = false;
364 defer_confirm_single_tap_ = false;
365 timeout_handler_->StopTimeout(SHOW_PRESS);
366 timeout_handler_->StopTimeout(LONG_PRESS);
368 break;
370 case MotionEvent::ACTION_CANCEL:
371 Cancel();
372 break;
375 return handled;
378 void GestureDetector::SetDoubleTapListener(
379 DoubleTapListener* double_tap_listener) {
380 if (double_tap_listener == double_tap_listener_)
381 return;
383 DCHECK(!is_double_tapping_);
385 // Null'ing the double-tap listener should flush an active tap timeout.
386 if (!double_tap_listener) {
387 if (timeout_handler_->HasTimeout(TAP)) {
388 timeout_handler_->StopTimeout(TAP);
389 OnTapTimeout();
393 double_tap_listener_ = double_tap_listener;
396 void GestureDetector::Init(const Config& config) {
397 DCHECK(listener_);
399 const float touch_slop = config.touch_slop + kSlopEpsilon;
400 const float double_tap_touch_slop = touch_slop;
401 const float double_tap_slop = config.double_tap_slop + kSlopEpsilon;
402 touch_slop_square_ = touch_slop * touch_slop;
403 double_tap_touch_slop_square_ = double_tap_touch_slop * double_tap_touch_slop;
404 double_tap_slop_square_ = double_tap_slop * double_tap_slop;
405 double_tap_timeout_ = config.double_tap_timeout;
406 double_tap_min_time_ = config.double_tap_min_time;
407 DCHECK(double_tap_min_time_ < double_tap_timeout_);
408 min_fling_velocity_ = config.minimum_fling_velocity;
409 max_fling_velocity_ = config.maximum_fling_velocity;
411 swipe_enabled_ = config.swipe_enabled;
412 min_swipe_velocity_ = config.minimum_swipe_velocity;
413 DCHECK_GT(config.maximum_swipe_deviation_angle, 0);
414 DCHECK_LE(config.maximum_swipe_deviation_angle, 45);
415 const float maximum_swipe_deviation_angle =
416 std::min(45.f, std::max(0.001f, config.maximum_swipe_deviation_angle));
417 min_swipe_direction_component_ratio_ =
418 1.f / tan(maximum_swipe_deviation_angle * kDegreesToRadians);
420 two_finger_tap_enabled_ = config.two_finger_tap_enabled;
421 two_finger_tap_distance_square_ = config.two_finger_tap_max_separation *
422 config.two_finger_tap_max_separation;
423 two_finger_tap_timeout_ = config.two_finger_tap_timeout;
426 void GestureDetector::OnShowPressTimeout() {
427 listener_->OnShowPress(*current_down_event_);
430 void GestureDetector::OnLongPressTimeout() {
431 timeout_handler_->StopTimeout(TAP);
432 defer_confirm_single_tap_ = false;
433 listener_->OnLongPress(*current_down_event_);
436 void GestureDetector::OnTapTimeout() {
437 if (!double_tap_listener_)
438 return;
439 if (!still_down_) {
440 CHECK(previous_up_event_);
441 double_tap_listener_->OnSingleTapConfirmed(*previous_up_event_);
442 } else {
443 defer_confirm_single_tap_ = true;
447 void GestureDetector::Cancel() {
448 CancelTaps();
449 velocity_tracker_.Clear();
450 still_down_ = false;
453 void GestureDetector::CancelTaps() {
454 timeout_handler_->Stop();
455 is_double_tapping_ = false;
456 always_in_tap_region_ = false;
457 always_in_bigger_tap_region_ = false;
458 defer_confirm_single_tap_ = false;
461 bool GestureDetector::IsConsideredDoubleTap(
462 const MotionEvent& first_down,
463 const MotionEvent& first_up,
464 const MotionEvent& second_down) const {
465 if (!always_in_bigger_tap_region_)
466 return false;
468 const base::TimeDelta delta_time =
469 second_down.GetEventTime() - first_up.GetEventTime();
470 if (delta_time < double_tap_min_time_ || delta_time > double_tap_timeout_)
471 return false;
473 const float delta_x = first_down.GetX() - second_down.GetX();
474 const float delta_y = first_down.GetY() - second_down.GetY();
475 return (delta_x * delta_x + delta_y * delta_y < double_tap_slop_square_);
478 bool GestureDetector::HandleSwipeIfNeeded(const MotionEvent& up,
479 float vx,
480 float vy) {
481 if (!swipe_enabled_ || (!vx && !vy))
482 return false;
483 float vx_abs = std::abs(vx);
484 float vy_abs = std::abs(vy);
486 if (vx_abs < min_swipe_velocity_)
487 vx_abs = vx = 0;
488 if (vy_abs < min_swipe_velocity_)
489 vy_abs = vy = 0;
491 // Note that the ratio will be 0 if both velocites are below the min.
492 float ratio = vx_abs > vy_abs ? vx_abs / std::max(vy_abs, 0.001f)
493 : vy_abs / std::max(vx_abs, 0.001f);
495 if (ratio < min_swipe_direction_component_ratio_)
496 return false;
498 if (vx_abs > vy_abs)
499 vy = 0;
500 else
501 vx = 0;
502 return listener_->OnSwipe(*current_down_event_, up, vx, vy);
505 } // namespace ui