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