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"
11 #include "ash/accessibility_delegate.h"
12 #include "ash/ash_switches.h"
13 #include "ash/metrics/user_metrics_recorder.h"
14 #include "ash/root_window_controller.h"
15 #include "ash/shell.h"
16 #include "ash/shell_window_ids.h"
17 #include "ash/switchable_windows.h"
18 #include "ash/wm/overview/scoped_overview_animation_settings.h"
19 #include "ash/wm/overview/scoped_transform_overview_window.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/window_state.h"
24 #include "base/auto_reset.h"
25 #include "base/command_line.h"
26 #include "base/metrics/histogram.h"
27 #include "third_party/skia/include/core/SkPaint.h"
28 #include "third_party/skia/include/core/SkPath.h"
29 #include "ui/aura/client/focus_client.h"
30 #include "ui/aura/window.h"
31 #include "ui/aura/window_event_dispatcher.h"
32 #include "ui/aura/window_observer.h"
33 #include "ui/base/resource/resource_bundle.h"
34 #include "ui/compositor/scoped_layer_animation_settings.h"
35 #include "ui/events/event.h"
36 #include "ui/gfx/canvas.h"
37 #include "ui/gfx/screen.h"
38 #include "ui/gfx/skia_util.h"
39 #include "ui/views/border.h"
40 #include "ui/views/controls/textfield/textfield.h"
41 #include "ui/views/layout/box_layout.h"
42 #include "ui/wm/core/window_util.h"
43 #include "ui/wm/public/activation_client.h"
49 // The proportion of screen width that the text filter takes.
50 const float kTextFilterScreenProportion
= 0.25;
52 // The amount of padding surrounding the text in the text filtering textbox.
53 const int kTextFilterHorizontalPadding
= 8;
55 // The distance between the top of the screen and the top edge of the
56 // text filtering textbox.
57 const int kTextFilterDistanceFromTop
= 32;
59 // The height of the text filtering textbox.
60 const int kTextFilterHeight
= 32;
62 // The font style used for text filtering.
63 static const ::ui::ResourceBundle::FontStyle kTextFilterFontStyle
=
64 ::ui::ResourceBundle::FontStyle::MediumFont
;
66 // The alpha value for the background of the text filtering textbox.
67 const unsigned char kTextFilterOpacity
= 180;
69 // The radius used for the rounded corners on the text filtering textbox.
70 const int kTextFilterCornerRadius
= 1;
72 // A comparator for locating a grid with a given root window.
73 struct RootWindowGridComparator
74 : public std::unary_function
<WindowGrid
*, bool> {
75 explicit RootWindowGridComparator(const aura::Window
* root_window
)
76 : root_window_(root_window
) {
79 bool operator()(WindowGrid
* grid
) const {
80 return (grid
->root_window() == root_window_
);
83 const aura::Window
* root_window_
;
86 // A comparator for locating a selectable window given a targeted window.
87 struct WindowSelectorItemTargetComparator
88 : public std::unary_function
<WindowSelectorItem
*, bool> {
89 explicit WindowSelectorItemTargetComparator(const aura::Window
* target_window
)
90 : target(target_window
) {
93 bool operator()(WindowSelectorItem
* window
) const {
94 return window
->Contains(target
);
97 const aura::Window
* target
;
100 // A comparator for locating a selector item for a given root.
101 struct WindowSelectorItemForRoot
102 : public std::unary_function
<WindowSelectorItem
*, bool> {
103 explicit WindowSelectorItemForRoot(const aura::Window
* root
)
104 : root_window(root
) {
107 bool operator()(WindowSelectorItem
* item
) const {
108 return item
->GetRootWindow() == root_window
;
111 const aura::Window
* root_window
;
114 // A View having rounded corners and a specified background color which is
115 // only painted within the bounds defined by the rounded corners.
116 // TODO(tdanderson): This duplicates code from RoundedImageView. Refactor these
117 // classes and move into ui/views.
118 class RoundedContainerView
: public views::View
{
120 RoundedContainerView(int corner_radius
, SkColor background
)
121 : corner_radius_(corner_radius
),
122 background_(background
) {
125 ~RoundedContainerView() override
{}
127 void OnPaint(gfx::Canvas
* canvas
) override
{
128 views::View::OnPaint(canvas
);
130 SkScalar radius
= SkIntToScalar(corner_radius_
);
131 const SkScalar kRadius
[8] = {radius
, radius
, radius
, radius
,
132 radius
, radius
, radius
, radius
};
134 gfx::Rect
bounds(size());
135 path
.addRoundRect(gfx::RectToSkRect(bounds
), kRadius
);
138 paint
.setAntiAlias(true);
139 canvas
->ClipPath(path
, true);
140 canvas
->DrawColor(background_
);
147 DISALLOW_COPY_AND_ASSIGN(RoundedContainerView
);
150 // Triggers a shelf visibility update on all root window controllers.
151 void UpdateShelfVisibility() {
152 Shell::RootWindowControllerList root_window_controllers
=
153 Shell::GetInstance()->GetAllRootWindowControllers();
154 for (Shell::RootWindowControllerList::iterator iter
=
155 root_window_controllers
.begin();
156 iter
!= root_window_controllers
.end(); ++iter
) {
157 (*iter
)->UpdateShelfVisibility();
161 // Initializes the text filter on the top of the main root window and requests
162 // focus on its textfield.
163 views::Widget
* CreateTextFilter(views::TextfieldController
* controller
,
164 aura::Window
* root_window
) {
165 views::Widget
* widget
= new views::Widget
;
166 views::Widget::InitParams params
;
167 params
.type
= views::Widget::InitParams::TYPE_WINDOW_FRAMELESS
;
168 params
.ownership
= views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET
;
169 params
.opacity
= views::Widget::InitParams::TRANSLUCENT_WINDOW
;
170 params
.parent
= Shell::GetContainer(root_window
,
171 kShellWindowId_OverlayContainer
);
172 params
.accept_events
= true;
173 params
.bounds
= gfx::Rect(
174 root_window
->bounds().width() / 2 * (1 - kTextFilterScreenProportion
),
175 kTextFilterDistanceFromTop
,
176 root_window
->bounds().width() * kTextFilterScreenProportion
,
178 widget
->Init(params
);
180 // Use |container| to specify the padding surrounding the text and to give
181 // the textfield rounded corners.
182 views::View
* container
= new RoundedContainerView(
183 kTextFilterCornerRadius
, SkColorSetARGB(kTextFilterOpacity
, 0, 0, 0));
184 ui::ResourceBundle
& bundle
= ui::ResourceBundle::GetSharedInstance();
185 int text_height
= bundle
.GetFontList(kTextFilterFontStyle
).GetHeight();
187 int vertical_padding
= (kTextFilterHeight
- text_height
) / 2;
188 container
->SetLayoutManager(new views::BoxLayout(views::BoxLayout::kVertical
,
189 kTextFilterHorizontalPadding
,
193 views::Textfield
* textfield
= new views::Textfield
;
194 textfield
->set_controller(controller
);
195 textfield
->SetBackgroundColor(SK_ColorTRANSPARENT
);
196 textfield
->SetBorder(views::Border::NullBorder());
197 textfield
->SetTextColor(SK_ColorWHITE
);
198 textfield
->SetFontList(bundle
.GetFontList(kTextFilterFontStyle
));
200 container
->AddChildView(textfield
);
201 widget
->SetContentsView(container
);
203 // The textfield initially contains no text, so shift its position to be
204 // outside the visible bounds of the screen.
205 gfx::Transform transform
;
206 transform
.Translate(0, -WindowSelector::kTextFilterBottomEdge
);
207 widget
->GetNativeWindow()->SetTransform(transform
);
209 textfield
->RequestFocus();
216 const int WindowSelector::kTextFilterBottomEdge
=
217 kTextFilterDistanceFromTop
+ kTextFilterHeight
;
219 WindowSelector::WindowSelector(const WindowList
& windows
,
220 WindowSelectorDelegate
* delegate
)
221 : delegate_(delegate
),
222 restore_focus_window_(aura::client::GetFocusClient(
223 Shell::GetPrimaryRootWindow())->GetFocusedWindow()),
224 ignore_activations_(false),
225 selected_grid_index_(0),
226 overview_start_time_(base::Time::Now()),
229 showing_selection_widget_(false),
230 text_filter_string_length_(0),
231 num_times_textfield_cleared_(0) {
233 Shell
* shell
= Shell::GetInstance();
234 shell
->OnOverviewModeStarting();
236 if (restore_focus_window_
)
237 restore_focus_window_
->AddObserver(this);
239 const aura::Window::Windows root_windows
= Shell::GetAllRootWindows();
240 for (aura::Window::Windows::const_iterator iter
= root_windows
.begin();
241 iter
!= root_windows
.end(); iter
++) {
242 // Observed switchable containers for newly created windows on all root
244 for (size_t i
= 0; i
< kSwitchableWindowContainerIdsLength
; ++i
) {
245 aura::Window
* container
= Shell::GetContainer(*iter
,
246 kSwitchableWindowContainerIds
[i
]);
247 container
->AddObserver(this);
248 observed_windows_
.insert(container
);
250 scoped_ptr
<WindowGrid
> grid(new WindowGrid(*iter
, windows
, this));
253 num_items_
+= grid
->size();
254 grid_list_
.push_back(grid
.release());
257 // Do not call PrepareForOverview until all items are added to window_list_ as
258 // we don't want to cause any window updates until all windows in overview
259 // are observed. See http://crbug.com/384495.
260 for (ScopedVector
<WindowGrid
>::iterator iter
= grid_list_
.begin();
261 iter
!= grid_list_
.end(); ++iter
) {
262 (*iter
)->PrepareForOverview();
263 (*iter
)->PositionWindows(true);
266 DCHECK(!grid_list_
.empty());
267 UMA_HISTOGRAM_COUNTS_100("Ash.WindowSelector.Items", num_items_
);
269 text_filter_widget_
.reset(
270 CreateTextFilter(this, Shell::GetPrimaryRootWindow()));
272 shell
->activation_client()->AddObserver(this);
274 shell
->GetScreen()->AddObserver(this);
275 shell
->metrics()->RecordUserMetricsAction(UMA_WINDOW_OVERVIEW
);
276 HideAndTrackNonOverviewWindows();
277 // Send an a11y alert.
278 shell
->accessibility_delegate()->TriggerAccessibilityAlert(
279 ui::A11Y_ALERT_WINDOW_OVERVIEW_MODE_ENTERED
);
281 UpdateShelfVisibility();
284 WindowSelector::~WindowSelector() {
285 Shell
* shell
= Shell::GetInstance();
287 ResetFocusRestoreWindow(true);
288 for (std::set
<aura::Window
*>::iterator iter
= observed_windows_
.begin();
289 iter
!= observed_windows_
.end(); ++iter
) {
290 (*iter
)->RemoveObserver(this);
292 shell
->activation_client()->RemoveObserver(this);
293 aura::Window::Windows root_windows
= Shell::GetAllRootWindows();
295 const aura::WindowTracker::Windows
hidden_windows(hidden_windows_
.windows());
296 for (aura::WindowTracker::Windows::const_iterator iter
=
297 hidden_windows
.begin(); iter
!= hidden_windows
.end(); ++iter
) {
298 ScopedOverviewAnimationSettings
animation_settings(
299 OverviewAnimationType::OVERVIEW_ANIMATION_LAY_OUT_SELECTOR_ITEMS
,
301 (*iter
)->layer()->SetOpacity(1);
305 shell
->GetScreen()->RemoveObserver(this);
307 size_t remaining_items
= 0;
308 for (ScopedVector
<WindowGrid
>::iterator iter
= grid_list_
.begin();
309 iter
!= grid_list_
.end(); iter
++) {
310 remaining_items
+= (*iter
)->size();
313 DCHECK(num_items_
>= remaining_items
);
314 UMA_HISTOGRAM_COUNTS_100("Ash.WindowSelector.OverviewClosedItems",
315 num_items_
- remaining_items
);
316 UMA_HISTOGRAM_MEDIUM_TIMES("Ash.WindowSelector.TimeInOverview",
317 base::Time::Now() - overview_start_time_
);
319 // Record metrics related to text filtering.
320 UMA_HISTOGRAM_COUNTS_100("Ash.WindowSelector.TextFilteringStringLength",
321 text_filter_string_length_
);
322 UMA_HISTOGRAM_COUNTS_100("Ash.WindowSelector.TextFilteringTextfieldCleared",
323 num_times_textfield_cleared_
);
324 if (text_filter_string_length_
) {
325 UMA_HISTOGRAM_MEDIUM_TIMES(
326 "Ash.WindowSelector.TimeInOverviewWithTextFiltering",
327 base::Time::Now() - overview_start_time_
);
328 UMA_HISTOGRAM_COUNTS_100(
329 "Ash.WindowSelector.ItemsWhenTextFilteringUsed",
333 // TODO(flackr): Change this to OnOverviewModeEnded and move it to when
334 // everything is done.
335 shell
->OnOverviewModeEnding();
337 // Clearing the window list resets the ignored_by_shelf flag on the windows.
339 UpdateShelfVisibility();
342 void WindowSelector::CancelSelection() {
343 delegate_
->OnSelectionEnded();
346 void WindowSelector::OnGridEmpty(WindowGrid
* grid
) {
347 ScopedVector
<WindowGrid
>::iterator iter
=
348 std::find(grid_list_
.begin(), grid_list_
.end(), grid
);
349 DCHECK(iter
!= grid_list_
.end());
350 grid_list_
.erase(iter
);
351 // TODO(flackr): Use the previous index for more than two displays.
352 selected_grid_index_
= 0;
353 if (grid_list_
.empty())
357 bool WindowSelector::HandleKeyEvent(views::Textfield
* sender
,
358 const ui::KeyEvent
& key_event
) {
359 if (key_event
.type() != ui::ET_KEY_PRESSED
)
362 switch (key_event
.key_code()) {
363 case ui::VKEY_ESCAPE
:
368 Move(WindowSelector::UP
, true);
372 Move(WindowSelector::DOWN
, true);
377 Move(WindowSelector::RIGHT
, true);
381 Move(WindowSelector::LEFT
, true);
383 case ui::VKEY_RETURN
:
384 // Ignore if no item is selected.
385 if (!grid_list_
[selected_grid_index_
]->is_selecting())
387 UMA_HISTOGRAM_COUNTS_100("Ash.WindowSelector.ArrowKeyPresses",
389 UMA_HISTOGRAM_CUSTOM_COUNTS(
390 "Ash.WindowSelector.KeyPressesOverItemsRatio",
391 (num_key_presses_
* 100) / num_items_
, 1, 300, 30);
392 Shell::GetInstance()->metrics()->RecordUserMetricsAction(
393 UMA_WINDOW_OVERVIEW_ENTER_KEY
);
394 wm::GetWindowState(grid_list_
[selected_grid_index_
]->
395 SelectedWindow()->SelectionWindow())->Activate();
398 // Not a key we are interested in, allow the textfield to handle it.
404 void WindowSelector::OnDisplayAdded(const gfx::Display
& display
) {
407 void WindowSelector::OnDisplayRemoved(const gfx::Display
& display
) {
408 // TODO(flackr): Keep window selection active on remaining displays.
412 void WindowSelector::OnDisplayMetricsChanged(const gfx::Display
& display
,
414 PositionWindows(/* animate */ false);
417 void WindowSelector::OnWindowAdded(aura::Window
* new_window
) {
418 if (new_window
->type() != ui::wm::WINDOW_TYPE_NORMAL
&&
419 new_window
->type() != ui::wm::WINDOW_TYPE_PANEL
) {
423 for (size_t i
= 0; i
< kSwitchableWindowContainerIdsLength
; ++i
) {
424 if (new_window
->parent()->id() == kSwitchableWindowContainerIds
[i
] &&
425 !::wm::GetTransientParent(new_window
)) {
426 // The new window is in one of the switchable containers, abort overview.
433 void WindowSelector::OnWindowDestroying(aura::Window
* window
) {
434 window
->RemoveObserver(this);
435 observed_windows_
.erase(window
);
436 if (window
== restore_focus_window_
)
437 restore_focus_window_
= NULL
;
440 void WindowSelector::OnWindowActivated(aura::Window
* gained_active
,
441 aura::Window
* lost_active
) {
442 if (ignore_activations_
||
444 gained_active
== text_filter_widget_
->GetNativeWindow()) {
448 ScopedVector
<WindowGrid
>::iterator grid
=
449 std::find_if(grid_list_
.begin(), grid_list_
.end(),
450 RootWindowGridComparator(gained_active
->GetRootWindow()));
451 if (grid
== grid_list_
.end())
453 const std::vector
<WindowSelectorItem
*> windows
= (*grid
)->window_list();
455 ScopedVector
<WindowSelectorItem
>::const_iterator iter
= std::find_if(
456 windows
.begin(), windows
.end(),
457 WindowSelectorItemTargetComparator(gained_active
));
459 if (iter
!= windows
.end())
460 (*iter
)->RestoreWindowOnExit(gained_active
);
462 // Don't restore focus on exit if a window was just activated.
463 ResetFocusRestoreWindow(false);
467 void WindowSelector::OnAttemptToReactivateWindow(aura::Window
* request_active
,
468 aura::Window
* actual_active
) {
469 OnWindowActivated(request_active
, actual_active
);
472 void WindowSelector::ContentsChanged(views::Textfield
* sender
,
473 const base::string16
& new_contents
) {
474 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
475 switches::kAshDisableTextFilteringInOverviewMode
)) {
479 text_filter_string_length_
= new_contents
.length();
480 if (!text_filter_string_length_
)
481 num_times_textfield_cleared_
++;
483 bool should_show_selection_widget
= !new_contents
.empty();
484 if (showing_selection_widget_
!= should_show_selection_widget
) {
485 ui::ScopedLayerAnimationSettings
animation_settings(
486 text_filter_widget_
->GetNativeWindow()->layer()->GetAnimator());
487 animation_settings
.SetPreemptionStrategy(
488 ui::LayerAnimator::IMMEDIATELY_ANIMATE_TO_NEW_TARGET
);
489 animation_settings
.SetTweenType(showing_selection_widget_
?
490 gfx::Tween::FAST_OUT_LINEAR_IN
: gfx::Tween::LINEAR_OUT_SLOW_IN
);
492 gfx::Transform transform
;
493 if (should_show_selection_widget
) {
494 transform
.Translate(0, 0);
495 text_filter_widget_
->GetNativeWindow()->layer()->SetOpacity(1);
497 transform
.Translate(0, -kTextFilterBottomEdge
);
498 text_filter_widget_
->GetNativeWindow()->layer()->SetOpacity(0);
501 text_filter_widget_
->GetNativeWindow()->SetTransform(transform
);
502 showing_selection_widget_
= should_show_selection_widget
;
504 for (ScopedVector
<WindowGrid
>::iterator iter
= grid_list_
.begin();
505 iter
!= grid_list_
.end(); iter
++) {
506 (*iter
)->FilterItems(new_contents
);
509 // If the selection widget is not active, execute a Move() command so that it
510 // shows up on the first undimmed item.
511 if (grid_list_
[selected_grid_index_
]->is_selecting())
513 Move(WindowSelector::RIGHT
, false);
516 void WindowSelector::PositionWindows(bool animate
) {
517 for (ScopedVector
<WindowGrid
>::iterator iter
= grid_list_
.begin();
518 iter
!= grid_list_
.end(); iter
++) {
519 (*iter
)->PositionWindows(animate
);
523 void WindowSelector::HideAndTrackNonOverviewWindows() {
524 // Add the windows to hidden_windows first so that if any are destroyed
525 // while hiding them they are tracked.
526 for (ScopedVector
<WindowGrid
>::iterator grid_iter
= grid_list_
.begin();
527 grid_iter
!= grid_list_
.end(); ++grid_iter
) {
528 for (size_t i
= 0; i
< kSwitchableWindowContainerIdsLength
; ++i
) {
529 const aura::Window
* container
=
530 Shell::GetContainer((*grid_iter
)->root_window(),
531 kSwitchableWindowContainerIds
[i
]);
532 for (aura::Window::Windows::const_iterator iter
=
533 container
->children().begin(); iter
!= container
->children().end();
535 if (!(*iter
)->IsVisible() || (*grid_iter
)->Contains(*iter
))
537 hidden_windows_
.Add(*iter
);
542 // Copy the window list as it can change during iteration.
543 const aura::WindowTracker::Windows
hidden_windows(hidden_windows_
.windows());
544 for (aura::WindowTracker::Windows::const_iterator iter
=
545 hidden_windows
.begin(); iter
!= hidden_windows
.end(); ++iter
) {
546 if (!hidden_windows_
.Contains(*iter
))
548 ScopedOverviewAnimationSettings
animation_settings(
549 OverviewAnimationType::OVERVIEW_ANIMATION_HIDE_WINDOW
,
552 // Hiding the window can result in it being destroyed.
553 if (!hidden_windows_
.Contains(*iter
))
555 (*iter
)->layer()->SetOpacity(0);
559 void WindowSelector::ResetFocusRestoreWindow(bool focus
) {
560 if (!restore_focus_window_
)
563 base::AutoReset
<bool> restoring_focus(&ignore_activations_
, true);
564 restore_focus_window_
->Focus();
566 // If the window is in the observed_windows_ list it needs to continue to be
568 if (observed_windows_
.find(restore_focus_window_
) ==
569 observed_windows_
.end()) {
570 restore_focus_window_
->RemoveObserver(this);
572 restore_focus_window_
= NULL
;
575 void WindowSelector::Move(Direction direction
, bool animate
) {
576 // Keep calling Move() on the grids until one of them reports no overflow or
577 // we made a full cycle on all the grids.
579 i
<= grid_list_
.size() &&
580 grid_list_
[selected_grid_index_
]->Move(direction
, animate
); i
++) {
581 // TODO(flackr): If there are more than two monitors, move between grids
582 // in the requested direction.
583 selected_grid_index_
= (selected_grid_index_
+ 1) % grid_list_
.size();