[iOS] Cleanup ios/chrome/ios_chrome.gyp
[chromium-blink-merge.git] / ash / wm / overview / window_selector.cc
blob3e033cc90de4e610c2821c765daee217e018ffd9
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"
7 #include <algorithm>
8 #include <functional>
9 #include <set>
10 #include <vector>
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 "base/auto_reset.h"
26 #include "base/command_line.h"
27 #include "base/metrics/histogram.h"
28 #include "third_party/skia/include/core/SkPaint.h"
29 #include "third_party/skia/include/core/SkPath.h"
30 #include "ui/aura/client/focus_client.h"
31 #include "ui/aura/window.h"
32 #include "ui/aura/window_event_dispatcher.h"
33 #include "ui/aura/window_observer.h"
34 #include "ui/base/resource/resource_bundle.h"
35 #include "ui/compositor/scoped_layer_animation_settings.h"
36 #include "ui/events/event.h"
37 #include "ui/gfx/canvas.h"
38 #include "ui/gfx/screen.h"
39 #include "ui/gfx/skia_util.h"
40 #include "ui/views/border.h"
41 #include "ui/views/controls/textfield/textfield.h"
42 #include "ui/views/layout/box_layout.h"
43 #include "ui/wm/core/window_util.h"
44 #include "ui/wm/public/activation_client.h"
46 namespace ash {
48 namespace {
50 // The proportion of screen width that the text filter takes.
51 const float kTextFilterScreenProportion = 0.25;
53 // The amount of padding surrounding the text in the text filtering textbox.
54 const int kTextFilterHorizontalPadding = 8;
56 // The distance between the top of the screen and the top edge of the
57 // text filtering textbox.
58 const int kTextFilterDistanceFromTop = 32;
60 // The height of the text filtering textbox.
61 const int kTextFilterHeight = 32;
63 // The font style used for text filtering.
64 static const ::ui::ResourceBundle::FontStyle kTextFilterFontStyle =
65 ::ui::ResourceBundle::FontStyle::MediumFont;
67 // The alpha value for the background of the text filtering textbox.
68 const unsigned char kTextFilterOpacity = 180;
70 // The radius used for the rounded corners on the text filtering textbox.
71 const int kTextFilterCornerRadius = 1;
73 // A comparator for locating a grid with a given root window.
74 struct RootWindowGridComparator
75 : public std::unary_function<WindowGrid*, bool> {
76 explicit RootWindowGridComparator(const aura::Window* root_window)
77 : root_window_(root_window) {
80 bool operator()(WindowGrid* grid) const {
81 return (grid->root_window() == root_window_);
84 const aura::Window* root_window_;
87 // A comparator for locating a selectable window given a targeted window.
88 struct WindowSelectorItemTargetComparator
89 : public std::unary_function<WindowSelectorItem*, bool> {
90 explicit WindowSelectorItemTargetComparator(const aura::Window* target_window)
91 : target(target_window) {
94 bool operator()(WindowSelectorItem* window) const {
95 return window->GetWindow() == target;
98 const aura::Window* target;
101 // A comparator for locating a selector item for a given root.
102 struct WindowSelectorItemForRoot
103 : public std::unary_function<WindowSelectorItem*, bool> {
104 explicit WindowSelectorItemForRoot(const aura::Window* root)
105 : root_window(root) {
108 bool operator()(WindowSelectorItem* item) const {
109 return item->root_window() == root_window;
112 const aura::Window* root_window;
115 // A View having rounded corners and a specified background color which is
116 // only painted within the bounds defined by the rounded corners.
117 // TODO(tdanderson): This duplicates code from RoundedImageView. Refactor these
118 // classes and move into ui/views.
119 class RoundedContainerView : public views::View {
120 public:
121 RoundedContainerView(int corner_radius, SkColor background)
122 : corner_radius_(corner_radius),
123 background_(background) {
126 ~RoundedContainerView() override {}
128 void OnPaint(gfx::Canvas* canvas) override {
129 views::View::OnPaint(canvas);
131 SkScalar radius = SkIntToScalar(corner_radius_);
132 const SkScalar kRadius[8] = {radius, radius, radius, radius,
133 radius, radius, radius, radius};
134 SkPath path;
135 gfx::Rect bounds(size());
136 path.addRoundRect(gfx::RectToSkRect(bounds), kRadius);
138 SkPaint paint;
139 paint.setAntiAlias(true);
140 canvas->ClipPath(path, true);
141 canvas->DrawColor(background_);
144 private:
145 int corner_radius_;
146 SkColor background_;
148 DISALLOW_COPY_AND_ASSIGN(RoundedContainerView);
151 // Triggers a shelf visibility update on all root window controllers.
152 void UpdateShelfVisibility() {
153 Shell::RootWindowControllerList root_window_controllers =
154 Shell::GetInstance()->GetAllRootWindowControllers();
155 for (Shell::RootWindowControllerList::iterator iter =
156 root_window_controllers.begin();
157 iter != root_window_controllers.end(); ++iter) {
158 (*iter)->UpdateShelfVisibility();
162 // Initializes the text filter on the top of the main root window and requests
163 // focus on its textfield.
164 views::Widget* CreateTextFilter(views::TextfieldController* controller,
165 aura::Window* root_window) {
166 views::Widget* widget = new views::Widget;
167 views::Widget::InitParams params;
168 params.type = views::Widget::InitParams::TYPE_WINDOW_FRAMELESS;
169 params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
170 params.opacity = views::Widget::InitParams::TRANSLUCENT_WINDOW;
171 params.parent = Shell::GetContainer(root_window,
172 kShellWindowId_OverlayContainer);
173 params.accept_events = true;
174 params.bounds = gfx::Rect(
175 root_window->bounds().width() / 2 * (1 - kTextFilterScreenProportion),
176 kTextFilterDistanceFromTop,
177 root_window->bounds().width() * kTextFilterScreenProportion,
178 kTextFilterHeight);
179 widget->Init(params);
181 // Use |container| to specify the padding surrounding the text and to give
182 // the textfield rounded corners.
183 views::View* container = new RoundedContainerView(
184 kTextFilterCornerRadius, SkColorSetARGB(kTextFilterOpacity, 0, 0, 0));
185 ui::ResourceBundle& bundle = ui::ResourceBundle::GetSharedInstance();
186 int text_height = bundle.GetFontList(kTextFilterFontStyle).GetHeight();
187 DCHECK(text_height);
188 int vertical_padding = (kTextFilterHeight - text_height) / 2;
189 container->SetLayoutManager(new views::BoxLayout(views::BoxLayout::kVertical,
190 kTextFilterHorizontalPadding,
191 vertical_padding,
192 0));
194 views::Textfield* textfield = new views::Textfield;
195 textfield->set_controller(controller);
196 textfield->SetBackgroundColor(SK_ColorTRANSPARENT);
197 textfield->SetBorder(views::Border::NullBorder());
198 textfield->SetTextColor(SK_ColorWHITE);
199 textfield->SetFontList(bundle.GetFontList(kTextFilterFontStyle));
201 container->AddChildView(textfield);
202 widget->SetContentsView(container);
204 // The textfield initially contains no text, so shift its position to be
205 // outside the visible bounds of the screen.
206 gfx::Transform transform;
207 transform.Translate(0, -WindowSelector::kTextFilterBottomEdge);
208 widget->GetNativeWindow()->SetTransform(transform);
209 widget->Show();
210 textfield->RequestFocus();
212 return widget;
215 } // namespace
217 const int WindowSelector::kTextFilterBottomEdge =
218 kTextFilterDistanceFromTop + kTextFilterHeight;
220 // static
221 bool WindowSelector::IsSelectable(aura::Window* window) {
222 wm::WindowState* state = wm::GetWindowState(window);
223 if (state->GetStateType() == wm::WINDOW_STATE_TYPE_DOCKED ||
224 state->GetStateType() == wm::WINDOW_STATE_TYPE_DOCKED_MINIMIZED) {
225 return false;
227 return window->type() == ui::wm::WINDOW_TYPE_NORMAL ||
228 window->type() == ui::wm::WINDOW_TYPE_PANEL;
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()),
238 num_key_presses_(0),
239 num_items_(0),
240 showing_selection_widget_(false),
241 text_filter_string_length_(0),
242 num_times_textfield_cleared_(0),
243 restoring_minimized_windows_(false) {
244 DCHECK(delegate_);
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 const aura::Window::Windows root_windows = Shell::GetAllRootWindows();
259 for (aura::Window::Windows::const_iterator iter = root_windows.begin();
260 iter != root_windows.end(); iter++) {
261 // Observed switchable containers for newly created windows on all root
262 // windows.
263 for (size_t i = 0; i < kSwitchableWindowContainerIdsLength; ++i) {
264 aura::Window* container = Shell::GetContainer(*iter,
265 kSwitchableWindowContainerIds[i]);
266 container->AddObserver(this);
267 observed_windows_.insert(container);
270 // Hide the callout widgets for panels. It is safe to call this for
271 // root windows that don't contain any panel windows.
272 static_cast<PanelLayoutManager*>(
273 Shell::GetContainer(*iter, kShellWindowId_PanelContainer)
274 ->layout_manager())->SetShowCalloutWidgets(false);
276 scoped_ptr<WindowGrid> grid(new WindowGrid(*iter, windows, this));
277 if (grid->empty())
278 continue;
279 num_items_ += grid->size();
280 grid_list_.push_back(grid.release());
284 // The calls to WindowGrid::PrepareForOverview() and CreateTextFilter(...)
285 // requires some LayoutManagers (ie PanelLayoutManager) to perform layouts
286 // so that windows are correctly visible and properly animated in overview
287 // mode. Otherwise these layouts should be suppressed during overview mode
288 // so they don't conflict with overview mode animations. The
289 // |restoring_minimized_windows_| flag enables the PanelLayoutManager to
290 // make this decision.
291 base::AutoReset<bool> auto_restoring_minimized_windows(
292 &restoring_minimized_windows_, true);
294 // Do not call PrepareForOverview until all items are added to window_list_
295 // as we don't want to cause any window updates until all windows in
296 // overview are observed. See http://crbug.com/384495.
297 for (WindowGrid* window_grid : grid_list_) {
298 window_grid->PrepareForOverview();
299 window_grid->PositionWindows(true);
302 text_filter_widget_.reset(
303 CreateTextFilter(this, Shell::GetPrimaryRootWindow()));
306 DCHECK(!grid_list_.empty());
307 UMA_HISTOGRAM_COUNTS_100("Ash.WindowSelector.Items", num_items_);
309 Shell* shell = Shell::GetInstance();
311 shell->activation_client()->AddObserver(this);
313 shell->GetScreen()->AddObserver(this);
314 shell->metrics()->RecordUserMetricsAction(UMA_WINDOW_OVERVIEW);
315 // Send an a11y alert.
316 shell->accessibility_delegate()->TriggerAccessibilityAlert(
317 ui::A11Y_ALERT_WINDOW_OVERVIEW_MODE_ENTERED);
319 UpdateShelfVisibility();
322 // NOTE: The work done in Shutdown() is not done in the destructor because it
323 // may cause other, unrelated classes, (ie PanelLayoutManager) to make indirect
324 // calls to restoring_minimized_windows() on a partially destructed object.
325 void WindowSelector::Shutdown() {
326 ResetFocusRestoreWindow(true);
327 RemoveAllObservers();
329 aura::Window::Windows root_windows = Shell::GetAllRootWindows();
330 for (aura::Window::Windows::const_iterator iter = root_windows.begin();
331 iter != root_windows.end(); iter++) {
332 // Un-hide the callout widgets for panels. It is safe to call this for
333 // root_windows that don't contain any panel windows.
334 static_cast<PanelLayoutManager*>(
335 Shell::GetContainer(*iter, kShellWindowId_PanelContainer)
336 ->layout_manager())->SetShowCalloutWidgets(true);
339 size_t remaining_items = 0;
340 for (WindowGrid* window_grid : grid_list_) {
341 for (WindowSelectorItem* window_selector_item : window_grid->window_list())
342 window_selector_item->RestoreWindow();
343 remaining_items += window_grid->size();
346 DCHECK(num_items_ >= remaining_items);
347 UMA_HISTOGRAM_COUNTS_100("Ash.WindowSelector.OverviewClosedItems",
348 num_items_ - remaining_items);
349 UMA_HISTOGRAM_MEDIUM_TIMES("Ash.WindowSelector.TimeInOverview",
350 base::Time::Now() - overview_start_time_);
352 // Record metrics related to text filtering.
353 UMA_HISTOGRAM_COUNTS_100("Ash.WindowSelector.TextFilteringStringLength",
354 text_filter_string_length_);
355 UMA_HISTOGRAM_COUNTS_100("Ash.WindowSelector.TextFilteringTextfieldCleared",
356 num_times_textfield_cleared_);
357 if (text_filter_string_length_) {
358 UMA_HISTOGRAM_MEDIUM_TIMES(
359 "Ash.WindowSelector.TimeInOverviewWithTextFiltering",
360 base::Time::Now() - overview_start_time_);
361 UMA_HISTOGRAM_COUNTS_100(
362 "Ash.WindowSelector.ItemsWhenTextFilteringUsed",
363 remaining_items);
366 // Clearing the window list resets the ignored_by_shelf flag on the windows.
367 grid_list_.clear();
368 UpdateShelfVisibility();
371 void WindowSelector::RemoveAllObservers() {
372 Shell* shell = Shell::GetInstance();
373 for (aura::Window* window : observed_windows_)
374 window->RemoveObserver(this);
376 shell->activation_client()->RemoveObserver(this);
377 shell->GetScreen()->RemoveObserver(this);
378 if (restore_focus_window_)
379 restore_focus_window_->RemoveObserver(this);
382 void WindowSelector::CancelSelection() {
383 delegate_->OnSelectionEnded();
386 void WindowSelector::OnGridEmpty(WindowGrid* grid) {
387 ScopedVector<WindowGrid>::iterator iter =
388 std::find(grid_list_.begin(), grid_list_.end(), grid);
389 DCHECK(iter != grid_list_.end());
390 grid_list_.erase(iter);
391 // TODO(flackr): Use the previous index for more than two displays.
392 selected_grid_index_ = 0;
393 if (grid_list_.empty())
394 CancelSelection();
397 void WindowSelector::SelectWindow(aura::Window* window) {
398 // Record UMA_WINDOW_OVERVIEW_ACTIVE_WINDOW_CHANGED if the user is selecting
399 // a window other than the window that was active prior to entering overview
400 // mode (i.e., the window at the front of the MRU list).
401 MruWindowTracker::WindowList window_list =
402 Shell::GetInstance()->mru_window_tracker()->BuildMruWindowList();
403 if (window_list.size() > 0 && window_list[0] != window) {
404 Shell::GetInstance()->metrics()->RecordUserMetricsAction(
405 UMA_WINDOW_OVERVIEW_ACTIVE_WINDOW_CHANGED);
408 wm::GetWindowState(window)->Activate();
411 bool WindowSelector::HandleKeyEvent(views::Textfield* sender,
412 const ui::KeyEvent& key_event) {
413 if (key_event.type() != ui::ET_KEY_PRESSED)
414 return false;
416 switch (key_event.key_code()) {
417 case ui::VKEY_ESCAPE:
418 CancelSelection();
419 break;
420 case ui::VKEY_UP:
421 num_key_presses_++;
422 Move(WindowSelector::UP, true);
423 break;
424 case ui::VKEY_DOWN:
425 num_key_presses_++;
426 Move(WindowSelector::DOWN, true);
427 break;
428 case ui::VKEY_RIGHT:
429 case ui::VKEY_TAB:
430 num_key_presses_++;
431 Move(WindowSelector::RIGHT, true);
432 break;
433 case ui::VKEY_LEFT:
434 num_key_presses_++;
435 Move(WindowSelector::LEFT, true);
436 break;
437 case ui::VKEY_RETURN:
438 // Ignore if no item is selected.
439 if (!grid_list_[selected_grid_index_]->is_selecting())
440 return false;
441 UMA_HISTOGRAM_COUNTS_100("Ash.WindowSelector.ArrowKeyPresses",
442 num_key_presses_);
443 UMA_HISTOGRAM_CUSTOM_COUNTS(
444 "Ash.WindowSelector.KeyPressesOverItemsRatio",
445 (num_key_presses_ * 100) / num_items_, 1, 300, 30);
446 Shell::GetInstance()->metrics()->RecordUserMetricsAction(
447 UMA_WINDOW_OVERVIEW_ENTER_KEY);
448 SelectWindow(
449 grid_list_[selected_grid_index_]->SelectedWindow()->GetWindow());
450 break;
451 default:
452 // Not a key we are interested in, allow the textfield to handle it.
453 return false;
455 return true;
458 void WindowSelector::OnDisplayAdded(const gfx::Display& display) {
461 void WindowSelector::OnDisplayRemoved(const gfx::Display& display) {
462 // TODO(flackr): Keep window selection active on remaining displays.
463 CancelSelection();
466 void WindowSelector::OnDisplayMetricsChanged(const gfx::Display& display,
467 uint32_t metrics) {
468 PositionWindows(/* animate */ false);
471 void WindowSelector::OnWindowAdded(aura::Window* new_window) {
472 if (!IsSelectable(new_window))
473 return;
475 for (size_t i = 0; i < kSwitchableWindowContainerIdsLength; ++i) {
476 if (new_window->parent()->id() == kSwitchableWindowContainerIds[i] &&
477 !::wm::GetTransientParent(new_window)) {
478 // The new window is in one of the switchable containers, abort overview.
479 CancelSelection();
480 return;
485 void WindowSelector::OnWindowDestroying(aura::Window* window) {
486 window->RemoveObserver(this);
487 observed_windows_.erase(window);
488 if (window == restore_focus_window_)
489 restore_focus_window_ = nullptr;
492 void WindowSelector::OnWindowActivated(aura::Window* gained_active,
493 aura::Window* lost_active) {
494 if (ignore_activations_ ||
495 !gained_active ||
496 gained_active == text_filter_widget_->GetNativeWindow()) {
497 return;
500 ScopedVector<WindowGrid>::iterator grid =
501 std::find_if(grid_list_.begin(), grid_list_.end(),
502 RootWindowGridComparator(gained_active->GetRootWindow()));
503 if (grid == grid_list_.end())
504 return;
505 const std::vector<WindowSelectorItem*> windows = (*grid)->window_list();
507 ScopedVector<WindowSelectorItem>::const_iterator iter = std::find_if(
508 windows.begin(), windows.end(),
509 WindowSelectorItemTargetComparator(gained_active));
511 if (iter != windows.end())
512 (*iter)->ShowWindowOnExit();
514 // Don't restore focus on exit if a window was just activated.
515 ResetFocusRestoreWindow(false);
516 CancelSelection();
519 void WindowSelector::OnAttemptToReactivateWindow(aura::Window* request_active,
520 aura::Window* actual_active) {
521 OnWindowActivated(request_active, actual_active);
524 void WindowSelector::ContentsChanged(views::Textfield* sender,
525 const base::string16& new_contents) {
526 text_filter_string_length_ = new_contents.length();
527 if (!text_filter_string_length_)
528 num_times_textfield_cleared_++;
530 bool should_show_selection_widget = !new_contents.empty();
531 if (showing_selection_widget_ != should_show_selection_widget) {
532 ui::ScopedLayerAnimationSettings animation_settings(
533 text_filter_widget_->GetNativeWindow()->layer()->GetAnimator());
534 animation_settings.SetPreemptionStrategy(
535 ui::LayerAnimator::IMMEDIATELY_ANIMATE_TO_NEW_TARGET);
536 animation_settings.SetTweenType(showing_selection_widget_ ?
537 gfx::Tween::FAST_OUT_LINEAR_IN : gfx::Tween::LINEAR_OUT_SLOW_IN);
539 gfx::Transform transform;
540 if (should_show_selection_widget) {
541 transform.Translate(0, 0);
542 text_filter_widget_->GetNativeWindow()->layer()->SetOpacity(1);
543 } else {
544 transform.Translate(0, -kTextFilterBottomEdge);
545 text_filter_widget_->GetNativeWindow()->layer()->SetOpacity(0);
548 text_filter_widget_->GetNativeWindow()->SetTransform(transform);
549 showing_selection_widget_ = should_show_selection_widget;
551 for (ScopedVector<WindowGrid>::iterator iter = grid_list_.begin();
552 iter != grid_list_.end(); iter++) {
553 (*iter)->FilterItems(new_contents);
556 // If the selection widget is not active, execute a Move() command so that it
557 // shows up on the first undimmed item.
558 if (grid_list_[selected_grid_index_]->is_selecting())
559 return;
560 Move(WindowSelector::RIGHT, false);
563 void WindowSelector::PositionWindows(bool animate) {
564 for (ScopedVector<WindowGrid>::iterator iter = grid_list_.begin();
565 iter != grid_list_.end(); iter++) {
566 (*iter)->PositionWindows(animate);
570 void WindowSelector::ResetFocusRestoreWindow(bool focus) {
571 if (!restore_focus_window_)
572 return;
573 if (focus) {
574 base::AutoReset<bool> restoring_focus(&ignore_activations_, true);
575 restore_focus_window_->Focus();
577 // If the window is in the observed_windows_ list it needs to continue to be
578 // observed.
579 if (observed_windows_.find(restore_focus_window_) ==
580 observed_windows_.end()) {
581 restore_focus_window_->RemoveObserver(this);
583 restore_focus_window_ = nullptr;
586 void WindowSelector::Move(Direction direction, bool animate) {
587 // Keep calling Move() on the grids until one of them reports no overflow or
588 // we made a full cycle on all the grids.
589 for (size_t i = 0;
590 i <= grid_list_.size() &&
591 grid_list_[selected_grid_index_]->Move(direction, animate); i++) {
592 // TODO(flackr): If there are more than two monitors, move between grids
593 // in the requested direction.
594 selected_grid_index_ = (selected_grid_index_ + 1) % grid_list_.size();
598 } // namespace ash