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.
5 #include "ash/wm/overview/window_selector.h"
12 #include "ash/accessibility_delegate.h"
13 #include "ash/ash_switches.h"
14 #include "ash/metrics/user_metrics_recorder.h"
15 #include "ash/root_window_controller.h"
16 #include "ash/shell.h"
17 #include "ash/shell_window_ids.h"
18 #include "ash/switchable_windows.h"
19 #include "ash/wm/mru_window_tracker.h"
20 #include "ash/wm/overview/window_grid.h"
21 #include "ash/wm/overview/window_selector_delegate.h"
22 #include "ash/wm/overview/window_selector_item.h"
23 #include "ash/wm/panels/panel_layout_manager.h"
24 #include "ash/wm/window_state.h"
25 #include "ash/wm/window_util.h"
26 #include "base/auto_reset.h"
27 #include "base/command_line.h"
28 #include "base/metrics/histogram.h"
29 #include "third_party/skia/include/core/SkPaint.h"
30 #include "third_party/skia/include/core/SkPath.h"
31 #include "ui/aura/client/focus_client.h"
32 #include "ui/aura/window.h"
33 #include "ui/aura/window_event_dispatcher.h"
34 #include "ui/aura/window_observer.h"
35 #include "ui/base/resource/resource_bundle.h"
36 #include "ui/compositor/scoped_layer_animation_settings.h"
37 #include "ui/events/event.h"
38 #include "ui/gfx/canvas.h"
39 #include "ui/gfx/screen.h"
40 #include "ui/gfx/skia_util.h"
41 #include "ui/views/border.h"
42 #include "ui/views/controls/textfield/textfield.h"
43 #include "ui/views/layout/box_layout.h"
44 #include "ui/wm/core/window_util.h"
45 #include "ui/wm/public/activation_client.h"
51 // The proportion of screen width that the text filter takes.
52 const float kTextFilterScreenProportion
= 0.25;
54 // The amount of padding surrounding the text in the text filtering textbox.
55 const int kTextFilterHorizontalPadding
= 8;
57 // The distance between the top of the screen and the top edge of the
58 // text filtering textbox.
59 const int kTextFilterDistanceFromTop
= 32;
61 // The height of the text filtering textbox.
62 const int kTextFilterHeight
= 32;
64 // The font style used for text filtering.
65 static const ::ui::ResourceBundle::FontStyle kTextFilterFontStyle
=
66 ::ui::ResourceBundle::FontStyle::MediumFont
;
68 // The alpha value for the background of the text filtering textbox.
69 const unsigned char kTextFilterOpacity
= 180;
71 // The radius used for the rounded corners on the text filtering textbox.
72 const int kTextFilterCornerRadius
= 1;
74 // A comparator for locating a grid with a given root window.
75 struct RootWindowGridComparator
76 : public std::unary_function
<WindowGrid
*, bool> {
77 explicit RootWindowGridComparator(const aura::Window
* root_window
)
78 : root_window_(root_window
) {
81 bool operator()(WindowGrid
* grid
) const {
82 return (grid
->root_window() == root_window_
);
85 const aura::Window
* root_window_
;
88 // A comparator for locating a selectable window given a targeted window.
89 struct WindowSelectorItemTargetComparator
90 : public std::unary_function
<WindowSelectorItem
*, bool> {
91 explicit WindowSelectorItemTargetComparator(const aura::Window
* target_window
)
92 : target(target_window
) {
95 bool operator()(WindowSelectorItem
* window
) const {
96 return window
->GetWindow() == target
;
99 const aura::Window
* target
;
102 // A comparator for locating a selector item for a given root.
103 struct WindowSelectorItemForRoot
104 : public std::unary_function
<WindowSelectorItem
*, bool> {
105 explicit WindowSelectorItemForRoot(const aura::Window
* root
)
106 : root_window(root
) {
109 bool operator()(WindowSelectorItem
* item
) const {
110 return item
->root_window() == root_window
;
113 const aura::Window
* root_window
;
116 // A View having rounded corners and a specified background color which is
117 // only painted within the bounds defined by the rounded corners.
118 // TODO(tdanderson): This duplicates code from RoundedImageView. Refactor these
119 // classes and move into ui/views.
120 class RoundedContainerView
: public views::View
{
122 RoundedContainerView(int corner_radius
, SkColor background
)
123 : corner_radius_(corner_radius
),
124 background_(background
) {
127 ~RoundedContainerView() override
{}
129 void OnPaint(gfx::Canvas
* canvas
) override
{
130 views::View::OnPaint(canvas
);
132 SkScalar radius
= SkIntToScalar(corner_radius_
);
133 const SkScalar kRadius
[8] = {radius
, radius
, radius
, radius
,
134 radius
, radius
, radius
, radius
};
136 gfx::Rect
bounds(size());
137 path
.addRoundRect(gfx::RectToSkRect(bounds
), kRadius
);
140 paint
.setAntiAlias(true);
141 canvas
->ClipPath(path
, true);
142 canvas
->DrawColor(background_
);
149 DISALLOW_COPY_AND_ASSIGN(RoundedContainerView
);
152 // Triggers a shelf visibility update on all root window controllers.
153 void UpdateShelfVisibility() {
154 Shell::RootWindowControllerList root_window_controllers
=
155 Shell::GetInstance()->GetAllRootWindowControllers();
156 for (Shell::RootWindowControllerList::iterator iter
=
157 root_window_controllers
.begin();
158 iter
!= root_window_controllers
.end(); ++iter
) {
159 (*iter
)->UpdateShelfVisibility();
163 // Initializes the text filter on the top of the main root window and requests
164 // focus on its textfield.
165 views::Widget
* CreateTextFilter(views::TextfieldController
* controller
,
166 aura::Window
* root_window
) {
167 views::Widget
* widget
= new views::Widget
;
168 views::Widget::InitParams params
;
169 params
.type
= views::Widget::InitParams::TYPE_WINDOW_FRAMELESS
;
170 params
.ownership
= views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET
;
171 params
.opacity
= views::Widget::InitParams::TRANSLUCENT_WINDOW
;
172 params
.parent
= Shell::GetContainer(root_window
,
173 kShellWindowId_OverlayContainer
);
174 params
.accept_events
= true;
175 params
.bounds
= gfx::Rect(
176 root_window
->bounds().width() / 2 * (1 - kTextFilterScreenProportion
),
177 kTextFilterDistanceFromTop
,
178 root_window
->bounds().width() * kTextFilterScreenProportion
,
180 widget
->Init(params
);
182 // Use |container| to specify the padding surrounding the text and to give
183 // the textfield rounded corners.
184 views::View
* container
= new RoundedContainerView(
185 kTextFilterCornerRadius
, SkColorSetARGB(kTextFilterOpacity
, 0, 0, 0));
186 ui::ResourceBundle
& bundle
= ui::ResourceBundle::GetSharedInstance();
187 int text_height
= bundle
.GetFontList(kTextFilterFontStyle
).GetHeight();
189 int vertical_padding
= (kTextFilterHeight
- text_height
) / 2;
190 container
->SetLayoutManager(new views::BoxLayout(views::BoxLayout::kVertical
,
191 kTextFilterHorizontalPadding
,
195 views::Textfield
* textfield
= new views::Textfield
;
196 textfield
->set_controller(controller
);
197 textfield
->SetBackgroundColor(SK_ColorTRANSPARENT
);
198 textfield
->SetBorder(views::Border::NullBorder());
199 textfield
->SetTextColor(SK_ColorWHITE
);
200 textfield
->SetFontList(bundle
.GetFontList(kTextFilterFontStyle
));
202 container
->AddChildView(textfield
);
203 widget
->SetContentsView(container
);
205 // The textfield initially contains no text, so shift its position to be
206 // outside the visible bounds of the screen.
207 gfx::Transform transform
;
208 transform
.Translate(0, -WindowSelector::kTextFilterBottomEdge
);
209 widget
->GetNativeWindow()->SetTransform(transform
);
211 textfield
->RequestFocus();
218 const int WindowSelector::kTextFilterBottomEdge
=
219 kTextFilterDistanceFromTop
+ kTextFilterHeight
;
222 bool WindowSelector::IsSelectable(aura::Window
* window
) {
223 wm::WindowState
* state
= wm::GetWindowState(window
);
224 if (state
->GetStateType() == wm::WINDOW_STATE_TYPE_DOCKED
||
225 state
->GetStateType() == wm::WINDOW_STATE_TYPE_DOCKED_MINIMIZED
) {
228 return state
->IsUserPositionable();
231 WindowSelector::WindowSelector(WindowSelectorDelegate
* delegate
)
232 : delegate_(delegate
),
233 restore_focus_window_(aura::client::GetFocusClient(
234 Shell::GetPrimaryRootWindow())->GetFocusedWindow()),
235 ignore_activations_(false),
236 selected_grid_index_(0),
237 overview_start_time_(base::Time::Now()),
240 showing_selection_widget_(false),
241 text_filter_string_length_(0),
242 num_times_textfield_cleared_(0),
243 restoring_minimized_windows_(false) {
247 WindowSelector::~WindowSelector() {
248 RemoveAllObservers();
251 // NOTE: The work done in Init() is not done in the constructor because it may
252 // cause other, unrelated classes, (ie PanelLayoutManager) to make indirect
253 // calls to restoring_minimized_windows() on a partially constructed object.
254 void WindowSelector::Init(const WindowList
& windows
) {
255 if (restore_focus_window_
)
256 restore_focus_window_
->AddObserver(this);
258 aura::Window::Windows root_windows
= Shell::GetAllRootWindows();
259 std::sort(root_windows
.begin(), root_windows
.end(),
260 [](const aura::Window
* a
, const aura::Window
* b
) {
261 // Since we don't know if windows are vertically or horizontally
262 // oriented we use both x and y position. This may be confusing
263 // if you have 3 or more monitors which are not strictly
264 // horizontal or vertical but that case is not yet supported.
265 return (a
->GetBoundsInScreen().x() + a
->GetBoundsInScreen().y()) <
266 (b
->GetBoundsInScreen().x() + b
->GetBoundsInScreen().y());
269 for (aura::Window::Windows::const_iterator iter
= root_windows
.begin();
270 iter
!= root_windows
.end(); iter
++) {
271 // Observed switchable containers for newly created windows on all root
273 for (size_t i
= 0; i
< kSwitchableWindowContainerIdsLength
; ++i
) {
274 aura::Window
* container
= Shell::GetContainer(*iter
,
275 kSwitchableWindowContainerIds
[i
]);
276 container
->AddObserver(this);
277 observed_windows_
.insert(container
);
280 // Hide the callout widgets for panels. It is safe to call this for
281 // root windows that don't contain any panel windows.
282 static_cast<PanelLayoutManager
*>(
283 Shell::GetContainer(*iter
, kShellWindowId_PanelContainer
)
284 ->layout_manager())->SetShowCalloutWidgets(false);
286 scoped_ptr
<WindowGrid
> grid(new WindowGrid(*iter
, windows
, this));
289 num_items_
+= grid
->size();
290 grid_list_
.push_back(grid
.Pass());
294 // The calls to WindowGrid::PrepareForOverview() and CreateTextFilter(...)
295 // requires some LayoutManagers (ie PanelLayoutManager) to perform layouts
296 // so that windows are correctly visible and properly animated in overview
297 // mode. Otherwise these layouts should be suppressed during overview mode
298 // so they don't conflict with overview mode animations. The
299 // |restoring_minimized_windows_| flag enables the PanelLayoutManager to
300 // make this decision.
301 base::AutoReset
<bool> auto_restoring_minimized_windows(
302 &restoring_minimized_windows_
, true);
304 // Do not call PrepareForOverview until all items are added to window_list_
305 // as we don't want to cause any window updates until all windows in
306 // overview are observed. See http://crbug.com/384495.
307 for (WindowGrid
* window_grid
: grid_list_
) {
308 window_grid
->PrepareForOverview();
309 window_grid
->PositionWindows(true);
312 text_filter_widget_
.reset(
313 CreateTextFilter(this, Shell::GetPrimaryRootWindow()));
316 DCHECK(!grid_list_
.empty());
317 UMA_HISTOGRAM_COUNTS_100("Ash.WindowSelector.Items", num_items_
);
319 Shell
* shell
= Shell::GetInstance();
321 shell
->activation_client()->AddObserver(this);
323 shell
->GetScreen()->AddObserver(this);
324 shell
->metrics()->RecordUserMetricsAction(UMA_WINDOW_OVERVIEW
);
325 // Send an a11y alert.
326 shell
->accessibility_delegate()->TriggerAccessibilityAlert(
327 ui::A11Y_ALERT_WINDOW_OVERVIEW_MODE_ENTERED
);
329 UpdateShelfVisibility();
332 // NOTE: The work done in Shutdown() is not done in the destructor because it
333 // may cause other, unrelated classes, (ie PanelLayoutManager) to make indirect
334 // calls to restoring_minimized_windows() on a partially destructed object.
335 void WindowSelector::Shutdown() {
336 ResetFocusRestoreWindow(true);
337 RemoveAllObservers();
339 aura::Window::Windows root_windows
= Shell::GetAllRootWindows();
340 for (aura::Window::Windows::const_iterator iter
= root_windows
.begin();
341 iter
!= root_windows
.end(); iter
++) {
342 // Un-hide the callout widgets for panels. It is safe to call this for
343 // root_windows that don't contain any panel windows.
344 static_cast<PanelLayoutManager
*>(
345 Shell::GetContainer(*iter
, kShellWindowId_PanelContainer
)
346 ->layout_manager())->SetShowCalloutWidgets(true);
349 size_t remaining_items
= 0;
350 for (WindowGrid
* window_grid
: grid_list_
) {
351 for (WindowSelectorItem
* window_selector_item
: window_grid
->window_list())
352 window_selector_item
->RestoreWindow();
353 remaining_items
+= window_grid
->size();
356 DCHECK(num_items_
>= remaining_items
);
357 UMA_HISTOGRAM_COUNTS_100("Ash.WindowSelector.OverviewClosedItems",
358 num_items_
- remaining_items
);
359 UMA_HISTOGRAM_MEDIUM_TIMES("Ash.WindowSelector.TimeInOverview",
360 base::Time::Now() - overview_start_time_
);
362 // Record metrics related to text filtering.
363 UMA_HISTOGRAM_COUNTS_100("Ash.WindowSelector.TextFilteringStringLength",
364 text_filter_string_length_
);
365 UMA_HISTOGRAM_COUNTS_100("Ash.WindowSelector.TextFilteringTextfieldCleared",
366 num_times_textfield_cleared_
);
367 if (text_filter_string_length_
) {
368 UMA_HISTOGRAM_MEDIUM_TIMES(
369 "Ash.WindowSelector.TimeInOverviewWithTextFiltering",
370 base::Time::Now() - overview_start_time_
);
371 UMA_HISTOGRAM_COUNTS_100(
372 "Ash.WindowSelector.ItemsWhenTextFilteringUsed",
376 // Clearing the window list resets the ignored_by_shelf flag on the windows.
378 UpdateShelfVisibility();
381 void WindowSelector::RemoveAllObservers() {
382 Shell
* shell
= Shell::GetInstance();
383 for (aura::Window
* window
: observed_windows_
)
384 window
->RemoveObserver(this);
386 shell
->activation_client()->RemoveObserver(this);
387 shell
->GetScreen()->RemoveObserver(this);
388 if (restore_focus_window_
)
389 restore_focus_window_
->RemoveObserver(this);
392 void WindowSelector::CancelSelection() {
393 delegate_
->OnSelectionEnded();
396 void WindowSelector::OnGridEmpty(WindowGrid
* grid
) {
397 ScopedVector
<WindowGrid
>::iterator iter
=
398 std::find(grid_list_
.begin(), grid_list_
.end(), grid
);
399 DCHECK(iter
!= grid_list_
.end());
400 size_t index
= iter
- grid_list_
.begin();
401 grid_list_
.erase(iter
);
402 if (index
> 0 && selected_grid_index_
>= index
) {
403 selected_grid_index_
--;
404 // If the grid which became empty was the one with the selected window, we
405 // need to select a window on the newly selected grid.
406 if (selected_grid_index_
== index
- 1)
409 if (grid_list_
.empty())
413 void WindowSelector::SelectWindow(aura::Window
* window
) {
414 // Record UMA_WINDOW_OVERVIEW_ACTIVE_WINDOW_CHANGED if the user is selecting
415 // a window other than the window that was active prior to entering overview
416 // mode (i.e., the window at the front of the MRU list).
417 MruWindowTracker::WindowList window_list
=
418 Shell::GetInstance()->mru_window_tracker()->BuildMruWindowList();
419 if (window_list
.size() > 0 && window_list
[0] != window
) {
420 Shell::GetInstance()->metrics()->RecordUserMetricsAction(
421 UMA_WINDOW_OVERVIEW_ACTIVE_WINDOW_CHANGED
);
424 wm::GetWindowState(window
)->Activate();
427 bool WindowSelector::HandleKeyEvent(views::Textfield
* sender
,
428 const ui::KeyEvent
& key_event
) {
429 if (key_event
.type() != ui::ET_KEY_PRESSED
)
432 switch (key_event
.key_code()) {
433 case ui::VKEY_ESCAPE
:
438 Move(WindowSelector::UP
, true);
442 Move(WindowSelector::DOWN
, true);
447 Move(WindowSelector::RIGHT
, true);
451 Move(WindowSelector::LEFT
, true);
453 case ui::VKEY_RETURN
:
454 // Ignore if no item is selected.
455 if (!grid_list_
[selected_grid_index_
]->is_selecting())
457 UMA_HISTOGRAM_COUNTS_100("Ash.WindowSelector.ArrowKeyPresses",
459 UMA_HISTOGRAM_CUSTOM_COUNTS(
460 "Ash.WindowSelector.KeyPressesOverItemsRatio",
461 (num_key_presses_
* 100) / num_items_
, 1, 300, 30);
462 Shell::GetInstance()->metrics()->RecordUserMetricsAction(
463 UMA_WINDOW_OVERVIEW_ENTER_KEY
);
465 grid_list_
[selected_grid_index_
]->SelectedWindow()->GetWindow());
468 // Not a key we are interested in, allow the textfield to handle it.
474 void WindowSelector::OnDisplayAdded(const gfx::Display
& display
) {
477 void WindowSelector::OnDisplayRemoved(const gfx::Display
& display
) {
478 // TODO(flackr): Keep window selection active on remaining displays.
482 void WindowSelector::OnDisplayMetricsChanged(const gfx::Display
& display
,
484 PositionWindows(/* animate */ false);
485 RepositionTextFilterOnDisplayMetricsChange();
488 void WindowSelector::OnWindowAdded(aura::Window
* new_window
) {
489 if (!IsSelectable(new_window
))
492 for (size_t i
= 0; i
< kSwitchableWindowContainerIdsLength
; ++i
) {
493 if (new_window
->parent()->id() == kSwitchableWindowContainerIds
[i
] &&
494 !::wm::GetTransientParent(new_window
)) {
495 // The new window is in one of the switchable containers, abort overview.
502 void WindowSelector::OnWindowDestroying(aura::Window
* window
) {
503 window
->RemoveObserver(this);
504 observed_windows_
.erase(window
);
505 if (window
== restore_focus_window_
)
506 restore_focus_window_
= nullptr;
509 void WindowSelector::OnWindowActivated(
510 aura::client::ActivationChangeObserver::ActivationReason reason
,
511 aura::Window
* gained_active
,
512 aura::Window
* lost_active
) {
513 if (ignore_activations_
||
515 gained_active
== text_filter_widget_
->GetNativeWindow()) {
519 ScopedVector
<WindowGrid
>::iterator grid
=
520 std::find_if(grid_list_
.begin(), grid_list_
.end(),
521 RootWindowGridComparator(gained_active
->GetRootWindow()));
522 if (grid
== grid_list_
.end())
524 const std::vector
<WindowSelectorItem
*> windows
= (*grid
)->window_list();
526 ScopedVector
<WindowSelectorItem
>::const_iterator iter
= std::find_if(
527 windows
.begin(), windows
.end(),
528 WindowSelectorItemTargetComparator(gained_active
));
530 if (iter
!= windows
.end())
531 (*iter
)->ShowWindowOnExit();
533 // Don't restore focus on exit if a window was just activated.
534 ResetFocusRestoreWindow(false);
538 void WindowSelector::OnAttemptToReactivateWindow(aura::Window
* request_active
,
539 aura::Window
* actual_active
) {
540 OnWindowActivated(aura::client::ActivationChangeObserver::ActivationReason::
542 request_active
, actual_active
);
545 void WindowSelector::ContentsChanged(views::Textfield
* sender
,
546 const base::string16
& new_contents
) {
547 text_filter_string_length_
= new_contents
.length();
548 if (!text_filter_string_length_
)
549 num_times_textfield_cleared_
++;
551 bool should_show_selection_widget
= !new_contents
.empty();
552 if (showing_selection_widget_
!= should_show_selection_widget
) {
553 ui::ScopedLayerAnimationSettings
animation_settings(
554 text_filter_widget_
->GetNativeWindow()->layer()->GetAnimator());
555 animation_settings
.SetPreemptionStrategy(
556 ui::LayerAnimator::IMMEDIATELY_ANIMATE_TO_NEW_TARGET
);
557 animation_settings
.SetTweenType(showing_selection_widget_
?
558 gfx::Tween::FAST_OUT_LINEAR_IN
: gfx::Tween::LINEAR_OUT_SLOW_IN
);
560 gfx::Transform transform
;
561 if (should_show_selection_widget
) {
562 transform
.Translate(0, 0);
563 text_filter_widget_
->GetNativeWindow()->layer()->SetOpacity(1);
565 transform
.Translate(0, -kTextFilterBottomEdge
);
566 text_filter_widget_
->GetNativeWindow()->layer()->SetOpacity(0);
569 text_filter_widget_
->GetNativeWindow()->SetTransform(transform
);
570 showing_selection_widget_
= should_show_selection_widget
;
572 for (ScopedVector
<WindowGrid
>::iterator iter
= grid_list_
.begin();
573 iter
!= grid_list_
.end(); iter
++) {
574 (*iter
)->FilterItems(new_contents
);
577 // If the selection widget is not active, execute a Move() command so that it
578 // shows up on the first undimmed item.
579 if (grid_list_
[selected_grid_index_
]->is_selecting())
581 Move(WindowSelector::RIGHT
, false);
584 void WindowSelector::PositionWindows(bool animate
) {
585 for (ScopedVector
<WindowGrid
>::iterator iter
= grid_list_
.begin();
586 iter
!= grid_list_
.end(); iter
++) {
587 (*iter
)->PositionWindows(animate
);
591 void WindowSelector::RepositionTextFilterOnDisplayMetricsChange() {
592 aura::Window
* root_window
= Shell::GetPrimaryRootWindow();
594 root_window
->bounds().width() / 2 * (1 - kTextFilterScreenProportion
),
595 kTextFilterDistanceFromTop
,
596 root_window
->bounds().width() * kTextFilterScreenProportion
,
599 text_filter_widget_
->SetBounds(rect
);
601 gfx::Transform transform
;
602 transform
.Translate(0, text_filter_string_length_
== 0
603 ? -WindowSelector::kTextFilterBottomEdge
605 text_filter_widget_
->GetNativeWindow()->SetTransform(transform
);
608 void WindowSelector::ResetFocusRestoreWindow(bool focus
) {
609 if (!restore_focus_window_
)
612 base::AutoReset
<bool> restoring_focus(&ignore_activations_
, true);
613 restore_focus_window_
->Focus();
615 // If the window is in the observed_windows_ list it needs to continue to be
617 if (observed_windows_
.find(restore_focus_window_
) ==
618 observed_windows_
.end()) {
619 restore_focus_window_
->RemoveObserver(this);
621 restore_focus_window_
= nullptr;
624 void WindowSelector::Move(Direction direction
, bool animate
) {
625 // Direction to move if moving past the end of a display.
626 int display_direction
= (direction
== RIGHT
|| direction
== DOWN
) ? 1 : -1;
628 // If this is the first move and it's going backwards, start on the last
630 if (display_direction
== -1 && !grid_list_
.empty() &&
631 !grid_list_
[selected_grid_index_
]->is_selecting()) {
632 selected_grid_index_
= grid_list_
.size() - 1;
635 // Keep calling Move() on the grids until one of them reports no overflow or
636 // we made a full cycle on all the grids.
638 i
<= grid_list_
.size() &&
639 grid_list_
[selected_grid_index_
]->Move(direction
, animate
); i
++) {
640 selected_grid_index_
=
641 (selected_grid_index_
+ display_direction
+ grid_list_
.size()) %