[Ozone-Gbm] Explicitly crash if trying software rendering on GBM
[chromium-blink-merge.git] / ash / wm / overview / window_selector.cc
blob6230b9b7c50331bd1f818be81e233deedbbd7c59
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/overview/scoped_overview_animation_settings.h"
20 #include "ash/wm/overview/scoped_transform_overview_window.h"
21 #include "ash/wm/overview/window_grid.h"
22 #include "ash/wm/overview/window_selector_delegate.h"
23 #include "ash/wm/overview/window_selector_item.h"
24 #include "ash/wm/panels/panel_layout_manager.h"
25 #include "ash/wm/window_state.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"
47 namespace ash {
49 namespace {
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 {
121 public:
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};
135 SkPath path;
136 gfx::Rect bounds(size());
137 path.addRoundRect(gfx::RectToSkRect(bounds), kRadius);
139 SkPaint paint;
140 paint.setAntiAlias(true);
141 canvas->ClipPath(path, true);
142 canvas->DrawColor(background_);
145 private:
146 int corner_radius_;
147 SkColor 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,
179 kTextFilterHeight);
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();
188 DCHECK(text_height);
189 int vertical_padding = (kTextFilterHeight - text_height) / 2;
190 container->SetLayoutManager(new views::BoxLayout(views::BoxLayout::kVertical,
191 kTextFilterHorizontalPadding,
192 vertical_padding,
193 0));
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);
210 widget->Show();
211 textfield->RequestFocus();
213 return widget;
216 } // namespace
218 const int WindowSelector::kTextFilterBottomEdge =
219 kTextFilterDistanceFromTop + kTextFilterHeight;
221 WindowSelector::WindowSelector(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 restoring_minimized_windows_(false) {
234 DCHECK(delegate_);
237 WindowSelector::~WindowSelector() {
238 RemoveAllObservers();
241 // NOTE: The work done in Init() is not done in the constructor because it may
242 // cause other, unrelated classes, (ie PanelLayoutManager) to make indirect
243 // calls to restoring_minimized_windows() on a partially constructed object.
244 void WindowSelector::Init(const WindowList& windows) {
245 if (restore_focus_window_)
246 restore_focus_window_->AddObserver(this);
248 const aura::Window::Windows root_windows = Shell::GetAllRootWindows();
249 for (aura::Window::Windows::const_iterator iter = root_windows.begin();
250 iter != root_windows.end(); iter++) {
251 // Observed switchable containers for newly created windows on all root
252 // windows.
253 for (size_t i = 0; i < kSwitchableWindowContainerIdsLength; ++i) {
254 aura::Window* container = Shell::GetContainer(*iter,
255 kSwitchableWindowContainerIds[i]);
256 container->AddObserver(this);
257 observed_windows_.insert(container);
260 // Hide the callout widgets for panels. It is safe to call this for
261 // root windows that don't contain any panel windows.
262 static_cast<PanelLayoutManager*>(
263 Shell::GetContainer(*iter, kShellWindowId_PanelContainer)
264 ->layout_manager())->SetShowCalloutWidgets(false);
266 scoped_ptr<WindowGrid> grid(new WindowGrid(*iter, windows, this));
267 if (grid->empty())
268 continue;
269 num_items_ += grid->size();
270 grid_list_.push_back(grid.release());
274 // The calls to WindowGrid::PrepareForOverview() and CreateTextFilter(...)
275 // requires some LayoutManagers (ie PanelLayoutManager) to perform layouts
276 // so that windows are correctly visible and properly animated in overview
277 // mode. Otherwise these layouts should be suppressed during overview mode
278 // so they don't conflict with overview mode animations. The
279 // |restoring_minimized_windows_| flag enables the PanelLayoutManager to
280 // make this decision.
281 base::AutoReset<bool> auto_restoring_minimized_windows(
282 &restoring_minimized_windows_, true);
284 // Do not call PrepareForOverview until all items are added to window_list_
285 // as we don't want to cause any window updates until all windows in
286 // overview are observed. See http://crbug.com/384495.
287 for (WindowGrid* window_grid : grid_list_) {
288 window_grid->PrepareForOverview();
289 window_grid->PositionWindows(true);
292 text_filter_widget_.reset(
293 CreateTextFilter(this, Shell::GetPrimaryRootWindow()));
296 DCHECK(!grid_list_.empty());
297 UMA_HISTOGRAM_COUNTS_100("Ash.WindowSelector.Items", num_items_);
299 Shell* shell = Shell::GetInstance();
301 shell->activation_client()->AddObserver(this);
303 shell->GetScreen()->AddObserver(this);
304 shell->metrics()->RecordUserMetricsAction(UMA_WINDOW_OVERVIEW);
305 HideAndTrackNonOverviewWindows();
306 // Send an a11y alert.
307 shell->accessibility_delegate()->TriggerAccessibilityAlert(
308 ui::A11Y_ALERT_WINDOW_OVERVIEW_MODE_ENTERED);
310 UpdateShelfVisibility();
313 // NOTE: The work done in Shutdown() is not done in the destructor because it
314 // may cause other, unrelated classes, (ie PanelLayoutManager) to make indirect
315 // calls to restoring_minimized_windows() on a partially destructed object.
316 void WindowSelector::Shutdown() {
317 ResetFocusRestoreWindow(true);
318 RemoveAllObservers();
320 aura::Window::Windows root_windows = Shell::GetAllRootWindows();
321 for (aura::Window::Windows::const_iterator iter = root_windows.begin();
322 iter != root_windows.end(); iter++) {
323 // Un-hide the callout widgets for panels. It is safe to call this for
324 // root_windows that don't contain any panel windows.
325 static_cast<PanelLayoutManager*>(
326 Shell::GetContainer(*iter, kShellWindowId_PanelContainer)
327 ->layout_manager())->SetShowCalloutWidgets(true);
330 const aura::WindowTracker::Windows hidden_windows(hidden_windows_.windows());
331 for (aura::WindowTracker::Windows::const_iterator iter =
332 hidden_windows.begin(); iter != hidden_windows.end(); ++iter) {
333 ScopedOverviewAnimationSettings animation_settings(
334 OverviewAnimationType::OVERVIEW_ANIMATION_LAY_OUT_SELECTOR_ITEMS,
335 *iter);
336 (*iter)->layer()->SetOpacity(1);
337 (*iter)->Show();
340 size_t remaining_items = 0;
341 for (WindowGrid* window_grid : grid_list_) {
342 for (WindowSelectorItem* window_selector_item : window_grid->window_list())
343 window_selector_item->RestoreWindow();
344 remaining_items += window_grid->size();
347 DCHECK(num_items_ >= remaining_items);
348 UMA_HISTOGRAM_COUNTS_100("Ash.WindowSelector.OverviewClosedItems",
349 num_items_ - remaining_items);
350 UMA_HISTOGRAM_MEDIUM_TIMES("Ash.WindowSelector.TimeInOverview",
351 base::Time::Now() - overview_start_time_);
353 // Record metrics related to text filtering.
354 UMA_HISTOGRAM_COUNTS_100("Ash.WindowSelector.TextFilteringStringLength",
355 text_filter_string_length_);
356 UMA_HISTOGRAM_COUNTS_100("Ash.WindowSelector.TextFilteringTextfieldCleared",
357 num_times_textfield_cleared_);
358 if (text_filter_string_length_) {
359 UMA_HISTOGRAM_MEDIUM_TIMES(
360 "Ash.WindowSelector.TimeInOverviewWithTextFiltering",
361 base::Time::Now() - overview_start_time_);
362 UMA_HISTOGRAM_COUNTS_100(
363 "Ash.WindowSelector.ItemsWhenTextFilteringUsed",
364 remaining_items);
367 // Clearing the window list resets the ignored_by_shelf flag on the windows.
368 grid_list_.clear();
369 UpdateShelfVisibility();
372 void WindowSelector::RemoveAllObservers() {
373 Shell* shell = Shell::GetInstance();
374 for (aura::Window* window : observed_windows_)
375 window->RemoveObserver(this);
377 shell->activation_client()->RemoveObserver(this);
378 shell->GetScreen()->RemoveObserver(this);
379 if (restore_focus_window_)
380 restore_focus_window_->RemoveObserver(this);
383 void WindowSelector::CancelSelection() {
384 delegate_->OnSelectionEnded();
387 void WindowSelector::OnGridEmpty(WindowGrid* grid) {
388 ScopedVector<WindowGrid>::iterator iter =
389 std::find(grid_list_.begin(), grid_list_.end(), grid);
390 DCHECK(iter != grid_list_.end());
391 grid_list_.erase(iter);
392 // TODO(flackr): Use the previous index for more than two displays.
393 selected_grid_index_ = 0;
394 if (grid_list_.empty())
395 CancelSelection();
398 bool WindowSelector::HandleKeyEvent(views::Textfield* sender,
399 const ui::KeyEvent& key_event) {
400 if (key_event.type() != ui::ET_KEY_PRESSED)
401 return false;
403 switch (key_event.key_code()) {
404 case ui::VKEY_ESCAPE:
405 CancelSelection();
406 break;
407 case ui::VKEY_UP:
408 num_key_presses_++;
409 Move(WindowSelector::UP, true);
410 break;
411 case ui::VKEY_DOWN:
412 num_key_presses_++;
413 Move(WindowSelector::DOWN, true);
414 break;
415 case ui::VKEY_RIGHT:
416 case ui::VKEY_TAB:
417 num_key_presses_++;
418 Move(WindowSelector::RIGHT, true);
419 break;
420 case ui::VKEY_LEFT:
421 num_key_presses_++;
422 Move(WindowSelector::LEFT, true);
423 break;
424 case ui::VKEY_RETURN:
425 // Ignore if no item is selected.
426 if (!grid_list_[selected_grid_index_]->is_selecting())
427 return false;
428 UMA_HISTOGRAM_COUNTS_100("Ash.WindowSelector.ArrowKeyPresses",
429 num_key_presses_);
430 UMA_HISTOGRAM_CUSTOM_COUNTS(
431 "Ash.WindowSelector.KeyPressesOverItemsRatio",
432 (num_key_presses_ * 100) / num_items_, 1, 300, 30);
433 Shell::GetInstance()->metrics()->RecordUserMetricsAction(
434 UMA_WINDOW_OVERVIEW_ENTER_KEY);
435 wm::GetWindowState(grid_list_[selected_grid_index_]->
436 SelectedWindow()->GetWindow())->Activate();
437 break;
438 default:
439 // Not a key we are interested in, allow the textfield to handle it.
440 return false;
442 return true;
445 void WindowSelector::OnDisplayAdded(const gfx::Display& display) {
448 void WindowSelector::OnDisplayRemoved(const gfx::Display& display) {
449 // TODO(flackr): Keep window selection active on remaining displays.
450 CancelSelection();
453 void WindowSelector::OnDisplayMetricsChanged(const gfx::Display& display,
454 uint32_t metrics) {
455 PositionWindows(/* animate */ false);
458 void WindowSelector::OnWindowAdded(aura::Window* new_window) {
459 if (new_window->type() != ui::wm::WINDOW_TYPE_NORMAL &&
460 new_window->type() != ui::wm::WINDOW_TYPE_PANEL) {
461 return;
464 for (size_t i = 0; i < kSwitchableWindowContainerIdsLength; ++i) {
465 if (new_window->parent()->id() == kSwitchableWindowContainerIds[i] &&
466 !::wm::GetTransientParent(new_window)) {
467 // The new window is in one of the switchable containers, abort overview.
468 CancelSelection();
469 return;
474 void WindowSelector::OnWindowDestroying(aura::Window* window) {
475 window->RemoveObserver(this);
476 observed_windows_.erase(window);
477 if (window == restore_focus_window_)
478 restore_focus_window_ = nullptr;
481 void WindowSelector::OnWindowActivated(aura::Window* gained_active,
482 aura::Window* lost_active) {
483 if (ignore_activations_ ||
484 !gained_active ||
485 gained_active == text_filter_widget_->GetNativeWindow()) {
486 return;
489 ScopedVector<WindowGrid>::iterator grid =
490 std::find_if(grid_list_.begin(), grid_list_.end(),
491 RootWindowGridComparator(gained_active->GetRootWindow()));
492 if (grid == grid_list_.end())
493 return;
494 const std::vector<WindowSelectorItem*> windows = (*grid)->window_list();
496 ScopedVector<WindowSelectorItem>::const_iterator iter = std::find_if(
497 windows.begin(), windows.end(),
498 WindowSelectorItemTargetComparator(gained_active));
500 if (iter != windows.end())
501 (*iter)->ShowWindowOnExit();
503 // Don't restore focus on exit if a window was just activated.
504 ResetFocusRestoreWindow(false);
505 CancelSelection();
508 void WindowSelector::OnAttemptToReactivateWindow(aura::Window* request_active,
509 aura::Window* actual_active) {
510 OnWindowActivated(request_active, actual_active);
513 void WindowSelector::ContentsChanged(views::Textfield* sender,
514 const base::string16& new_contents) {
515 text_filter_string_length_ = new_contents.length();
516 if (!text_filter_string_length_)
517 num_times_textfield_cleared_++;
519 bool should_show_selection_widget = !new_contents.empty();
520 if (showing_selection_widget_ != should_show_selection_widget) {
521 ui::ScopedLayerAnimationSettings animation_settings(
522 text_filter_widget_->GetNativeWindow()->layer()->GetAnimator());
523 animation_settings.SetPreemptionStrategy(
524 ui::LayerAnimator::IMMEDIATELY_ANIMATE_TO_NEW_TARGET);
525 animation_settings.SetTweenType(showing_selection_widget_ ?
526 gfx::Tween::FAST_OUT_LINEAR_IN : gfx::Tween::LINEAR_OUT_SLOW_IN);
528 gfx::Transform transform;
529 if (should_show_selection_widget) {
530 transform.Translate(0, 0);
531 text_filter_widget_->GetNativeWindow()->layer()->SetOpacity(1);
532 } else {
533 transform.Translate(0, -kTextFilterBottomEdge);
534 text_filter_widget_->GetNativeWindow()->layer()->SetOpacity(0);
537 text_filter_widget_->GetNativeWindow()->SetTransform(transform);
538 showing_selection_widget_ = should_show_selection_widget;
540 for (ScopedVector<WindowGrid>::iterator iter = grid_list_.begin();
541 iter != grid_list_.end(); iter++) {
542 (*iter)->FilterItems(new_contents);
545 // If the selection widget is not active, execute a Move() command so that it
546 // shows up on the first undimmed item.
547 if (grid_list_[selected_grid_index_]->is_selecting())
548 return;
549 Move(WindowSelector::RIGHT, false);
552 void WindowSelector::PositionWindows(bool animate) {
553 for (ScopedVector<WindowGrid>::iterator iter = grid_list_.begin();
554 iter != grid_list_.end(); iter++) {
555 (*iter)->PositionWindows(animate);
559 void WindowSelector::HideAndTrackNonOverviewWindows() {
560 // Add the windows to hidden_windows first so that if any are destroyed
561 // while hiding them they are tracked.
562 for (ScopedVector<WindowGrid>::iterator grid_iter = grid_list_.begin();
563 grid_iter != grid_list_.end(); ++grid_iter) {
564 for (size_t i = 0; i < kSwitchableWindowContainerIdsLength; ++i) {
565 const aura::Window* container =
566 Shell::GetContainer((*grid_iter)->root_window(),
567 kSwitchableWindowContainerIds[i]);
568 for (aura::Window::Windows::const_iterator iter =
569 container->children().begin(); iter != container->children().end();
570 ++iter) {
571 if (!(*iter)->IsVisible() || (*grid_iter)->Contains(*iter))
572 continue;
573 hidden_windows_.Add(*iter);
578 // Copy the window list as it can change during iteration.
579 const aura::WindowTracker::Windows hidden_windows(hidden_windows_.windows());
580 for (aura::WindowTracker::Windows::const_iterator iter =
581 hidden_windows.begin(); iter != hidden_windows.end(); ++iter) {
582 if (!hidden_windows_.Contains(*iter))
583 continue;
584 ScopedOverviewAnimationSettings animation_settings(
585 OverviewAnimationType::OVERVIEW_ANIMATION_HIDE_WINDOW,
586 *iter);
587 (*iter)->Hide();
588 // Hiding the window can result in it being destroyed.
589 if (!hidden_windows_.Contains(*iter))
590 continue;
591 (*iter)->layer()->SetOpacity(0);
595 void WindowSelector::ResetFocusRestoreWindow(bool focus) {
596 if (!restore_focus_window_)
597 return;
598 if (focus) {
599 base::AutoReset<bool> restoring_focus(&ignore_activations_, true);
600 restore_focus_window_->Focus();
602 // If the window is in the observed_windows_ list it needs to continue to be
603 // observed.
604 if (observed_windows_.find(restore_focus_window_) ==
605 observed_windows_.end()) {
606 restore_focus_window_->RemoveObserver(this);
608 restore_focus_window_ = nullptr;
611 void WindowSelector::Move(Direction direction, bool animate) {
612 // Keep calling Move() on the grids until one of them reports no overflow or
613 // we made a full cycle on all the grids.
614 for (size_t i = 0;
615 i <= grid_list_.size() &&
616 grid_list_[selected_grid_index_]->Move(direction, animate); i++) {
617 // TODO(flackr): If there are more than two monitors, move between grids
618 // in the requested direction.
619 selected_grid_index_ = (selected_grid_index_ + 1) % grid_list_.size();
623 } // namespace ash