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