1 // Copyright (c) 2012 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/focus_cycler.h"
8 #include "ash/wm/mru_window_tracker.h"
9 #include "ash/wm/window_state.h"
10 #include "ash/wm/window_util.h"
11 #include "ui/aura/window.h"
12 #include "ui/views/accessible_pane_view.h"
13 #include "ui/views/focus/focus_search.h"
14 #include "ui/views/widget/widget.h"
15 #include "ui/wm/public/activation_client.h"
21 bool HasFocusableWindow() {
22 return !ash::Shell::GetInstance()->
23 mru_window_tracker()->BuildMruWindowList().empty();
28 FocusCycler::FocusCycler() : widget_activating_(NULL
) {
31 FocusCycler::~FocusCycler() {
34 void FocusCycler::AddWidget(views::Widget
* widget
) {
35 widgets_
.push_back(widget
);
38 void FocusCycler::RotateFocus(Direction direction
) {
39 aura::Window
* window
= ash::wm::GetActiveWindow();
41 views::Widget
* widget
= views::Widget::GetWidgetForNativeWindow(window
);
42 // First try to rotate focus within the active widget. If that succeeds,
44 if (widget
&& widget
->GetFocusManager()->RotatePaneFocus(
45 direction
== BACKWARD
?
46 views::FocusManager::kBackward
: views::FocusManager::kForward
,
47 views::FocusManager::kNoWrap
)) {
52 const bool has_window
= HasFocusableWindow();
54 int count
= static_cast<int>(widgets_
.size());
55 int browser_index
= has_window
? count
: -1;
57 for (; index
< count
; ++index
) {
58 if (widgets_
[index
]->IsActive())
62 int start_index
= index
;
68 if (direction
== FORWARD
)
69 index
= (index
+ 1) % count
;
71 index
= ((index
- 1) + count
) % count
;
73 // Ensure that we don't loop more than once.
74 if (index
== start_index
)
77 if (index
== browser_index
) {
78 // Activate the most recently active browser window.
79 MruWindowTracker::WindowList
mru_windows(
80 Shell::GetInstance()->mru_window_tracker()->BuildMruWindowList());
81 if (mru_windows
.empty())
83 aura::Window
* window
= mru_windows
.front();
84 wm::GetWindowState(window
)->Activate();
85 views::Widget
* widget
= views::Widget::GetWidgetForNativeWindow(window
);
88 views::FocusManager
* focus_manager
= widget
->GetFocusManager();
89 focus_manager
->ClearFocus();
90 focus_manager
->RotatePaneFocus(
91 direction
== BACKWARD
?
92 views::FocusManager::kBackward
: views::FocusManager::kForward
,
93 views::FocusManager::kWrap
);
96 if (FocusWidget(widgets_
[index
]))
102 bool FocusCycler::FocusWidget(views::Widget
* widget
) {
103 // Note: It is not necessary to set the focus directly to the pane since that
104 // will be taken care of by the widget activation.
105 widget_activating_
= widget
;
107 widget_activating_
= NULL
;
108 return widget
->IsActive();