Pin Chrome's shortcut to the Win10 Start menu on install and OS upgrade.
[chromium-blink-merge.git] / ui / events / gesture_detection / gesture_detector.cc
blobcd8883572ccda8eeb20c915d8f661d3e079d398e
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 // We should eventually apply touch slop for multi-finger
299 // scrolls as well as single finger scrolls. See
300 // crbug.com/492185 for details.
301 handled =
302 listener_->OnScroll(*current_down_event_, ev, scroll_x, scroll_y);
303 last_focus_x_ = focus_x;
304 last_focus_y_ = focus_y;
307 if (!two_finger_tap_allowed_for_gesture_)
308 break;
310 // Two-finger tap should be prevented if either pointer exceeds its
311 // (independent) slop region.
312 const int id0 = current_down_event_->GetPointerId(0);
313 const int ev_idx0 = ev.GetPointerId(0) == id0 ? 0 : 1;
315 // Check if the primary pointer exceeded the slop region.
316 float dx = current_down_event_->GetX() - ev.GetX(ev_idx0);
317 float dy = current_down_event_->GetY() - ev.GetY(ev_idx0);
318 if (dx * dx + dy * dy > touch_slop_square_) {
319 two_finger_tap_allowed_for_gesture_ = false;
320 break;
322 if (ev.GetPointerCount() == 2) {
323 // Check if the secondary pointer exceeded the slop region.
324 const int ev_idx1 = ev_idx0 == 0 ? 1 : 0;
325 const int idx1 = secondary_pointer_down_event_->GetActionIndex();
326 dx = secondary_pointer_down_event_->GetX(idx1) - ev.GetX(ev_idx1);
327 dy = secondary_pointer_down_event_->GetY(idx1) - ev.GetY(ev_idx1);
328 if (dx * dx + dy * dy > touch_slop_square_)
329 two_finger_tap_allowed_for_gesture_ = false;
332 break;
334 case MotionEvent::ACTION_UP:
335 still_down_ = false;
337 if (is_double_tapping_) {
338 // Finally, give the up event of the double-tap.
339 DCHECK(double_tap_listener_);
340 handled |= double_tap_listener_->OnDoubleTapEvent(ev);
341 } else if (always_in_tap_region_) {
342 handled = listener_->OnSingleTapUp(ev);
343 if (defer_confirm_single_tap_ && double_tap_listener_ != NULL) {
344 double_tap_listener_->OnSingleTapConfirmed(ev);
346 } else {
348 // A fling must travel the minimum tap distance.
349 const int pointer_id = ev.GetPointerId(0);
350 velocity_tracker_.ComputeCurrentVelocity(1000, max_fling_velocity_);
351 const float velocity_y = velocity_tracker_.GetYVelocity(pointer_id);
352 const float velocity_x = velocity_tracker_.GetXVelocity(pointer_id);
354 if ((std::abs(velocity_y) > min_fling_velocity_) ||
355 (std::abs(velocity_x) > min_fling_velocity_)) {
356 handled = listener_->OnFling(
357 *current_down_event_, ev, velocity_x, velocity_y);
360 handled |= HandleSwipeIfNeeded(ev, velocity_x, velocity_y);
363 previous_up_event_ = ev.Clone();
365 velocity_tracker_.Clear();
366 is_double_tapping_ = false;
367 defer_confirm_single_tap_ = false;
368 timeout_handler_->StopTimeout(SHOW_PRESS);
369 timeout_handler_->StopTimeout(LONG_PRESS);
371 break;
373 case MotionEvent::ACTION_CANCEL:
374 Cancel();
375 break;
378 return handled;
381 void GestureDetector::SetDoubleTapListener(
382 DoubleTapListener* double_tap_listener) {
383 if (double_tap_listener == double_tap_listener_)
384 return;
386 DCHECK(!is_double_tapping_);
388 // Null'ing the double-tap listener should flush an active tap timeout.
389 if (!double_tap_listener) {
390 if (timeout_handler_->HasTimeout(TAP)) {
391 timeout_handler_->StopTimeout(TAP);
392 OnTapTimeout();
396 double_tap_listener_ = double_tap_listener;
399 void GestureDetector::Init(const Config& config) {
400 DCHECK(listener_);
402 const float touch_slop = config.touch_slop + kSlopEpsilon;
403 const float double_tap_touch_slop = touch_slop;
404 const float double_tap_slop = config.double_tap_slop + kSlopEpsilon;
405 touch_slop_square_ = touch_slop * touch_slop;
406 double_tap_touch_slop_square_ = double_tap_touch_slop * double_tap_touch_slop;
407 double_tap_slop_square_ = double_tap_slop * double_tap_slop;
408 double_tap_timeout_ = config.double_tap_timeout;
409 double_tap_min_time_ = config.double_tap_min_time;
410 DCHECK(double_tap_min_time_ < double_tap_timeout_);
411 min_fling_velocity_ = config.minimum_fling_velocity;
412 max_fling_velocity_ = config.maximum_fling_velocity;
414 swipe_enabled_ = config.swipe_enabled;
415 min_swipe_velocity_ = config.minimum_swipe_velocity;
416 DCHECK_GT(config.maximum_swipe_deviation_angle, 0);
417 DCHECK_LE(config.maximum_swipe_deviation_angle, 45);
418 const float maximum_swipe_deviation_angle =
419 std::min(45.f, std::max(0.001f, config.maximum_swipe_deviation_angle));
420 min_swipe_direction_component_ratio_ =
421 1.f / tan(maximum_swipe_deviation_angle * kDegreesToRadians);
423 two_finger_tap_enabled_ = config.two_finger_tap_enabled;
424 two_finger_tap_distance_square_ = config.two_finger_tap_max_separation *
425 config.two_finger_tap_max_separation;
426 two_finger_tap_timeout_ = config.two_finger_tap_timeout;
429 void GestureDetector::OnShowPressTimeout() {
430 listener_->OnShowPress(*current_down_event_);
433 void GestureDetector::OnLongPressTimeout() {
434 timeout_handler_->StopTimeout(TAP);
435 defer_confirm_single_tap_ = false;
436 listener_->OnLongPress(*current_down_event_);
439 void GestureDetector::OnTapTimeout() {
440 if (!double_tap_listener_)
441 return;
442 if (!still_down_) {
443 CHECK(previous_up_event_);
444 double_tap_listener_->OnSingleTapConfirmed(*previous_up_event_);
445 } else {
446 defer_confirm_single_tap_ = true;
450 void GestureDetector::Cancel() {
451 CancelTaps();
452 velocity_tracker_.Clear();
453 still_down_ = false;
456 void GestureDetector::CancelTaps() {
457 timeout_handler_->Stop();
458 is_double_tapping_ = false;
459 always_in_tap_region_ = false;
460 always_in_bigger_tap_region_ = false;
461 defer_confirm_single_tap_ = false;
464 bool GestureDetector::IsConsideredDoubleTap(
465 const MotionEvent& first_down,
466 const MotionEvent& first_up,
467 const MotionEvent& second_down) const {
468 if (!always_in_bigger_tap_region_)
469 return false;
471 const base::TimeDelta delta_time =
472 second_down.GetEventTime() - first_up.GetEventTime();
473 if (delta_time < double_tap_min_time_ || delta_time > double_tap_timeout_)
474 return false;
476 const float delta_x = first_down.GetX() - second_down.GetX();
477 const float delta_y = first_down.GetY() - second_down.GetY();
478 return (delta_x * delta_x + delta_y * delta_y < double_tap_slop_square_);
481 bool GestureDetector::HandleSwipeIfNeeded(const MotionEvent& up,
482 float vx,
483 float vy) {
484 if (!swipe_enabled_ || (!vx && !vy))
485 return false;
486 float vx_abs = std::abs(vx);
487 float vy_abs = std::abs(vy);
489 if (vx_abs < min_swipe_velocity_)
490 vx_abs = vx = 0;
491 if (vy_abs < min_swipe_velocity_)
492 vy_abs = vy = 0;
494 // Note that the ratio will be 0 if both velocites are below the min.
495 float ratio = vx_abs > vy_abs ? vx_abs / std::max(vy_abs, 0.001f)
496 : vy_abs / std::max(vx_abs, 0.001f);
498 if (ratio < min_swipe_direction_component_ratio_)
499 return false;
501 if (vx_abs > vy_abs)
502 vy = 0;
503 else
504 vx = 0;
505 return listener_->OnSwipe(*current_down_event_, up, vx, vy);
508 } // namespace ui