Put WeakPtrFactory member last in USBEventRouter
[chromium-blink-merge.git] / ash / wm / overview / window_selector.cc
blob76eb46a10de22b2b98d4e610d1ea44844cbcd665
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 <set>
9 #include <vector>
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/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->Contains(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 WindowSelector::WindowSelector(const WindowList& windows,
221 WindowSelectorDelegate* delegate)
222 : delegate_(delegate),
223 restore_focus_window_(aura::client::GetFocusClient(
224 Shell::GetPrimaryRootWindow())->GetFocusedWindow()),
225 ignore_activations_(false),
226 selected_grid_index_(0),
227 overview_start_time_(base::Time::Now()),
228 num_key_presses_(0),
229 num_items_(0),
230 showing_selection_widget_(false),
231 text_filter_string_length_(0),
232 num_times_textfield_cleared_(0) {
233 DCHECK(delegate_);
234 Shell* shell = Shell::GetInstance();
235 shell->OnOverviewModeStarting();
237 if (restore_focus_window_)
238 restore_focus_window_->AddObserver(this);
240 const aura::Window::Windows root_windows = Shell::GetAllRootWindows();
241 for (aura::Window::Windows::const_iterator iter = root_windows.begin();
242 iter != root_windows.end(); iter++) {
243 // Observed switchable containers for newly created windows on all root
244 // windows.
245 for (size_t i = 0; i < kSwitchableWindowContainerIdsLength; ++i) {
246 aura::Window* container = Shell::GetContainer(*iter,
247 kSwitchableWindowContainerIds[i]);
248 container->AddObserver(this);
249 observed_windows_.insert(container);
252 // Hide the callout widgets for panels. It is safe to call this for
253 // root windows that don't contain any panel windows.
254 static_cast<PanelLayoutManager*>(
255 Shell::GetContainer(*iter, kShellWindowId_PanelContainer)
256 ->layout_manager())->SetShowCalloutWidgets(false);
258 scoped_ptr<WindowGrid> grid(new WindowGrid(*iter, windows, this));
259 if (grid->empty())
260 continue;
261 num_items_ += grid->size();
262 grid_list_.push_back(grid.release());
265 // Do not call PrepareForOverview until all items are added to window_list_ as
266 // we don't want to cause any window updates until all windows in overview
267 // are observed. See http://crbug.com/384495.
268 for (ScopedVector<WindowGrid>::iterator iter = grid_list_.begin();
269 iter != grid_list_.end(); ++iter) {
270 (*iter)->PrepareForOverview();
271 (*iter)->PositionWindows(true);
274 DCHECK(!grid_list_.empty());
275 UMA_HISTOGRAM_COUNTS_100("Ash.WindowSelector.Items", num_items_);
277 text_filter_widget_.reset(
278 CreateTextFilter(this, Shell::GetPrimaryRootWindow()));
280 shell->activation_client()->AddObserver(this);
282 shell->GetScreen()->AddObserver(this);
283 shell->metrics()->RecordUserMetricsAction(UMA_WINDOW_OVERVIEW);
284 HideAndTrackNonOverviewWindows();
285 // Send an a11y alert.
286 shell->accessibility_delegate()->TriggerAccessibilityAlert(
287 ui::A11Y_ALERT_WINDOW_OVERVIEW_MODE_ENTERED);
289 UpdateShelfVisibility();
292 WindowSelector::~WindowSelector() {
293 Shell* shell = Shell::GetInstance();
295 ResetFocusRestoreWindow(true);
296 for (std::set<aura::Window*>::iterator iter = observed_windows_.begin();
297 iter != observed_windows_.end(); ++iter) {
298 (*iter)->RemoveObserver(this);
300 shell->activation_client()->RemoveObserver(this);
302 aura::Window::Windows root_windows = Shell::GetAllRootWindows();
303 for (aura::Window::Windows::const_iterator iter = root_windows.begin();
304 iter != root_windows.end(); iter++) {
305 // Un-hide the callout widgets for panels. It is safe to call this for
306 // root_windows that don't contain any panel windows.
307 static_cast<PanelLayoutManager*>(
308 Shell::GetContainer(*iter, kShellWindowId_PanelContainer)
309 ->layout_manager())->SetShowCalloutWidgets(true);
312 const aura::WindowTracker::Windows hidden_windows(hidden_windows_.windows());
313 for (aura::WindowTracker::Windows::const_iterator iter =
314 hidden_windows.begin(); iter != hidden_windows.end(); ++iter) {
315 ScopedOverviewAnimationSettings animation_settings(
316 OverviewAnimationType::OVERVIEW_ANIMATION_LAY_OUT_SELECTOR_ITEMS,
317 *iter);
318 (*iter)->layer()->SetOpacity(1);
319 (*iter)->Show();
322 shell->GetScreen()->RemoveObserver(this);
324 size_t remaining_items = 0;
325 for (ScopedVector<WindowGrid>::iterator iter = grid_list_.begin();
326 iter != grid_list_.end(); iter++) {
327 remaining_items += (*iter)->size();
330 DCHECK(num_items_ >= remaining_items);
331 UMA_HISTOGRAM_COUNTS_100("Ash.WindowSelector.OverviewClosedItems",
332 num_items_ - remaining_items);
333 UMA_HISTOGRAM_MEDIUM_TIMES("Ash.WindowSelector.TimeInOverview",
334 base::Time::Now() - overview_start_time_);
336 // Record metrics related to text filtering.
337 UMA_HISTOGRAM_COUNTS_100("Ash.WindowSelector.TextFilteringStringLength",
338 text_filter_string_length_);
339 UMA_HISTOGRAM_COUNTS_100("Ash.WindowSelector.TextFilteringTextfieldCleared",
340 num_times_textfield_cleared_);
341 if (text_filter_string_length_) {
342 UMA_HISTOGRAM_MEDIUM_TIMES(
343 "Ash.WindowSelector.TimeInOverviewWithTextFiltering",
344 base::Time::Now() - overview_start_time_);
345 UMA_HISTOGRAM_COUNTS_100(
346 "Ash.WindowSelector.ItemsWhenTextFilteringUsed",
347 remaining_items);
350 // TODO(flackr): Change this to OnOverviewModeEnded and move it to when
351 // everything is done.
352 shell->OnOverviewModeEnding();
354 // Clearing the window list resets the ignored_by_shelf flag on the windows.
355 grid_list_.clear();
356 UpdateShelfVisibility();
359 void WindowSelector::CancelSelection() {
360 delegate_->OnSelectionEnded();
363 void WindowSelector::OnGridEmpty(WindowGrid* grid) {
364 ScopedVector<WindowGrid>::iterator iter =
365 std::find(grid_list_.begin(), grid_list_.end(), grid);
366 DCHECK(iter != grid_list_.end());
367 grid_list_.erase(iter);
368 // TODO(flackr): Use the previous index for more than two displays.
369 selected_grid_index_ = 0;
370 if (grid_list_.empty())
371 CancelSelection();
374 bool WindowSelector::HandleKeyEvent(views::Textfield* sender,
375 const ui::KeyEvent& key_event) {
376 if (key_event.type() != ui::ET_KEY_PRESSED)
377 return false;
379 switch (key_event.key_code()) {
380 case ui::VKEY_ESCAPE:
381 CancelSelection();
382 break;
383 case ui::VKEY_UP:
384 num_key_presses_++;
385 Move(WindowSelector::UP, true);
386 break;
387 case ui::VKEY_DOWN:
388 num_key_presses_++;
389 Move(WindowSelector::DOWN, true);
390 break;
391 case ui::VKEY_RIGHT:
392 case ui::VKEY_TAB:
393 num_key_presses_++;
394 Move(WindowSelector::RIGHT, true);
395 break;
396 case ui::VKEY_LEFT:
397 num_key_presses_++;
398 Move(WindowSelector::LEFT, true);
399 break;
400 case ui::VKEY_RETURN:
401 // Ignore if no item is selected.
402 if (!grid_list_[selected_grid_index_]->is_selecting())
403 return false;
404 UMA_HISTOGRAM_COUNTS_100("Ash.WindowSelector.ArrowKeyPresses",
405 num_key_presses_);
406 UMA_HISTOGRAM_CUSTOM_COUNTS(
407 "Ash.WindowSelector.KeyPressesOverItemsRatio",
408 (num_key_presses_ * 100) / num_items_, 1, 300, 30);
409 Shell::GetInstance()->metrics()->RecordUserMetricsAction(
410 UMA_WINDOW_OVERVIEW_ENTER_KEY);
411 wm::GetWindowState(grid_list_[selected_grid_index_]->
412 SelectedWindow()->SelectionWindow())->Activate();
413 break;
414 default:
415 // Not a key we are interested in, allow the textfield to handle it.
416 return false;
418 return true;
421 void WindowSelector::OnDisplayAdded(const gfx::Display& display) {
424 void WindowSelector::OnDisplayRemoved(const gfx::Display& display) {
425 // TODO(flackr): Keep window selection active on remaining displays.
426 CancelSelection();
429 void WindowSelector::OnDisplayMetricsChanged(const gfx::Display& display,
430 uint32_t metrics) {
431 PositionWindows(/* animate */ false);
434 void WindowSelector::OnWindowAdded(aura::Window* new_window) {
435 if (new_window->type() != ui::wm::WINDOW_TYPE_NORMAL &&
436 new_window->type() != ui::wm::WINDOW_TYPE_PANEL) {
437 return;
440 for (size_t i = 0; i < kSwitchableWindowContainerIdsLength; ++i) {
441 if (new_window->parent()->id() == kSwitchableWindowContainerIds[i] &&
442 !::wm::GetTransientParent(new_window)) {
443 // The new window is in one of the switchable containers, abort overview.
444 CancelSelection();
445 return;
450 void WindowSelector::OnWindowDestroying(aura::Window* window) {
451 window->RemoveObserver(this);
452 observed_windows_.erase(window);
453 if (window == restore_focus_window_)
454 restore_focus_window_ = nullptr;
457 void WindowSelector::OnWindowActivated(aura::Window* gained_active,
458 aura::Window* lost_active) {
459 if (ignore_activations_ ||
460 !gained_active ||
461 gained_active == text_filter_widget_->GetNativeWindow()) {
462 return;
465 ScopedVector<WindowGrid>::iterator grid =
466 std::find_if(grid_list_.begin(), grid_list_.end(),
467 RootWindowGridComparator(gained_active->GetRootWindow()));
468 if (grid == grid_list_.end())
469 return;
470 const std::vector<WindowSelectorItem*> windows = (*grid)->window_list();
472 ScopedVector<WindowSelectorItem>::const_iterator iter = std::find_if(
473 windows.begin(), windows.end(),
474 WindowSelectorItemTargetComparator(gained_active));
476 if (iter != windows.end())
477 (*iter)->RestoreWindowOnExit(gained_active);
479 // Don't restore focus on exit if a window was just activated.
480 ResetFocusRestoreWindow(false);
481 CancelSelection();
484 void WindowSelector::OnAttemptToReactivateWindow(aura::Window* request_active,
485 aura::Window* actual_active) {
486 OnWindowActivated(request_active, actual_active);
489 void WindowSelector::ContentsChanged(views::Textfield* sender,
490 const base::string16& new_contents) {
491 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
492 switches::kAshDisableTextFilteringInOverviewMode)) {
493 return;
496 text_filter_string_length_ = new_contents.length();
497 if (!text_filter_string_length_)
498 num_times_textfield_cleared_++;
500 bool should_show_selection_widget = !new_contents.empty();
501 if (showing_selection_widget_ != should_show_selection_widget) {
502 ui::ScopedLayerAnimationSettings animation_settings(
503 text_filter_widget_->GetNativeWindow()->layer()->GetAnimator());
504 animation_settings.SetPreemptionStrategy(
505 ui::LayerAnimator::IMMEDIATELY_ANIMATE_TO_NEW_TARGET);
506 animation_settings.SetTweenType(showing_selection_widget_ ?
507 gfx::Tween::FAST_OUT_LINEAR_IN : gfx::Tween::LINEAR_OUT_SLOW_IN);
509 gfx::Transform transform;
510 if (should_show_selection_widget) {
511 transform.Translate(0, 0);
512 text_filter_widget_->GetNativeWindow()->layer()->SetOpacity(1);
513 } else {
514 transform.Translate(0, -kTextFilterBottomEdge);
515 text_filter_widget_->GetNativeWindow()->layer()->SetOpacity(0);
518 text_filter_widget_->GetNativeWindow()->SetTransform(transform);
519 showing_selection_widget_ = should_show_selection_widget;
521 for (ScopedVector<WindowGrid>::iterator iter = grid_list_.begin();
522 iter != grid_list_.end(); iter++) {
523 (*iter)->FilterItems(new_contents);
526 // If the selection widget is not active, execute a Move() command so that it
527 // shows up on the first undimmed item.
528 if (grid_list_[selected_grid_index_]->is_selecting())
529 return;
530 Move(WindowSelector::RIGHT, false);
533 void WindowSelector::PositionWindows(bool animate) {
534 for (ScopedVector<WindowGrid>::iterator iter = grid_list_.begin();
535 iter != grid_list_.end(); iter++) {
536 (*iter)->PositionWindows(animate);
540 void WindowSelector::HideAndTrackNonOverviewWindows() {
541 // Add the windows to hidden_windows first so that if any are destroyed
542 // while hiding them they are tracked.
543 for (ScopedVector<WindowGrid>::iterator grid_iter = grid_list_.begin();
544 grid_iter != grid_list_.end(); ++grid_iter) {
545 for (size_t i = 0; i < kSwitchableWindowContainerIdsLength; ++i) {
546 const aura::Window* container =
547 Shell::GetContainer((*grid_iter)->root_window(),
548 kSwitchableWindowContainerIds[i]);
549 for (aura::Window::Windows::const_iterator iter =
550 container->children().begin(); iter != container->children().end();
551 ++iter) {
552 if (!(*iter)->IsVisible() || (*grid_iter)->Contains(*iter))
553 continue;
554 hidden_windows_.Add(*iter);
559 // Copy the window list as it can change during iteration.
560 const aura::WindowTracker::Windows hidden_windows(hidden_windows_.windows());
561 for (aura::WindowTracker::Windows::const_iterator iter =
562 hidden_windows.begin(); iter != hidden_windows.end(); ++iter) {
563 if (!hidden_windows_.Contains(*iter))
564 continue;
565 ScopedOverviewAnimationSettings animation_settings(
566 OverviewAnimationType::OVERVIEW_ANIMATION_HIDE_WINDOW,
567 *iter);
568 (*iter)->Hide();
569 // Hiding the window can result in it being destroyed.
570 if (!hidden_windows_.Contains(*iter))
571 continue;
572 (*iter)->layer()->SetOpacity(0);
576 void WindowSelector::ResetFocusRestoreWindow(bool focus) {
577 if (!restore_focus_window_)
578 return;
579 if (focus) {
580 base::AutoReset<bool> restoring_focus(&ignore_activations_, true);
581 restore_focus_window_->Focus();
583 // If the window is in the observed_windows_ list it needs to continue to be
584 // observed.
585 if (observed_windows_.find(restore_focus_window_) ==
586 observed_windows_.end()) {
587 restore_focus_window_->RemoveObserver(this);
589 restore_focus_window_ = nullptr;
592 void WindowSelector::Move(Direction direction, bool animate) {
593 // Keep calling Move() on the grids until one of them reports no overflow or
594 // we made a full cycle on all the grids.
595 for (size_t i = 0;
596 i <= grid_list_.size() &&
597 grid_list_[selected_grid_index_]->Move(direction, animate); i++) {
598 // TODO(flackr): If there are more than two monitors, move between grids
599 // in the requested direction.
600 selected_grid_index_ = (selected_grid_index_ + 1) % grid_list_.size();
604 } // namespace ash