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