Upstream version 5.34.92.0
[platform/framework/web/crosswalk.git] / src / ash / wm / toplevel_window_event_handler.cc
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.
4
5 #include "ash/wm/toplevel_window_event_handler.h"
6
7 #include "ash/shell.h"
8 #include "ash/wm/resize_shadow_controller.h"
9 #include "ash/wm/window_resizer.h"
10 #include "ash/wm/window_state.h"
11 #include "ash/wm/window_state_observer.h"
12 #include "ash/wm/window_util.h"
13 #include "ash/wm/workspace/snap_sizer.h"
14 #include "base/message_loop/message_loop.h"
15 #include "base/run_loop.h"
16 #include "ui/aura/client/cursor_client.h"
17 #include "ui/aura/env.h"
18 #include "ui/aura/root_window.h"
19 #include "ui/aura/window.h"
20 #include "ui/aura/window_delegate.h"
21 #include "ui/aura/window_observer.h"
22 #include "ui/base/cursor/cursor.h"
23 #include "ui/base/hit_test.h"
24 #include "ui/base/ui_base_types.h"
25 #include "ui/events/event.h"
26 #include "ui/events/event_utils.h"
27 #include "ui/events/gestures/gesture_recognizer.h"
28 #include "ui/gfx/geometry/point_conversions.h"
29 #include "ui/gfx/screen.h"
30
31 namespace {
32 const double kMinHorizVelocityForWindowSwipe = 1100;
33 const double kMinVertVelocityForWindowMinimize = 1000;
34 }
35
36 namespace ash {
37
38 namespace {
39
40 // Returns whether |window| can be moved via a two finger drag given
41 // the hittest results of the two fingers.
42 bool CanStartTwoFingerMove(aura::Window* window,
43                            int window_component1,
44                            int window_component2) {
45   // We allow moving a window via two fingers when the hittest components are
46   // HTCLIENT. This is done so that a window can be dragged via two fingers when
47   // the tab strip is full and hitting the caption area is difficult. We check
48   // the window type and the show state so that we do not steal touches from the
49   // web contents.
50   if (!ash::wm::GetWindowState(window)->IsNormalShowState() ||
51       window->type() != ui::wm::WINDOW_TYPE_NORMAL) {
52     return false;
53   }
54   int component1_behavior =
55       WindowResizer::GetBoundsChangeForWindowComponent(window_component1);
56   int component2_behavior =
57       WindowResizer::GetBoundsChangeForWindowComponent(window_component2);
58   return (component1_behavior & WindowResizer::kBoundsChange_Resizes) == 0 &&
59       (component2_behavior & WindowResizer::kBoundsChange_Resizes) == 0;
60 }
61
62 // Returns whether |window| can be moved or resized via one finger given
63 // |window_component|.
64 bool CanStartOneFingerDrag(int window_component) {
65   return WindowResizer::GetBoundsChangeForWindowComponent(
66       window_component) != 0;
67 }
68
69 gfx::Point ConvertPointToParent(aura::Window* window,
70                                 const gfx::Point& point) {
71   gfx::Point result(point);
72   aura::Window::ConvertPointToTarget(window, window->parent(), &result);
73   return result;
74 }
75
76 // Returns the window component containing |event|'s location.
77 int GetWindowComponent(aura::Window* window, const ui::LocatedEvent& event) {
78   return window->delegate()->GetNonClientComponent(event.location());
79 }
80
81 }  // namespace
82
83 // ScopedWindowResizer ---------------------------------------------------------
84
85 // Wraps a WindowResizer and installs an observer on its target window.  When
86 // the window is destroyed ResizerWindowDestroyed() is invoked back on the
87 // ToplevelWindowEventHandler to clean up.
88 class ToplevelWindowEventHandler::ScopedWindowResizer
89     : public aura::WindowObserver,
90       public wm::WindowStateObserver {
91  public:
92   ScopedWindowResizer(ToplevelWindowEventHandler* handler,
93                       WindowResizer* resizer);
94   virtual ~ScopedWindowResizer();
95
96   // Returns true if the drag moves the window and does not resize.
97   bool IsMove() const;
98
99   WindowResizer* resizer() { return resizer_.get(); }
100
101   // WindowObserver overrides:
102   virtual void OnWindowHierarchyChanging(
103       const HierarchyChangeParams& params) OVERRIDE;
104   virtual void OnWindowDestroying(aura::Window* window) OVERRIDE;
105
106   // WindowStateObserver overrides:
107   virtual void OnWindowShowTypeChanged(wm::WindowState* window_state,
108                                        wm::WindowShowType type) OVERRIDE;
109
110  private:
111   ToplevelWindowEventHandler* handler_;
112   scoped_ptr<WindowResizer> resizer_;
113
114   DISALLOW_COPY_AND_ASSIGN(ScopedWindowResizer);
115 };
116
117 ToplevelWindowEventHandler::ScopedWindowResizer::ScopedWindowResizer(
118     ToplevelWindowEventHandler* handler,
119     WindowResizer* resizer)
120     : handler_(handler),
121       resizer_(resizer) {
122   resizer_->GetTarget()->AddObserver(this);
123   wm::GetWindowState(resizer_->GetTarget())->AddObserver(this);
124 }
125
126 ToplevelWindowEventHandler::ScopedWindowResizer::~ScopedWindowResizer() {
127   resizer_->GetTarget()->RemoveObserver(this);
128   wm::GetWindowState(resizer_->GetTarget())->RemoveObserver(this);
129 }
130
131 bool ToplevelWindowEventHandler::ScopedWindowResizer::IsMove() const {
132   return resizer_->details().bounds_change ==
133       WindowResizer::kBoundsChange_Repositions;
134 }
135
136 void ToplevelWindowEventHandler::ScopedWindowResizer::OnWindowHierarchyChanging(
137     const HierarchyChangeParams& params) {
138   if (params.receiver != resizer_->GetTarget())
139     return;
140   wm::WindowState* state = wm::GetWindowState(params.receiver);
141   if (state->continue_drag_after_reparent())
142     state->set_continue_drag_after_reparent(false);
143   else
144     handler_->CompleteDrag(DRAG_COMPLETE);
145 }
146
147 void ToplevelWindowEventHandler::ScopedWindowResizer::OnWindowShowTypeChanged(
148     wm::WindowState* window_state,
149     wm::WindowShowType old) {
150   if (!window_state->IsNormalShowState())
151     handler_->CompleteDrag(DRAG_COMPLETE);
152 }
153
154 void ToplevelWindowEventHandler::ScopedWindowResizer::OnWindowDestroying(
155     aura::Window* window) {
156   DCHECK_EQ(resizer_->GetTarget(), window);
157   handler_->ResizerWindowDestroyed();
158 }
159
160 // ToplevelWindowEventHandler --------------------------------------------------
161
162 ToplevelWindowEventHandler::ToplevelWindowEventHandler()
163     : first_finger_hittest_(HTNOWHERE),
164       in_move_loop_(false),
165       in_gesture_drag_(false),
166       drag_reverted_(false),
167       destroyed_(NULL) {
168   Shell::GetInstance()->display_controller()->AddObserver(this);
169 }
170
171 ToplevelWindowEventHandler::~ToplevelWindowEventHandler() {
172   Shell::GetInstance()->display_controller()->RemoveObserver(this);
173   if (destroyed_)
174     *destroyed_ = true;
175 }
176
177 void ToplevelWindowEventHandler::OnKeyEvent(ui::KeyEvent* event) {
178   if (window_resizer_.get() && event->type() == ui::ET_KEY_PRESSED &&
179       event->key_code() == ui::VKEY_ESCAPE) {
180     CompleteDrag(DRAG_REVERT);
181   }
182 }
183
184 void ToplevelWindowEventHandler::OnMouseEvent(
185     ui::MouseEvent* event) {
186   if ((event->flags() &
187       (ui::EF_MIDDLE_MOUSE_BUTTON | ui::EF_RIGHT_MOUSE_BUTTON)) != 0)
188     return;
189
190   if (in_gesture_drag_)
191     return;
192
193   aura::Window* target = static_cast<aura::Window*>(event->target());
194   switch (event->type()) {
195     case ui::ET_MOUSE_PRESSED:
196       HandleMousePressed(target, event);
197       break;
198     case ui::ET_MOUSE_DRAGGED:
199       HandleDrag(target, event);
200       break;
201     case ui::ET_MOUSE_CAPTURE_CHANGED:
202     case ui::ET_MOUSE_RELEASED:
203       HandleMouseReleased(target, event);
204       break;
205     case ui::ET_MOUSE_MOVED:
206       HandleMouseMoved(target, event);
207       break;
208     case ui::ET_MOUSE_EXITED:
209       HandleMouseExited(target, event);
210       break;
211     default:
212       break;
213   }
214 }
215
216 void ToplevelWindowEventHandler::OnGestureEvent(ui::GestureEvent* event) {
217   aura::Window* target = static_cast<aura::Window*>(event->target());
218   if (!target->delegate())
219     return;
220
221   if (window_resizer_.get() && !in_gesture_drag_)
222     return;
223
224   if (window_resizer_.get() &&
225       window_resizer_->resizer()->GetTarget() != target) {
226     return;
227   }
228
229   if (event->details().touch_points() > 2) {
230     if (window_resizer_.get()) {
231       CompleteDrag(DRAG_COMPLETE);
232       event->StopPropagation();
233     }
234     return;
235   }
236
237   switch (event->type()) {
238     case ui::ET_GESTURE_TAP_DOWN: {
239       int component = GetWindowComponent(target, *event);
240       if (!(WindowResizer::GetBoundsChangeForWindowComponent(component) &
241             WindowResizer::kBoundsChange_Resizes))
242         return;
243       internal::ResizeShadowController* controller =
244           Shell::GetInstance()->resize_shadow_controller();
245       if (controller)
246         controller->ShowShadow(target, component);
247       return;
248     }
249     case ui::ET_GESTURE_END: {
250       internal::ResizeShadowController* controller =
251           Shell::GetInstance()->resize_shadow_controller();
252       if (controller)
253         controller->HideShadow(target);
254
255       if (window_resizer_.get() &&
256           (event->details().touch_points() == 1 ||
257            !CanStartOneFingerDrag(first_finger_hittest_))) {
258         CompleteDrag(DRAG_COMPLETE);
259         event->StopPropagation();
260       }
261       return;
262     }
263     case ui::ET_GESTURE_BEGIN: {
264       if (event->details().touch_points() == 1) {
265         first_finger_hittest_ = GetWindowComponent(target, *event);
266       } else if (window_resizer_.get()) {
267         if (!window_resizer_->IsMove()) {
268           // The transition from resizing with one finger to resizing with two
269           // fingers causes unintended resizing because the location of
270           // ET_GESTURE_SCROLL_UPDATE jumps from the position of the first
271           // finger to the position in the middle of the two fingers. For this
272           // reason two finger resizing is not supported.
273           CompleteDrag(DRAG_COMPLETE);
274           event->StopPropagation();
275         }
276       } else {
277         int second_finger_hittest = GetWindowComponent(target, *event);
278         if (CanStartTwoFingerMove(
279                 target, first_finger_hittest_, second_finger_hittest)) {
280           gfx::Point location_in_parent =
281               event->details().bounding_box().CenterPoint();
282           AttemptToStartDrag(target, location_in_parent, HTCAPTION,
283                              aura::client::WINDOW_MOVE_SOURCE_TOUCH);
284           event->StopPropagation();
285         }
286       }
287       return;
288     }
289     case ui::ET_GESTURE_SCROLL_BEGIN: {
290       // The one finger drag is not started in ET_GESTURE_BEGIN to avoid the
291       // window jumping upon initiating a two finger drag. When a one finger
292       // drag is converted to a two finger drag, a jump occurs because the
293       // location of the ET_GESTURE_SCROLL_UPDATE event switches from the single
294       // finger's position to the position in the middle of the two fingers.
295       if (window_resizer_.get())
296         return;
297       int component = GetWindowComponent(target, *event);
298       if (!CanStartOneFingerDrag(component))
299         return;
300       gfx::Point location_in_parent(
301           ConvertPointToParent(target, event->location()));
302       AttemptToStartDrag(target, location_in_parent, component,
303                          aura::client::WINDOW_MOVE_SOURCE_TOUCH);
304       event->StopPropagation();
305       return;
306     }
307     default:
308       break;
309   }
310
311   if (!window_resizer_.get())
312     return;
313
314   switch (event->type()) {
315     case ui::ET_GESTURE_SCROLL_UPDATE:
316       HandleDrag(target, event);
317       event->StopPropagation();
318       return;
319     case ui::ET_GESTURE_SCROLL_END:
320       // We must complete the drag here instead of as a result of ET_GESTURE_END
321       // because otherwise the drag will be reverted when EndMoveLoop() is
322       // called.
323       // TODO(pkotwicz): Pass drag completion status to
324       // WindowMoveClient::EndMoveLoop().
325       CompleteDrag(DRAG_COMPLETE);
326       event->StopPropagation();
327       return;
328     case ui::ET_SCROLL_FLING_START:
329       CompleteDrag(DRAG_COMPLETE);
330
331       // TODO(pkotwicz): Fix tests which inadvertantly start flings and check
332       // window_resizer_->IsMove() instead of the hittest component at |event|'s
333       // location.
334       if (GetWindowComponent(target, *event) != HTCAPTION ||
335           !wm::GetWindowState(target)->IsNormalShowState()) {
336         return;
337       }
338
339       if (event->details().velocity_y() > kMinVertVelocityForWindowMinimize) {
340         SetWindowShowTypeFromGesture(target, wm::SHOW_TYPE_MINIMIZED);
341       } else if (event->details().velocity_y() <
342                  -kMinVertVelocityForWindowMinimize) {
343         SetWindowShowTypeFromGesture(target, wm::SHOW_TYPE_MAXIMIZED);
344       } else if (event->details().velocity_x() >
345                  kMinHorizVelocityForWindowSwipe) {
346         SetWindowShowTypeFromGesture(target, wm::SHOW_TYPE_RIGHT_SNAPPED);
347       } else if (event->details().velocity_x() <
348                  -kMinHorizVelocityForWindowSwipe) {
349         SetWindowShowTypeFromGesture(target, wm::SHOW_TYPE_LEFT_SNAPPED);
350       }
351       event->StopPropagation();
352       return;
353     case ui::ET_GESTURE_MULTIFINGER_SWIPE:
354       if (!wm::GetWindowState(target)->IsNormalShowState())
355         return;
356
357       CompleteDrag(DRAG_COMPLETE);
358
359       if (event->details().swipe_down())
360         SetWindowShowTypeFromGesture(target, wm::SHOW_TYPE_MINIMIZED);
361       else if (event->details().swipe_up())
362         SetWindowShowTypeFromGesture(target, wm::SHOW_TYPE_MAXIMIZED);
363       else if (event->details().swipe_right())
364         SetWindowShowTypeFromGesture(target, wm::SHOW_TYPE_RIGHT_SNAPPED);
365       else
366         SetWindowShowTypeFromGesture(target, wm::SHOW_TYPE_LEFT_SNAPPED);
367       event->StopPropagation();
368       return;
369     default:
370       return;
371   }
372 }
373
374 aura::client::WindowMoveResult ToplevelWindowEventHandler::RunMoveLoop(
375     aura::Window* source,
376     const gfx::Vector2d& drag_offset,
377     aura::client::WindowMoveSource move_source) {
378   DCHECK(!in_move_loop_);  // Can only handle one nested loop at a time.
379   aura::Window* root_window = source->GetRootWindow();
380   DCHECK(root_window);
381   // TODO(tdresser): Use gfx::PointF. See crbug.com/337824.
382   gfx::Point drag_location;
383   if (move_source == aura::client::WINDOW_MOVE_SOURCE_TOUCH &&
384       aura::Env::GetInstance()->is_touch_down()) {
385     gfx::PointF drag_location_f;
386     bool has_point = ui::GestureRecognizer::Get()->
387         GetLastTouchPointForTarget(source, &drag_location_f);
388     drag_location = gfx::ToFlooredPoint(drag_location_f);
389     DCHECK(has_point);
390   } else {
391     drag_location = root_window->GetDispatcher()->GetLastMouseLocationInRoot();
392     aura::Window::ConvertPointToTarget(
393         root_window, source->parent(), &drag_location);
394   }
395   // Set the cursor before calling AttemptToStartDrag(), as that will
396   // eventually call LockCursor() and prevent the cursor from changing.
397   aura::client::CursorClient* cursor_client =
398       aura::client::GetCursorClient(root_window);
399   if (cursor_client)
400     cursor_client->SetCursor(ui::kCursorPointer);
401   if (!AttemptToStartDrag(source, drag_location, HTCAPTION, move_source))
402     return aura::client::MOVE_CANCELED;
403
404   in_move_loop_ = true;
405   bool destroyed = false;
406   destroyed_ = &destroyed;
407   base::MessageLoopForUI* loop = base::MessageLoopForUI::current();
408   base::MessageLoop::ScopedNestableTaskAllower allow_nested(loop);
409   base::RunLoop run_loop(aura::Env::GetInstance()->GetDispatcher());
410   quit_closure_ = run_loop.QuitClosure();
411   run_loop.Run();
412   if (destroyed)
413     return aura::client::MOVE_CANCELED;
414   destroyed_ = NULL;
415   in_move_loop_ = false;
416   return drag_reverted_ ? aura::client::MOVE_CANCELED :
417       aura::client::MOVE_SUCCESSFUL;
418 }
419
420 void ToplevelWindowEventHandler::EndMoveLoop() {
421   if (in_move_loop_)
422     CompleteDrag(DRAG_REVERT);
423 }
424
425 void ToplevelWindowEventHandler::OnDisplayConfigurationChanging() {
426   CompleteDrag(DRAG_REVERT);
427 }
428
429 bool ToplevelWindowEventHandler::AttemptToStartDrag(
430     aura::Window* window,
431     const gfx::Point& point_in_parent,
432     int window_component,
433     aura::client::WindowMoveSource source) {
434   if (window_resizer_.get())
435     return false;
436   WindowResizer* resizer = CreateWindowResizer(window, point_in_parent,
437       window_component, source).release();
438   if (!resizer)
439     return false;
440
441   window_resizer_.reset(new ScopedWindowResizer(this, resizer));
442
443   pre_drag_window_bounds_ = window->bounds();
444   in_gesture_drag_ = (source == aura::client::WINDOW_MOVE_SOURCE_TOUCH);
445   return true;
446 }
447
448 void ToplevelWindowEventHandler::CompleteDrag(DragCompletionStatus status) {
449   scoped_ptr<ScopedWindowResizer> resizer(window_resizer_.release());
450   if (resizer) {
451     if (status == DRAG_COMPLETE)
452       resizer->resizer()->CompleteDrag();
453     else
454       resizer->resizer()->RevertDrag();
455   }
456   drag_reverted_ = (status == DRAG_REVERT);
457
458   first_finger_hittest_ = HTNOWHERE;
459   in_gesture_drag_ = false;
460   if (in_move_loop_)
461     quit_closure_.Run();
462 }
463
464 void ToplevelWindowEventHandler::HandleMousePressed(
465     aura::Window* target,
466     ui::MouseEvent* event) {
467   if (event->phase() != ui::EP_PRETARGET)
468     return;
469
470   // We also update the current window component here because for the
471   // mouse-drag-release-press case, where the mouse is released and
472   // pressed without mouse move event.
473   int component = GetWindowComponent(target, *event);
474   if ((event->flags() &
475         (ui::EF_IS_DOUBLE_CLICK | ui::EF_IS_TRIPLE_CLICK)) == 0 &&
476       WindowResizer::GetBoundsChangeForWindowComponent(component)) {
477     gfx::Point location_in_parent(
478         ConvertPointToParent(target, event->location()));
479     AttemptToStartDrag(target, location_in_parent, component,
480                        aura::client::WINDOW_MOVE_SOURCE_MOUSE);
481     event->StopPropagation();
482   } else {
483     CompleteDrag(DRAG_COMPLETE);
484   }
485 }
486
487 void ToplevelWindowEventHandler::HandleMouseReleased(
488     aura::Window* target,
489     ui::MouseEvent* event) {
490   if (event->phase() != ui::EP_PRETARGET)
491     return;
492
493   CompleteDrag(event->type() == ui::ET_MOUSE_RELEASED ?
494                    DRAG_COMPLETE : DRAG_REVERT);
495   // Completing the drag may result in hiding the window. If this happens
496   // return true so no other handlers/observers see the event. Otherwise
497   // they see the event on a hidden window.
498   if (event->type() == ui::ET_MOUSE_CAPTURE_CHANGED &&
499       !target->IsVisible()) {
500     event->StopPropagation();
501   }
502 }
503
504 void ToplevelWindowEventHandler::HandleDrag(
505     aura::Window* target,
506     ui::LocatedEvent* event) {
507   // This function only be triggered to move window
508   // by mouse drag or touch move event.
509   DCHECK(event->type() == ui::ET_MOUSE_DRAGGED ||
510          event->type() == ui::ET_TOUCH_MOVED ||
511          event->type() == ui::ET_GESTURE_SCROLL_UPDATE);
512
513   // Drag actions are performed pre-target handling to prevent spurious mouse
514   // moves from the move/size operation from being sent to the target.
515   if (event->phase() != ui::EP_PRETARGET)
516     return;
517
518   if (!window_resizer_)
519     return;
520   window_resizer_->resizer()->Drag(
521       ConvertPointToParent(target, event->location()), event->flags());
522   event->StopPropagation();
523 }
524
525 void ToplevelWindowEventHandler::HandleMouseMoved(
526     aura::Window* target,
527     ui::LocatedEvent* event) {
528   // Shadow effects are applied after target handling. Note that we don't
529   // respect ER_HANDLED here right now since we have not had a reason to allow
530   // the target to cancel shadow rendering.
531   if (event->phase() != ui::EP_POSTTARGET)
532     return;
533
534   // TODO(jamescook): Move the resize cursor update code into here from
535   // CompoundEventFilter?
536   internal::ResizeShadowController* controller =
537       Shell::GetInstance()->resize_shadow_controller();
538   if (controller) {
539     if (event->flags() & ui::EF_IS_NON_CLIENT) {
540       int component =
541           target->delegate()->GetNonClientComponent(event->location());
542       controller->ShowShadow(target, component);
543     } else {
544       controller->HideShadow(target);
545     }
546   }
547 }
548
549 void ToplevelWindowEventHandler::HandleMouseExited(
550     aura::Window* target,
551     ui::LocatedEvent* event) {
552   // Shadow effects are applied after target handling. Note that we don't
553   // respect ER_HANDLED here right now since we have not had a reason to allow
554   // the target to cancel shadow rendering.
555   if (event->phase() != ui::EP_POSTTARGET)
556     return;
557
558   internal::ResizeShadowController* controller =
559       Shell::GetInstance()->resize_shadow_controller();
560   if (controller)
561     controller->HideShadow(target);
562 }
563
564 void ToplevelWindowEventHandler::SetWindowShowTypeFromGesture(
565     aura::Window* window,
566     wm::WindowShowType new_show_type) {
567   wm::WindowState* window_state = ash::wm::GetWindowState(window);
568   switch (new_show_type) {
569     case wm::SHOW_TYPE_MINIMIZED:
570       if (window_state->CanMinimize()) {
571         window_state->Minimize();
572         window_state->set_always_restores_to_restore_bounds(true);
573         window_state->SetRestoreBoundsInParent(pre_drag_window_bounds_);
574       }
575       break;
576     case wm::SHOW_TYPE_MAXIMIZED:
577       if (window_state->CanMaximize()) {
578         window_state->SetRestoreBoundsInParent(pre_drag_window_bounds_);
579         window_state->Maximize();
580       }
581       break;
582     case wm::SHOW_TYPE_LEFT_SNAPPED:
583       if (window_state->CanSnap()) {
584         window_state->SetRestoreBoundsInParent(pre_drag_window_bounds_);
585         internal::SnapSizer::SnapWindow(window_state,
586                                         internal::SnapSizer::LEFT_EDGE);
587       }
588       break;
589     case wm::SHOW_TYPE_RIGHT_SNAPPED:
590       if (window_state->CanSnap()) {
591         window_state->SetRestoreBoundsInParent(pre_drag_window_bounds_);
592         internal::SnapSizer::SnapWindow(window_state,
593                                         internal::SnapSizer::RIGHT_EDGE);
594       }
595       break;
596     default:
597       NOTREACHED();
598   }
599 }
600
601 void ToplevelWindowEventHandler::ResizerWindowDestroyed() {
602   // We explicitly don't invoke RevertDrag() since that may do things to window.
603   // Instead we destroy the resizer.
604   window_resizer_.reset();
605
606   CompleteDrag(DRAG_REVERT);
607 }
608
609 }  // namespace ash