Reorder permission message rules, so that related rules appear together.
[chromium-blink-merge.git] / ash / drag_drop / drag_drop_controller.cc
blob70bbd05ab0dca92c28ae721057fe4a42e54e3b15
1 // Copyright (c) 2012 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 "ash/drag_drop/drag_drop_controller.h"
7 #include "ash/drag_drop/drag_drop_tracker.h"
8 #include "ash/drag_drop/drag_image_view.h"
9 #include "ash/shell.h"
10 #include "base/bind.h"
11 #include "base/message_loop/message_loop.h"
12 #include "base/metrics/histogram_macros.h"
13 #include "base/run_loop.h"
14 #include "ui/aura/client/capture_client.h"
15 #include "ui/aura/env.h"
16 #include "ui/aura/window.h"
17 #include "ui/aura/window_delegate.h"
18 #include "ui/aura/window_event_dispatcher.h"
19 #include "ui/base/dragdrop/drag_drop_types.h"
20 #include "ui/base/dragdrop/os_exchange_data.h"
21 #include "ui/base/hit_test.h"
22 #include "ui/events/event.h"
23 #include "ui/events/event_utils.h"
24 #include "ui/gfx/animation/linear_animation.h"
25 #include "ui/gfx/geometry/point.h"
26 #include "ui/gfx/geometry/rect.h"
27 #include "ui/gfx/geometry/rect_conversions.h"
28 #include "ui/gfx/path.h"
29 #include "ui/views/widget/native_widget_aura.h"
30 #include "ui/wm/core/coordinate_conversion.h"
31 #include "ui/wm/public/drag_drop_delegate.h"
33 namespace ash {
34 namespace {
36 // The duration of the drag cancel animation in millisecond.
37 const int kCancelAnimationDuration = 250;
38 const int kTouchCancelAnimationDuration = 20;
39 // The frame rate of the drag cancel animation in hertz.
40 const int kCancelAnimationFrameRate = 60;
42 // For touch initiated dragging, we scale and shift drag image by the following:
43 static const float kTouchDragImageScale = 1.2f;
44 static const int kTouchDragImageVerticalOffset = -25;
46 // Adjusts the drag image bounds such that the new bounds are scaled by |scale|
47 // and translated by the |drag_image_offset| and and additional
48 // |vertical_offset|.
49 gfx::Rect AdjustDragImageBoundsForScaleAndOffset(
50 const gfx::Rect& drag_image_bounds,
51 int vertical_offset,
52 float scale,
53 gfx::Vector2d* drag_image_offset) {
54 gfx::PointF final_origin = drag_image_bounds.origin();
55 gfx::SizeF final_size = drag_image_bounds.size();
56 final_size.Scale(scale);
57 drag_image_offset->set_x(drag_image_offset->x() * scale);
58 drag_image_offset->set_y(drag_image_offset->y() * scale);
59 float total_x_offset = drag_image_offset->x();
60 float total_y_offset = drag_image_offset->y() - vertical_offset;
61 final_origin.Offset(-total_x_offset, -total_y_offset);
62 return gfx::ToEnclosingRect(gfx::RectF(final_origin, final_size));
65 void DispatchGestureEndToWindow(aura::Window* window) {
66 if (window && window->delegate()) {
67 ui::GestureEvent gesture_end(0,
70 ui::EventTimeForNow(),
71 ui::GestureEventDetails(ui::ET_GESTURE_END));
72 window->delegate()->OnGestureEvent(&gesture_end);
75 } // namespace
77 class DragDropTrackerDelegate : public aura::WindowDelegate {
78 public:
79 explicit DragDropTrackerDelegate(DragDropController* controller)
80 : drag_drop_controller_(controller) {}
81 ~DragDropTrackerDelegate() override {}
83 // Overridden from WindowDelegate:
84 gfx::Size GetMinimumSize() const override { return gfx::Size(); }
86 gfx::Size GetMaximumSize() const override { return gfx::Size(); }
88 void OnBoundsChanged(const gfx::Rect& old_bounds,
89 const gfx::Rect& new_bounds) override {}
90 gfx::NativeCursor GetCursor(const gfx::Point& point) override {
91 return gfx::kNullCursor;
93 int GetNonClientComponent(const gfx::Point& point) const override {
94 return HTCAPTION;
96 bool ShouldDescendIntoChildForEventHandling(
97 aura::Window* child,
98 const gfx::Point& location) override {
99 return true;
101 bool CanFocus() override { return true; }
102 void OnCaptureLost() override {
103 if (drag_drop_controller_->IsDragDropInProgress())
104 drag_drop_controller_->DragCancel();
106 void OnPaint(const ui::PaintContext& context) override {}
107 void OnDeviceScaleFactorChanged(float device_scale_factor) override {}
108 void OnWindowDestroying(aura::Window* window) override {}
109 void OnWindowDestroyed(aura::Window* window) override {}
110 void OnWindowTargetVisibilityChanged(bool visible) override {}
111 bool HasHitTestMask() const override { return true; }
112 void GetHitTestMask(gfx::Path* mask) const override {
113 DCHECK(mask->isEmpty());
116 private:
117 DragDropController* drag_drop_controller_;
119 DISALLOW_COPY_AND_ASSIGN(DragDropTrackerDelegate);
122 ////////////////////////////////////////////////////////////////////////////////
123 // DragDropController, public:
125 DragDropController::DragDropController()
126 : drag_data_(NULL),
127 drag_operation_(0),
128 drag_window_(NULL),
129 drag_source_window_(NULL),
130 should_block_during_drag_drop_(true),
131 drag_drop_window_delegate_(new DragDropTrackerDelegate(this)),
132 current_drag_event_source_(ui::DragDropTypes::DRAG_EVENT_SOURCE_MOUSE),
133 weak_factory_(this) {
134 Shell::GetInstance()->PrependPreTargetHandler(this);
137 DragDropController::~DragDropController() {
138 Shell::GetInstance()->RemovePreTargetHandler(this);
139 Cleanup();
140 if (cancel_animation_)
141 cancel_animation_->End();
142 if (drag_image_)
143 drag_image_.reset();
146 int DragDropController::StartDragAndDrop(
147 const ui::OSExchangeData& data,
148 aura::Window* root_window,
149 aura::Window* source_window,
150 const gfx::Point& screen_location,
151 int operation,
152 ui::DragDropTypes::DragEventSource source) {
153 if (IsDragDropInProgress())
154 return 0;
156 const ui::OSExchangeData::Provider* provider = &data.provider();
157 // We do not support touch drag/drop without a drag image.
158 if (source == ui::DragDropTypes::DRAG_EVENT_SOURCE_TOUCH &&
159 provider->GetDragImage().size().IsEmpty())
160 return 0;
162 UMA_HISTOGRAM_ENUMERATION("Event.DragDrop.Start", source,
163 ui::DragDropTypes::DRAG_EVENT_SOURCE_COUNT);
165 current_drag_event_source_ = source;
166 DragDropTracker* tracker =
167 new DragDropTracker(root_window, drag_drop_window_delegate_.get());
168 if (source == ui::DragDropTypes::DRAG_EVENT_SOURCE_TOUCH) {
169 // We need to transfer the current gesture sequence and the GR's touch event
170 // queue to the |drag_drop_tracker_|'s capture window so that when it takes
171 // capture, it still gets a valid gesture state.
172 ui::GestureRecognizer::Get()->TransferEventsTo(source_window,
173 tracker->capture_window());
174 // We also send a gesture end to the source window so it can clear state.
175 // TODO(varunjain): Remove this whole block when gesture sequence
176 // transferring is properly done in the GR (http://crbug.com/160558)
177 DispatchGestureEndToWindow(source_window);
179 tracker->TakeCapture();
180 drag_drop_tracker_.reset(tracker);
181 drag_source_window_ = source_window;
182 if (drag_source_window_)
183 drag_source_window_->AddObserver(this);
184 pending_long_tap_.reset();
186 drag_data_ = &data;
187 drag_operation_ = operation;
189 float drag_image_scale = 1;
190 int drag_image_vertical_offset = 0;
191 if (source == ui::DragDropTypes::DRAG_EVENT_SOURCE_TOUCH) {
192 drag_image_scale = kTouchDragImageScale;
193 drag_image_vertical_offset = kTouchDragImageVerticalOffset;
195 gfx::Point start_location = screen_location;
196 drag_image_final_bounds_for_cancel_animation_ = gfx::Rect(
197 start_location - provider->GetDragImageOffset(),
198 provider->GetDragImage().size());
199 drag_image_.reset(new DragImageView(source_window->GetRootWindow(), source));
200 drag_image_->SetImage(provider->GetDragImage());
201 drag_image_offset_ = provider->GetDragImageOffset();
202 gfx::Rect drag_image_bounds(start_location, drag_image_->GetPreferredSize());
203 drag_image_bounds = AdjustDragImageBoundsForScaleAndOffset(drag_image_bounds,
204 drag_image_vertical_offset, drag_image_scale, &drag_image_offset_);
205 drag_image_->SetBoundsInScreen(drag_image_bounds);
206 drag_image_->SetWidgetVisible(true);
207 if (source == ui::DragDropTypes::DRAG_EVENT_SOURCE_TOUCH) {
208 drag_image_->SetTouchDragOperationHintPosition(gfx::Point(
209 drag_image_offset_.x(),
210 drag_image_offset_.y() + drag_image_vertical_offset));
213 drag_window_ = NULL;
215 // Ends cancel animation if it's in progress.
216 if (cancel_animation_)
217 cancel_animation_->End();
219 if (should_block_during_drag_drop_) {
220 base::RunLoop run_loop;
221 quit_closure_ = run_loop.QuitClosure();
222 base::MessageLoopForUI* loop = base::MessageLoopForUI::current();
223 base::MessageLoop::ScopedNestableTaskAllower allow_nested(loop);
224 run_loop.Run();
227 if (drag_operation_ == 0) {
228 UMA_HISTOGRAM_ENUMERATION("Event.DragDrop.Cancel", source,
229 ui::DragDropTypes::DRAG_EVENT_SOURCE_COUNT);
230 } else {
231 UMA_HISTOGRAM_ENUMERATION("Event.DragDrop.Drop", source,
232 ui::DragDropTypes::DRAG_EVENT_SOURCE_COUNT);
235 if (!cancel_animation_.get() || !cancel_animation_->is_animating() ||
236 !pending_long_tap_.get()) {
237 // If drag cancel animation is running, this cleanup is done when the
238 // animation completes.
239 if (drag_source_window_)
240 drag_source_window_->RemoveObserver(this);
241 drag_source_window_ = NULL;
244 return drag_operation_;
247 void DragDropController::DragUpdate(aura::Window* target,
248 const ui::LocatedEvent& event) {
249 int op = ui::DragDropTypes::DRAG_NONE;
250 if (target != drag_window_) {
251 if (drag_window_) {
252 aura::client::DragDropDelegate* delegate =
253 aura::client::GetDragDropDelegate(drag_window_);
254 if (delegate)
255 delegate->OnDragExited();
256 if (drag_window_ != drag_source_window_)
257 drag_window_->RemoveObserver(this);
259 drag_window_ = target;
260 // We are already an observer of |drag_source_window_| so no need to add.
261 if (drag_window_ != drag_source_window_)
262 drag_window_->AddObserver(this);
263 aura::client::DragDropDelegate* delegate =
264 aura::client::GetDragDropDelegate(drag_window_);
265 if (delegate) {
266 ui::DropTargetEvent e(*drag_data_,
267 event.location(),
268 event.root_location(),
269 drag_operation_);
270 e.set_flags(event.flags());
271 delegate->OnDragEntered(e);
273 } else {
274 aura::client::DragDropDelegate* delegate =
275 aura::client::GetDragDropDelegate(drag_window_);
276 if (delegate) {
277 ui::DropTargetEvent e(*drag_data_,
278 event.location(),
279 event.root_location(),
280 drag_operation_);
281 e.set_flags(event.flags());
282 op = delegate->OnDragUpdated(e);
283 gfx::NativeCursor cursor = ui::kCursorNoDrop;
284 if (op & ui::DragDropTypes::DRAG_COPY)
285 cursor = ui::kCursorCopy;
286 else if (op & ui::DragDropTypes::DRAG_LINK)
287 cursor = ui::kCursorAlias;
288 else if (op & ui::DragDropTypes::DRAG_MOVE)
289 cursor = ui::kCursorGrabbing;
290 ash::Shell::GetInstance()->cursor_manager()->SetCursor(cursor);
294 DCHECK(drag_image_.get());
295 if (drag_image_->visible()) {
296 gfx::Point root_location_in_screen = event.root_location();
297 ::wm::ConvertPointToScreen(target->GetRootWindow(),
298 &root_location_in_screen);
299 drag_image_->SetScreenPosition(
300 root_location_in_screen - drag_image_offset_);
301 drag_image_->SetTouchDragOperation(op);
305 void DragDropController::Drop(aura::Window* target,
306 const ui::LocatedEvent& event) {
307 ash::Shell::GetInstance()->cursor_manager()->SetCursor(ui::kCursorPointer);
309 // We must guarantee that a target gets a OnDragEntered before Drop. WebKit
310 // depends on not getting a Drop without DragEnter. This behavior is
311 // consistent with drag/drop on other platforms.
312 if (target != drag_window_)
313 DragUpdate(target, event);
314 DCHECK(target == drag_window_);
316 aura::client::DragDropDelegate* delegate =
317 aura::client::GetDragDropDelegate(target);
318 if (delegate) {
319 ui::DropTargetEvent e(
320 *drag_data_, event.location(), event.root_location(), drag_operation_);
321 e.set_flags(event.flags());
322 drag_operation_ = delegate->OnPerformDrop(e);
323 if (drag_operation_ == 0)
324 StartCanceledAnimation(kCancelAnimationDuration);
325 else
326 drag_image_.reset();
327 } else {
328 drag_image_.reset();
331 Cleanup();
332 if (should_block_during_drag_drop_)
333 quit_closure_.Run();
336 void DragDropController::DragCancel() {
337 DoDragCancel(kCancelAnimationDuration);
340 bool DragDropController::IsDragDropInProgress() {
341 return !!drag_drop_tracker_.get();
344 void DragDropController::OnKeyEvent(ui::KeyEvent* event) {
345 if (IsDragDropInProgress() && event->key_code() == ui::VKEY_ESCAPE) {
346 DragCancel();
347 event->StopPropagation();
351 void DragDropController::OnMouseEvent(ui::MouseEvent* event) {
352 if (!IsDragDropInProgress())
353 return;
355 // If current drag session was not started by mouse, dont process this mouse
356 // event, but consume it so it does not interfere with current drag session.
357 if (current_drag_event_source_ !=
358 ui::DragDropTypes::DRAG_EVENT_SOURCE_MOUSE) {
359 event->StopPropagation();
360 return;
363 aura::Window* translated_target = drag_drop_tracker_->GetTarget(*event);
364 if (!translated_target) {
365 DragCancel();
366 event->StopPropagation();
367 return;
369 scoped_ptr<ui::LocatedEvent> translated_event(
370 drag_drop_tracker_->ConvertEvent(translated_target, *event));
371 switch (translated_event->type()) {
372 case ui::ET_MOUSE_DRAGGED:
373 DragUpdate(translated_target, *translated_event.get());
374 break;
375 case ui::ET_MOUSE_RELEASED:
376 Drop(translated_target, *translated_event.get());
377 break;
378 default:
379 // We could also reach here because RootWindow may sometimes generate a
380 // bunch of fake mouse events
381 // (aura::RootWindow::PostMouseMoveEventAfterWindowChange).
382 break;
384 event->StopPropagation();
387 void DragDropController::OnTouchEvent(ui::TouchEvent* event) {
388 if (!IsDragDropInProgress())
389 return;
391 // If current drag session was not started by touch, dont process this touch
392 // event, but consume it so it does not interfere with current drag session.
393 if (current_drag_event_source_ != ui::DragDropTypes::DRAG_EVENT_SOURCE_TOUCH)
394 event->StopPropagation();
396 if (event->handled())
397 return;
399 if (event->type() == ui::ET_TOUCH_CANCELLED)
400 DragCancel();
403 void DragDropController::OnGestureEvent(ui::GestureEvent* event) {
404 if (!IsDragDropInProgress())
405 return;
407 // No one else should handle gesture events when in drag drop. Note that it is
408 // not enough to just set ER_HANDLED because the dispatcher only stops
409 // dispatching when the event has ER_CONSUMED. If we just set ER_HANDLED, the
410 // event will still be dispatched to other handlers and we depend on
411 // individual handlers' kindness to not touch events marked ER_HANDLED (not
412 // all handlers are so kind and may cause bugs like crbug.com/236493).
413 event->StopPropagation();
415 // If current drag session was not started by touch, dont process this event.
416 if (current_drag_event_source_ != ui::DragDropTypes::DRAG_EVENT_SOURCE_TOUCH)
417 return;
419 // Apply kTouchDragImageVerticalOffset to the location.
420 ui::GestureEvent touch_offset_event(*event,
421 static_cast<aura::Window*>(NULL),
422 static_cast<aura::Window*>(NULL));
423 gfx::Point touch_offset_location = touch_offset_event.location();
424 gfx::Point touch_offset_root_location = touch_offset_event.root_location();
425 touch_offset_location.Offset(0, kTouchDragImageVerticalOffset);
426 touch_offset_root_location.Offset(0, kTouchDragImageVerticalOffset);
427 touch_offset_event.set_location(touch_offset_location);
428 touch_offset_event.set_root_location(touch_offset_root_location);
430 aura::Window* translated_target =
431 drag_drop_tracker_->GetTarget(touch_offset_event);
432 if (!translated_target) {
433 DragCancel();
434 event->SetHandled();
435 return;
437 scoped_ptr<ui::LocatedEvent> translated_event(
438 drag_drop_tracker_->ConvertEvent(translated_target, touch_offset_event));
440 switch (event->type()) {
441 case ui::ET_GESTURE_SCROLL_UPDATE:
442 DragUpdate(translated_target, *translated_event.get());
443 break;
444 case ui::ET_GESTURE_SCROLL_END:
445 case ui::ET_SCROLL_FLING_START:
446 Drop(translated_target, *translated_event.get());
447 break;
448 case ui::ET_GESTURE_LONG_TAP:
449 // Ideally we would want to just forward this long tap event to the
450 // |drag_source_window_|. However, webkit does not accept events while a
451 // drag drop is still in progress. The drag drop ends only when the nested
452 // message loop ends. Due to this stupidity, we have to defer forwarding
453 // the long tap.
454 pending_long_tap_.reset(
455 new ui::GestureEvent(*event,
456 static_cast<aura::Window*>(drag_drop_tracker_->capture_window()),
457 static_cast<aura::Window*>(drag_source_window_)));
458 DoDragCancel(kTouchCancelAnimationDuration);
459 break;
460 default:
461 break;
463 event->SetHandled();
466 void DragDropController::OnWindowDestroyed(aura::Window* window) {
467 if (drag_window_ == window)
468 drag_window_ = NULL;
469 if (drag_source_window_ == window)
470 drag_source_window_ = NULL;
473 ////////////////////////////////////////////////////////////////////////////////
474 // DragDropController, protected:
476 gfx::LinearAnimation* DragDropController::CreateCancelAnimation(
477 int duration,
478 int frame_rate,
479 gfx::AnimationDelegate* delegate) {
480 return new gfx::LinearAnimation(duration, frame_rate, delegate);
483 ////////////////////////////////////////////////////////////////////////////////
484 // DragDropController, private:
486 void DragDropController::AnimationEnded(const gfx::Animation* animation) {
487 cancel_animation_.reset();
489 // By the time we finish animation, another drag/drop session may have
490 // started. We do not want to destroy the drag image in that case.
491 if (!IsDragDropInProgress())
492 drag_image_.reset();
493 if (pending_long_tap_) {
494 // If not in a nested message loop, we can forward the long tap right now.
495 if (!should_block_during_drag_drop_) {
496 ForwardPendingLongTap();
497 } else {
498 // See comment about this in OnGestureEvent().
499 base::MessageLoopForUI::current()->PostTask(
500 FROM_HERE,
501 base::Bind(&DragDropController::ForwardPendingLongTap,
502 weak_factory_.GetWeakPtr()));
507 void DragDropController::DoDragCancel(int drag_cancel_animation_duration_ms) {
508 ash::Shell::GetInstance()->cursor_manager()->SetCursor(ui::kCursorPointer);
510 // |drag_window_| can be NULL if we have just started the drag and have not
511 // received any DragUpdates, or, if the |drag_window_| gets destroyed during
512 // a drag/drop.
513 aura::client::DragDropDelegate* delegate = drag_window_?
514 aura::client::GetDragDropDelegate(drag_window_) : NULL;
515 if (delegate)
516 delegate->OnDragExited();
518 Cleanup();
519 drag_operation_ = 0;
520 StartCanceledAnimation(drag_cancel_animation_duration_ms);
521 if (should_block_during_drag_drop_)
522 quit_closure_.Run();
525 void DragDropController::AnimationProgressed(const gfx::Animation* animation) {
526 gfx::Rect current_bounds = animation->CurrentValueBetween(
527 drag_image_initial_bounds_for_cancel_animation_,
528 drag_image_final_bounds_for_cancel_animation_);
529 drag_image_->SetBoundsInScreen(current_bounds);
532 void DragDropController::AnimationCanceled(const gfx::Animation* animation) {
533 AnimationEnded(animation);
536 void DragDropController::StartCanceledAnimation(int animation_duration_ms) {
537 DCHECK(drag_image_.get());
538 drag_image_->SetTouchDragOperationHintOff();
539 drag_image_initial_bounds_for_cancel_animation_ =
540 drag_image_->GetBoundsInScreen();
541 cancel_animation_.reset(CreateCancelAnimation(animation_duration_ms,
542 kCancelAnimationFrameRate,
543 this));
544 cancel_animation_->Start();
547 void DragDropController::ForwardPendingLongTap() {
548 if (drag_source_window_ && drag_source_window_->delegate()) {
549 drag_source_window_->delegate()->OnGestureEvent(pending_long_tap_.get());
550 DispatchGestureEndToWindow(drag_source_window_);
552 pending_long_tap_.reset();
553 if (drag_source_window_)
554 drag_source_window_->RemoveObserver(this);
555 drag_source_window_ = NULL;
558 void DragDropController::Cleanup() {
559 if (drag_window_)
560 drag_window_->RemoveObserver(this);
561 drag_window_ = NULL;
562 drag_data_ = NULL;
563 // Cleanup can be called again while deleting DragDropTracker, so delete
564 // the pointer with a local variable to avoid double free.
565 scoped_ptr<ash::DragDropTracker> holder = drag_drop_tracker_.Pass();
568 } // namespace ash