dropdown_bar_host.cc revision 5821806d5e7f356e8fa4b058a389a808ea183019
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.
4
5#include "chrome/browser/ui/views/dropdown_bar_host.h"
6
7#include <algorithm>
8
9#include "chrome/browser/ui/view_ids.h"
10#include "chrome/browser/ui/views/dropdown_bar_host_delegate.h"
11#include "chrome/browser/ui/views/dropdown_bar_view.h"
12#include "chrome/browser/ui/views/frame/browser_view.h"
13#include "ui/base/animation/slide_animation.h"
14#include "ui/base/keycodes/keyboard_codes.h"
15#include "ui/gfx/path.h"
16#include "ui/gfx/scrollbar_size.h"
17#include "ui/views/focus/external_focus_tracker.h"
18#include "ui/views/focus/view_storage.h"
19#include "ui/views/widget/widget.h"
20
21#if defined(USE_AURA)
22#include "ui/gfx/scoped_sk_region.h"
23#elif defined(OS_WIN)
24#include "base/win/scoped_gdi_object.h"
25#endif
26
27namespace {
28
29#if defined(USE_AURA)
30typedef gfx::ScopedSkRegion ScopedPlatformRegion;
31#elif defined(OS_WIN)
32typedef base::win::ScopedRegion ScopedPlatformRegion;
33#endif
34
35}  // namespace
36
37using gfx::Path;
38
39// static
40bool DropdownBarHost::disable_animations_during_testing_ = false;
41
42////////////////////////////////////////////////////////////////////////////////
43// DropdownBarHost, public:
44
45DropdownBarHost::DropdownBarHost(BrowserView* browser_view)
46    : browser_view_(browser_view),
47      view_(NULL),
48      delegate_(NULL),
49      animation_offset_(0),
50      focus_manager_(NULL),
51      esc_accel_target_registered_(false),
52      is_visible_(false) {
53}
54
55void DropdownBarHost::Init(views::View* view,
56                           DropdownBarHostDelegate* delegate) {
57  DCHECK(view);
58  DCHECK(delegate);
59
60  view_ = view;
61  delegate_ = delegate;
62
63  // Initialize the host.
64  host_.reset(new views::Widget);
65  views::Widget::InitParams params(views::Widget::InitParams::TYPE_CONTROL);
66  params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
67  params.parent_widget = browser_view_->GetWidget();
68#if defined(USE_AURA)
69  params.transparent = true;
70#endif
71  host_->Init(params);
72  host_->SetContentsView(view_);
73
74  // Start listening to focus changes, so we can register and unregister our
75  // own handler for Escape.
76  focus_manager_ = host_->GetFocusManager();
77  if (focus_manager_) {
78    focus_manager_->AddFocusChangeListener(this);
79  } else {
80    // In some cases (see bug http://crbug.com/17056) it seems we may not have
81    // a focus manager.  Please reopen the bug if you hit this.
82    NOTREACHED();
83  }
84
85  // Start the process of animating the opening of the widget.
86  animation_.reset(new ui::SlideAnimation(this));
87}
88
89DropdownBarHost::~DropdownBarHost() {
90  focus_manager_->RemoveFocusChangeListener(this);
91  focus_tracker_.reset(NULL);
92}
93
94void DropdownBarHost::Show(bool animate) {
95  // Stores the currently focused view, and tracks focus changes so that we can
96  // restore focus when the dropdown widget is closed.
97  focus_tracker_.reset(new views::ExternalFocusTracker(view_, focus_manager_));
98
99  if (!animate || disable_animations_during_testing_) {
100    is_visible_ = true;
101    animation_->Reset(1);
102    AnimationProgressed(animation_.get());
103  } else {
104    if (!is_visible_) {
105      // Don't re-start the animation.
106      is_visible_ = true;
107      animation_->Reset();
108      animation_->Show();
109    }
110  }
111}
112
113void DropdownBarHost::SetFocusAndSelection() {
114  delegate_->SetFocusAndSelection(true);
115}
116
117bool DropdownBarHost::IsAnimating() const {
118  return animation_->is_animating();
119}
120
121void DropdownBarHost::Hide(bool animate) {
122  if (!IsVisible())
123    return;
124  if (animate && !disable_animations_during_testing_ &&
125      !animation_->IsClosing()) {
126    animation_->Hide();
127  } else {
128    if (animation_->IsClosing()) {
129      // If we're in the middle of a close animation, skip immediately to the
130      // end of the animation.
131      StopAnimation();
132    } else {
133      // Otherwise we need to set both the animation state to ended and the
134      // DropdownBarHost state to ended/hidden, otherwise the next time we try
135      // to show the bar, it might refuse to do so. Note that we call
136      // AnimationEnded ourselves as Reset does not call it if we are not
137      // animating here.
138      animation_->Reset();
139      AnimationEnded(animation_.get());
140    }
141  }
142}
143
144void DropdownBarHost::StopAnimation() {
145  animation_->End();
146}
147
148bool DropdownBarHost::IsVisible() const {
149  return is_visible_;
150}
151
152////////////////////////////////////////////////////////////////////////////////
153// DropdownBarHost, views::FocusChangeListener implementation:
154void DropdownBarHost::OnWillChangeFocus(views::View* focused_before,
155                                        views::View* focused_now) {
156  // First we need to determine if one or both of the views passed in are child
157  // views of our view.
158  bool our_view_before = focused_before && view_->Contains(focused_before);
159  bool our_view_now = focused_now && view_->Contains(focused_now);
160
161  // When both our_view_before and our_view_now are false, it means focus is
162  // changing hands elsewhere in the application (and we shouldn't do anything).
163  // Similarly, when both are true, focus is changing hands within the dropdown
164  // widget (and again, we should not do anything). We therefore only need to
165  // look at when we gain initial focus and when we loose it.
166  if (!our_view_before && our_view_now) {
167    // We are gaining focus from outside the dropdown widget so we must register
168    // a handler for Escape.
169    RegisterAccelerators();
170  } else if (our_view_before && !our_view_now) {
171    // We are losing focus to something outside our widget so we restore the
172    // original handler for Escape.
173    UnregisterAccelerators();
174  }
175}
176
177void DropdownBarHost::OnDidChangeFocus(views::View* focused_before,
178                                       views::View* focused_now) {
179}
180
181////////////////////////////////////////////////////////////////////////////////
182// DropdownBarHost, ui::AnimationDelegate implementation:
183
184void DropdownBarHost::AnimationProgressed(const ui::Animation* animation) {
185  // First, we calculate how many pixels to slide the widget.
186  gfx::Size pref_size = view_->GetPreferredSize();
187  animation_offset_ = static_cast<int>((1.0 - animation_->GetCurrentValue()) *
188                                       pref_size.height());
189
190  // This call makes sure it appears in the right location, the size and shape
191  // is correct and that it slides in the right direction.
192  gfx::Rect dlg_rect = GetDialogPosition(gfx::Rect());
193  SetDialogPosition(dlg_rect, false);
194
195  // Let the view know if we are animating, and at which offset to draw the
196  // edges.
197  delegate_->SetAnimationOffset(animation_offset_);
198  view_->SchedulePaint();
199}
200
201void DropdownBarHost::AnimationEnded(const ui::Animation* animation) {
202  // Place the dropdown widget in its fully opened state.
203  animation_offset_ = 0;
204
205  if (!animation_->IsShowing()) {
206    // Animation has finished closing.
207    host_->Hide();
208    is_visible_ = false;
209  } else {
210    // Animation has finished opening.
211  }
212}
213
214////////////////////////////////////////////////////////////////////////////////
215// DropdownBarHost protected:
216
217void DropdownBarHost::ResetFocusTracker() {
218  focus_tracker_.reset(NULL);
219}
220
221void DropdownBarHost::GetWidgetBounds(gfx::Rect* bounds) {
222  DCHECK(bounds);
223  *bounds = browser_view_->bounds();
224}
225
226void DropdownBarHost::UpdateWindowEdges(const gfx::Rect& new_pos) {
227  // |w| is used to make it easier to create the part of the polygon that curves
228  // the right side of the Find window. It essentially keeps track of the
229  // x-pixel position of the right-most background image inside the view.
230  // TODO(finnur): Let the view tell us how to draw the curves or convert
231  // this to a CustomFrameWindow.
232  int w = new_pos.width() - 6;  // -6 positions us at the left edge of the
233                                // rightmost background image of the view.
234  int h = new_pos.height();
235
236  // This polygon array represents the outline of the background image for the
237  // window. Basically, it encompasses only the visible pixels of the
238  // concatenated find_dlg_LMR_bg images (where LMR = [left | middle | right]).
239  const Path::Point polygon[] = {
240      {2, 0}, {3, 1}, {3, h - 2}, {4, h - 1},
241        {4, h}, {w+0, h},
242      {w+2, h - 1}, {w+3, h - 2}, {w+3, 1}, {w+4, 0}
243  };
244
245  // Find the largest x and y value in the polygon.
246  int max_x = 0, max_y = 0;
247  for (size_t i = 0; i < arraysize(polygon); i++) {
248    max_x = std::max(max_x, static_cast<int>(polygon[i].x));
249    max_y = std::max(max_y, static_cast<int>(polygon[i].y));
250  }
251
252  // We then create the polygon and use SetWindowRgn to force the window to draw
253  // only within that area. This region may get reduced in size below.
254  Path path(polygon, arraysize(polygon));
255  ScopedPlatformRegion region(path.CreateNativeRegion());
256  // Are we animating?
257  if (animation_offset() > 0) {
258    // The animation happens in two steps: First, we clip the window and then in
259    // GetWidgetPosition we offset the window position so that it still looks
260    // attached to the toolbar as it grows. We clip the window by creating a
261    // rectangle region (that gradually increases as the animation progresses)
262    // and find the intersection between the two regions using CombineRgn.
263
264    // |y| shrinks as the animation progresses from the height of the view down
265    // to 0 (and reverses when closing).
266    int y = animation_offset();
267    // |y| shrinking means the animation (visible) region gets larger. In other
268    // words: the rectangle grows upward (when the widget is opening).
269    Path animation_path;
270    SkRect animation_rect = { SkIntToScalar(0), SkIntToScalar(y),
271                              SkIntToScalar(max_x), SkIntToScalar(max_y) };
272    animation_path.addRect(animation_rect);
273    ScopedPlatformRegion animation_region(
274        animation_path.CreateNativeRegion());
275    region.Set(Path::IntersectRegions(animation_region.Get(), region.Get()));
276
277    // Next, we need to increase the region a little bit to account for the
278    // curved edges that the view will draw to make it look like grows out of
279    // the toolbar.
280    Path::Point left_curve[] = {
281      {2, y+0}, {3, y+1}, {3, y+0}, {2, y+0}
282    };
283    Path::Point right_curve[] = {
284      {w+3, y+1}, {w+4, y+0}, {w+3, y+0}, {w+3, y+1}
285    };
286
287    // Combine the region for the curve on the left with our main region.
288    Path left_path(left_curve, arraysize(left_curve));
289    ScopedPlatformRegion r(left_path.CreateNativeRegion());
290    region.Set(Path::CombineRegions(r.Get(), region.Get()));
291
292    // Combine the region for the curve on the right with our main region.
293    Path right_path(right_curve, arraysize(right_curve));
294    region.Set(Path::CombineRegions(r.Get(), region.Get()));
295  }
296
297  // Now see if we need to truncate the region because parts of it obscures
298  // the main window border.
299  gfx::Rect widget_bounds;
300  GetWidgetBounds(&widget_bounds);
301
302  // Calculate how much our current position overlaps our boundaries. If we
303  // overlap, it means we have too little space to draw the whole widget and
304  // we allow overwriting the scrollbar before we start truncating our widget.
305  //
306  // TODO(brettw) this constant is evil. This is the amount of room we've added
307  // to the window size, when we set the region, it can change the size.
308  static const int kAddedWidth = 7;
309  int difference = new_pos.right() - kAddedWidth - widget_bounds.right() -
310      gfx::scrollbar_size() + 1;
311  if (difference > 0) {
312    Path::Point exclude[4];
313    exclude[0].x = max_x - difference;  // Top left corner.
314    exclude[0].y = 0;
315
316    exclude[1].x = max_x;               // Top right corner.
317    exclude[1].y = 0;
318
319    exclude[2].x = max_x;               // Bottom right corner.
320    exclude[2].y = max_y;
321
322    exclude[3].x = max_x - difference;  // Bottom left corner.
323    exclude[3].y = max_y;
324
325    // Subtract this region from the original region.
326    gfx::Path exclude_path(exclude, arraysize(exclude));
327    ScopedPlatformRegion exclude_region(exclude_path.CreateNativeRegion());
328    region.Set(Path::SubtractRegion(region.Get(), exclude_region.Get()));
329  }
330
331  // Window takes ownership of the region.
332  host()->SetShape(region.release());
333}
334
335void DropdownBarHost::RegisterAccelerators() {
336  DCHECK(!esc_accel_target_registered_);
337  ui::Accelerator escape(ui::VKEY_ESCAPE, ui::EF_NONE);
338  focus_manager_->RegisterAccelerator(
339      escape, ui::AcceleratorManager::kNormalPriority, this);
340  esc_accel_target_registered_ = true;
341}
342
343void DropdownBarHost::UnregisterAccelerators() {
344  DCHECK(esc_accel_target_registered_);
345  ui::Accelerator escape(ui::VKEY_ESCAPE, ui::EF_NONE);
346  focus_manager_->UnregisterAccelerator(escape, this);
347  esc_accel_target_registered_ = false;
348}
349