- add sources.
[platform/framework/web/crosswalk.git] / src / ash / wm / overview / window_overview.cc
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.
4
5 #include "ash/wm/overview/window_overview.h"
6
7 #include <algorithm>
8
9 #include "ash/screen_ash.h"
10 #include "ash/shell.h"
11 #include "ash/shell_delegate.h"
12 #include "ash/shell_window_ids.h"
13 #include "ash/wm/mru_window_tracker.h"
14 #include "ash/wm/overview/scoped_transform_overview_window.h"
15 #include "ash/wm/overview/window_selector.h"
16 #include "ash/wm/overview/window_selector_item.h"
17 #include "base/metrics/histogram.h"
18 #include "third_party/skia/include/core/SkColor.h"
19 #include "ui/aura/client/cursor_client.h"
20 #include "ui/aura/root_window.h"
21 #include "ui/aura/window.h"
22 #include "ui/compositor/scoped_layer_animation_settings.h"
23 #include "ui/events/event.h"
24 #include "ui/views/widget/widget.h"
25
26 namespace ash {
27
28 namespace {
29
30 // Conceptually the window overview is a table or grid of cells having this
31 // fixed aspect ratio. The number of columns is determined by maximizing the
32 // area of them based on the number of windows.
33 const float kCardAspectRatio = 4.0f / 3.0f;
34
35 // In the conceptual overview table, the window margin is the space reserved
36 // around the window within the cell. This margin does not overlap so the
37 // closest distance between adjacent windows will be twice this amount.
38 const int kWindowMargin = 30;
39
40 // The minimum number of cards along the major axis (i.e. horizontally on a
41 // landscape orientation).
42 const int kMinCardsMajor = 3;
43
44 // The duration of transition animations on the overview selector.
45 const int kOverviewSelectorTransitionMilliseconds = 100;
46
47 // The color and opacity of the overview selector.
48 const SkColor kWindowOverviewSelectionColor = SK_ColorBLACK;
49 const float kWindowOverviewSelectionOpacity = 0.5f;
50
51 // The padding or amount of the window selector widget visible around the edges
52 // of the currently selected window.
53 const int kWindowOverviewSelectionPadding = 25;
54
55 // A comparator for locating a given target window.
56 struct WindowSelectorItemComparator
57     : public std::unary_function<WindowSelectorItem*, bool> {
58   explicit WindowSelectorItemComparator(const aura::Window* target_window)
59       : target(target_window) {
60   }
61
62   bool operator()(WindowSelectorItem* window) const {
63     return window->TargetedWindow(target) != NULL;
64   }
65
66   const aura::Window* target;
67 };
68
69 // An observer which holds onto the passed widget until the animation is
70 // complete.
71 class CleanupWidgetAfterAnimationObserver : public ui::LayerAnimationObserver {
72  public:
73   explicit CleanupWidgetAfterAnimationObserver(
74       scoped_ptr<views::Widget> widget);
75
76   // ui::LayerAnimationObserver:
77   virtual void OnLayerAnimationEnded(
78       ui::LayerAnimationSequence* sequence) OVERRIDE;
79   virtual void OnLayerAnimationAborted(
80       ui::LayerAnimationSequence* sequence) OVERRIDE;
81   virtual void OnLayerAnimationScheduled(
82       ui::LayerAnimationSequence* sequence) OVERRIDE;
83
84  private:
85   virtual ~CleanupWidgetAfterAnimationObserver();
86
87   scoped_ptr<views::Widget> widget_;
88
89   DISALLOW_COPY_AND_ASSIGN(CleanupWidgetAfterAnimationObserver);
90 };
91
92 CleanupWidgetAfterAnimationObserver::CleanupWidgetAfterAnimationObserver(
93     scoped_ptr<views::Widget> widget)
94     : widget_(widget.Pass()) {
95   widget_->GetNativeWindow()->layer()->GetAnimator()->AddObserver(this);
96 }
97
98 CleanupWidgetAfterAnimationObserver::~CleanupWidgetAfterAnimationObserver() {
99   widget_->GetNativeWindow()->layer()->GetAnimator()->RemoveObserver(this);
100 }
101
102 void CleanupWidgetAfterAnimationObserver::OnLayerAnimationEnded(
103     ui::LayerAnimationSequence* sequence) {
104   delete this;
105 }
106
107 void CleanupWidgetAfterAnimationObserver::OnLayerAnimationAborted(
108     ui::LayerAnimationSequence* sequence) {
109   delete this;
110 }
111
112 void CleanupWidgetAfterAnimationObserver::OnLayerAnimationScheduled(
113     ui::LayerAnimationSequence* sequence) {
114 }
115
116 }  // namespace
117
118 WindowOverview::WindowOverview(WindowSelector* window_selector,
119                                WindowSelectorItemList* windows,
120                                aura::Window* single_root_window)
121     : window_selector_(window_selector),
122       windows_(windows),
123       selection_index_(0),
124       single_root_window_(single_root_window),
125       overview_start_time_(base::Time::Now()),
126       cursor_client_(NULL) {
127   for (WindowSelectorItemList::iterator iter = windows_->begin();
128        iter != windows_->end(); ++iter) {
129     (*iter)->PrepareForOverview();
130   }
131   PositionWindows();
132   DCHECK(!windows_->empty());
133   cursor_client_ = aura::client::GetCursorClient(
134       windows_->front()->GetRootWindow());
135   if (cursor_client_) {
136     cursor_client_->SetCursor(ui::kCursorPointer);
137     cursor_client_->ShowCursor();
138     // TODO(flackr): Only prevent cursor changes for windows in the overview.
139     // This will be easier to do without exposing the overview mode code if the
140     // cursor changes are moved to ToplevelWindowEventHandler::HandleMouseMoved
141     // as suggested there.
142     cursor_client_->LockCursor();
143   }
144   ash::Shell::GetInstance()->PrependPreTargetHandler(this);
145   Shell* shell = Shell::GetInstance();
146   shell->delegate()->RecordUserMetricsAction(UMA_WINDOW_OVERVIEW);
147   HideAndTrackNonOverviewWindows();
148 }
149
150 WindowOverview::~WindowOverview() {
151   const aura::WindowTracker::Windows hidden_windows = hidden_windows_.windows();
152   for (aura::WindowTracker::Windows::const_iterator iter =
153        hidden_windows.begin(); iter != hidden_windows.end(); ++iter) {
154     ui::ScopedLayerAnimationSettings settings(
155         (*iter)->layer()->GetAnimator());
156     settings.SetTransitionDuration(base::TimeDelta::FromMilliseconds(
157         ScopedTransformOverviewWindow::kTransitionMilliseconds));
158     settings.SetPreemptionStrategy(
159         ui::LayerAnimator::IMMEDIATELY_ANIMATE_TO_NEW_TARGET);
160     (*iter)->Show();
161     (*iter)->layer()->SetOpacity(1);
162   }
163   if (cursor_client_)
164     cursor_client_->UnlockCursor();
165   ash::Shell::GetInstance()->RemovePreTargetHandler(this);
166   UMA_HISTOGRAM_MEDIUM_TIMES(
167       "Ash.WindowSelector.TimeInOverview",
168       base::Time::Now() - overview_start_time_);
169 }
170
171 void WindowOverview::SetSelection(size_t index) {
172   gfx::Rect target_bounds(GetSelectionBounds(index));
173
174   if (selection_widget_) {
175     // If the selection widget is already active, determine the animation to
176     // use to animate the widget to the new bounds.
177     int change = static_cast<int>(index) - static_cast<int>(selection_index_);
178     int windows = static_cast<int>(windows_->size());
179     // If moving from the first to the last or last to the first index,
180     // convert the delta to be +/- 1.
181     if (windows > 2 && abs(change) == windows - 1) {
182       if (change < 0)
183         change += windows;
184       else
185         change -= windows;
186     }
187     if (selection_index_ < windows_->size() &&
188         (*windows_)[selection_index_]->target_bounds().y() !=
189             (*windows_)[index]->target_bounds().y() &&
190         abs(change) == 1) {
191       // The selection has changed forward or backwards by one with a change
192       // in the height of the target. In this case create a new selection widget
193       // to fade in on the new position and animate and fade out the old one.
194       gfx::Display dst_display = gfx::Screen::GetScreenFor(
195           selection_widget_->GetNativeWindow())->GetDisplayMatching(
196               target_bounds);
197       gfx::Vector2d fade_out_direction(
198           change * ((*windows_)[selection_index_]->target_bounds().width() +
199                     2 * kWindowMargin), 0);
200       aura::Window* old_selection = selection_widget_->GetNativeWindow();
201
202       // CleanupWidgetAfterAnimationObserver will delete itself (and the
203       // widget) when the animation is complete.
204       new CleanupWidgetAfterAnimationObserver(selection_widget_.Pass());
205       ui::ScopedLayerAnimationSettings animation_settings(
206           old_selection->layer()->GetAnimator());
207       animation_settings.SetTransitionDuration(
208           base::TimeDelta::FromMilliseconds(
209               kOverviewSelectorTransitionMilliseconds));
210       animation_settings.SetPreemptionStrategy(
211           ui::LayerAnimator::IMMEDIATELY_ANIMATE_TO_NEW_TARGET);
212       old_selection->SetBoundsInScreen(
213           GetSelectionBounds(selection_index_) + fade_out_direction,
214           dst_display);
215       old_selection->layer()->SetOpacity(0);
216       InitializeSelectionWidget();
217       selection_widget_->GetNativeWindow()->SetBoundsInScreen(
218           target_bounds - fade_out_direction, dst_display);
219     }
220     ui::ScopedLayerAnimationSettings animation_settings(
221         selection_widget_->GetNativeWindow()->layer()->GetAnimator());
222     animation_settings.SetTransitionDuration(base::TimeDelta::FromMilliseconds(
223         kOverviewSelectorTransitionMilliseconds));
224     animation_settings.SetPreemptionStrategy(
225         ui::LayerAnimator::IMMEDIATELY_ANIMATE_TO_NEW_TARGET);
226     selection_widget_->SetBounds(target_bounds);
227     selection_widget_->GetNativeWindow()->layer()->SetOpacity(
228         kWindowOverviewSelectionOpacity);
229   } else {
230     InitializeSelectionWidget();
231     selection_widget_->SetBounds(target_bounds);
232     selection_widget_->GetNativeWindow()->layer()->SetOpacity(
233         kWindowOverviewSelectionOpacity);
234   }
235   selection_index_ = index;
236 }
237
238 void WindowOverview::OnWindowsChanged() {
239   PositionWindows();
240 }
241
242 void WindowOverview::MoveToSingleRootWindow(aura::Window* root_window) {
243   single_root_window_ = root_window;
244   PositionWindows();
245 }
246
247 void WindowOverview::OnKeyEvent(ui::KeyEvent* event) {
248   if (GetTargetedWindow(static_cast<aura::Window*>(event->target())))
249     event->StopPropagation();
250   if (event->type() != ui::ET_KEY_PRESSED)
251     return;
252
253   if (event->key_code() == ui::VKEY_ESCAPE)
254     window_selector_->CancelSelection();
255 }
256
257 void WindowOverview::OnMouseEvent(ui::MouseEvent* event) {
258   aura::Window* target = GetEventTarget(event);
259   if (!target)
260     return;
261
262   event->StopPropagation();
263   if (event->type() != ui::ET_MOUSE_RELEASED)
264     return;
265
266   window_selector_->SelectWindow(target);
267 }
268
269 void WindowOverview::OnScrollEvent(ui::ScrollEvent* event) {
270   // Set the handled flag to prevent delivering scroll events to the window but
271   // still allowing other pretarget handlers to process the scroll event.
272   if (GetTargetedWindow(static_cast<aura::Window*>(event->target())))
273     event->SetHandled();
274 }
275
276 void WindowOverview::OnTouchEvent(ui::TouchEvent* event) {
277   // Existing touches should be allowed to continue. This prevents getting
278   // stuck in a gesture or with pressed fingers being tracked elsewhere.
279   if (event->type() != ui::ET_TOUCH_PRESSED)
280     return;
281
282   aura::Window* target = GetEventTarget(event);
283   if (!target)
284     return;
285
286   // TODO(flackr): StopPropogation prevents generation of gesture events.
287   // We should find a better way to prevent events from being delivered to
288   // the window, perhaps a transparent window in front of the target window
289   // or using EventClientImpl::CanProcessEventsWithinSubtree and then a tap
290   // gesture could be used to activate the window.
291   event->SetHandled();
292   window_selector_->SelectWindow(target);
293 }
294
295 aura::Window* WindowOverview::GetEventTarget(ui::LocatedEvent* event) {
296   aura::Window* target = static_cast<aura::Window*>(event->target());
297   // If the target window doesn't actually contain the event location (i.e.
298   // mouse down over the window and mouse up elsewhere) then do not select the
299   // window.
300   if (!target->HitTest(event->location()))
301     return NULL;
302
303   return GetTargetedWindow(target);
304 }
305
306 aura::Window* WindowOverview::GetTargetedWindow(aura::Window* window) {
307   for (WindowSelectorItemList::iterator iter = windows_->begin();
308        iter != windows_->end(); ++iter) {
309     aura::Window* selected = (*iter)->TargetedWindow(window);
310     if (selected)
311       return selected;
312   }
313   return NULL;
314 }
315
316 void WindowOverview::HideAndTrackNonOverviewWindows() {
317   Shell::RootWindowList root_windows = Shell::GetAllRootWindows();
318   for (Shell::RootWindowList::const_iterator root_iter = root_windows.begin();
319        root_iter != root_windows.end(); ++root_iter) {
320     for (size_t i = 0; i < kSwitchableWindowContainerIdsLength; ++i) {
321       aura::Window* container = Shell::GetContainer(*root_iter,
322           kSwitchableWindowContainerIds[i]);
323       // Copy the children list as it can change during iteration.
324       aura::Window::Windows children(container->children());
325       for (aura::Window::Windows::const_iterator iter = children.begin();
326            iter != children.end(); ++iter) {
327         if (GetTargetedWindow(*iter) || !(*iter)->IsVisible())
328           continue;
329         ui::ScopedLayerAnimationSettings settings(
330             (*iter)->layer()->GetAnimator());
331         settings.SetTransitionDuration(base::TimeDelta::FromMilliseconds(
332             ScopedTransformOverviewWindow::kTransitionMilliseconds));
333         settings.SetPreemptionStrategy(
334             ui::LayerAnimator::IMMEDIATELY_ANIMATE_TO_NEW_TARGET);
335         (*iter)->Hide();
336         (*iter)->layer()->SetOpacity(0);
337         hidden_windows_.Add(*iter);
338       }
339     }
340   }
341 }
342
343 void WindowOverview::PositionWindows() {
344   if (single_root_window_) {
345     std::vector<WindowSelectorItem*> windows;
346     for (WindowSelectorItemList::iterator iter = windows_->begin();
347          iter != windows_->end(); ++iter) {
348       windows.push_back(*iter);
349     }
350     PositionWindowsOnRoot(single_root_window_, windows);
351   } else {
352     Shell::RootWindowList root_window_list = Shell::GetAllRootWindows();
353     for (size_t i = 0; i < root_window_list.size(); ++i)
354       PositionWindowsFromRoot(root_window_list[i]);
355   }
356 }
357
358 void WindowOverview::PositionWindowsFromRoot(aura::Window* root_window) {
359   std::vector<WindowSelectorItem*> windows;
360   for (WindowSelectorItemList::iterator iter = windows_->begin();
361        iter != windows_->end(); ++iter) {
362     if ((*iter)->GetRootWindow() == root_window)
363       windows.push_back(*iter);
364   }
365   PositionWindowsOnRoot(root_window, windows);
366 }
367
368 void WindowOverview::PositionWindowsOnRoot(
369     aura::Window* root_window,
370     const std::vector<WindowSelectorItem*>& windows) {
371   if (windows.empty())
372     return;
373
374   gfx::Size window_size;
375   gfx::Rect total_bounds = ScreenAsh::ConvertRectToScreen(root_window,
376       ScreenAsh::GetDisplayWorkAreaBoundsInParent(
377       Shell::GetContainer(root_window,
378                           internal::kShellWindowId_DefaultContainer)));
379
380   // Find the minimum number of windows per row that will fit all of the
381   // windows on screen.
382   size_t columns = std::max(
383       total_bounds.width() > total_bounds.height() ? kMinCardsMajor : 1,
384       static_cast<int>(ceil(sqrt(total_bounds.width() * windows.size() /
385                                  (kCardAspectRatio * total_bounds.height())))));
386   size_t rows = ((windows.size() + columns - 1) / columns);
387   window_size.set_width(std::min(
388       static_cast<int>(total_bounds.width() / columns),
389       static_cast<int>(total_bounds.height() * kCardAspectRatio / rows)));
390   window_size.set_height(window_size.width() / kCardAspectRatio);
391
392   // Calculate the X and Y offsets necessary to center the grid.
393   int x_offset = total_bounds.x() + ((windows.size() >= columns ? 0 :
394       (columns - windows.size()) * window_size.width()) +
395       (total_bounds.width() - columns * window_size.width())) / 2;
396   int y_offset = total_bounds.y() + (total_bounds.height() -
397       rows * window_size.height()) / 2;
398   for (size_t i = 0; i < windows.size(); ++i) {
399     gfx::Transform transform;
400     int column = i % columns;
401     int row = i / columns;
402     gfx::Rect target_bounds(window_size.width() * column + x_offset,
403                             window_size.height() * row + y_offset,
404                             window_size.width(),
405                             window_size.height());
406     target_bounds.Inset(kWindowMargin, kWindowMargin);
407     windows[i]->SetBounds(root_window, target_bounds);
408   }
409 }
410
411 void WindowOverview::InitializeSelectionWidget() {
412   selection_widget_.reset(new views::Widget);
413   views::Widget::InitParams params;
414   params.type = views::Widget::InitParams::TYPE_POPUP;
415   params.can_activate = false;
416   params.keep_on_top = false;
417   params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
418   params.opacity = views::Widget::InitParams::OPAQUE_WINDOW;
419   params.parent = Shell::GetContainer(
420       single_root_window_ ? single_root_window_ :
421                             windows_->front()->GetRootWindow(),
422       internal::kShellWindowId_DefaultContainer);
423   params.accept_events = false;
424   selection_widget_->set_focus_on_creation(false);
425   selection_widget_->Init(params);
426   views::View* content_view = new views::View;
427   content_view->set_background(
428       views::Background::CreateSolidBackground(kWindowOverviewSelectionColor));
429   selection_widget_->SetContentsView(content_view);
430   selection_widget_->Show();
431   selection_widget_->GetNativeWindow()->parent()->StackChildAtBottom(
432       selection_widget_->GetNativeWindow());
433   selection_widget_->GetNativeWindow()->layer()->SetOpacity(0);
434 }
435
436 gfx::Rect WindowOverview::GetSelectionBounds(size_t index) {
437   gfx::Rect bounds((*windows_)[index]->bounds());
438   bounds.Inset(-kWindowOverviewSelectionPadding,
439                -kWindowOverviewSelectionPadding);
440   return bounds;
441 }
442
443 }  // namespace ash