Home | History | Annotate | Download | only in infobars
      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/infobars/infobar_view.h"
      6 
      7 #include <algorithm>
      8 
      9 #include "base/memory/scoped_ptr.h"
     10 #include "base/strings/utf_string_conversions.h"
     11 #include "chrome/browser/ui/views/infobars/infobar_background.h"
     12 #include "chrome/grit/generated_resources.h"
     13 #include "components/infobars/core/infobar_delegate.h"
     14 #include "grit/theme_resources.h"
     15 #include "third_party/skia/include/effects/SkGradientShader.h"
     16 #include "ui/accessibility/ax_view_state.h"
     17 #include "ui/base/l10n/l10n_util.h"
     18 #include "ui/base/resource/resource_bundle.h"
     19 #include "ui/gfx/canvas.h"
     20 #include "ui/gfx/image/image.h"
     21 #include "ui/resources/grit/ui_resources.h"
     22 #include "ui/views/controls/button/image_button.h"
     23 #include "ui/views/controls/button/label_button.h"
     24 #include "ui/views/controls/button/label_button_border.h"
     25 #include "ui/views/controls/button/menu_button.h"
     26 #include "ui/views/controls/image_view.h"
     27 #include "ui/views/controls/label.h"
     28 #include "ui/views/controls/link.h"
     29 #include "ui/views/controls/menu/menu_runner.h"
     30 #include "ui/views/layout/layout_constants.h"
     31 #include "ui/views/widget/widget.h"
     32 #include "ui/views/window/non_client_view.h"
     33 
     34 
     35 // Helpers --------------------------------------------------------------------
     36 
     37 namespace {
     38 
     39 const int kEdgeItemPadding = views::kRelatedControlHorizontalSpacing;
     40 const int kIconToLabelSpacing = views::kRelatedControlHorizontalSpacing;
     41 const int kBeforeCloseButtonSpacing = views::kUnrelatedControlHorizontalSpacing;
     42 
     43 bool SortLabelsByDecreasingWidth(views::Label* label_1, views::Label* label_2) {
     44   return label_1->GetPreferredSize().width() >
     45       label_2->GetPreferredSize().width();
     46 }
     47 
     48 }  // namespace
     49 
     50 
     51 // InfoBar --------------------------------------------------------------------
     52 
     53 // static
     54 const int infobars::InfoBar::kSeparatorLineHeight =
     55     views::NonClientFrameView::kClientEdgeThickness;
     56 const int infobars::InfoBar::kDefaultArrowTargetHeight = 9;
     57 const int infobars::InfoBar::kMaximumArrowTargetHeight = 24;
     58 const int infobars::InfoBar::kDefaultArrowTargetHalfWidth =
     59     kDefaultArrowTargetHeight;
     60 const int infobars::InfoBar::kMaximumArrowTargetHalfWidth = 14;
     61 const int infobars::InfoBar::kDefaultBarTargetHeight = 36;
     62 
     63 // InfoBarView ----------------------------------------------------------------
     64 
     65 // static
     66 const int InfoBarView::kButtonButtonSpacing = views::kRelatedButtonHSpacing;
     67 const int InfoBarView::kEndOfLabelSpacing = views::kItemLabelSpacing;
     68 
     69 InfoBarView::InfoBarView(scoped_ptr<infobars::InfoBarDelegate> delegate)
     70     : infobars::InfoBar(delegate.Pass()),
     71       views::ExternalFocusTracker(this, NULL),
     72       icon_(NULL),
     73       close_button_(NULL) {
     74   set_owned_by_client();  // InfoBar deletes itself at the appropriate time.
     75   set_background(
     76       new InfoBarBackground(infobars::InfoBar::delegate()->GetInfoBarType()));
     77 }
     78 
     79 InfoBarView::~InfoBarView() {
     80   // We should have closed any open menus in PlatformSpecificHide(), then
     81   // subclasses' RunMenu() functions should have prevented opening any new ones
     82   // once we became unowned.
     83   DCHECK(!menu_runner_.get());
     84 }
     85 
     86 views::Label* InfoBarView::CreateLabel(const base::string16& text) const {
     87   ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();
     88   views::Label* label = new views::Label(
     89       text, rb.GetFontList(ui::ResourceBundle::MediumFont));
     90   label->SizeToPreferredSize();
     91   label->SetBackgroundColor(background()->get_color());
     92   label->SetEnabledColor(SK_ColorBLACK);
     93   label->SetHorizontalAlignment(gfx::ALIGN_LEFT);
     94   return label;
     95 }
     96 
     97 views::Link* InfoBarView::CreateLink(const base::string16& text,
     98                                      views::LinkListener* listener) const {
     99   ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();
    100   views::Link* link = new views::Link(text);
    101   link->SetFontList(rb.GetFontList(ui::ResourceBundle::MediumFont));
    102   link->SizeToPreferredSize();
    103   link->SetHorizontalAlignment(gfx::ALIGN_LEFT);
    104   link->set_listener(listener);
    105   link->SetBackgroundColor(background()->get_color());
    106   return link;
    107 }
    108 
    109 // static
    110 views::LabelButton* InfoBarView::CreateLabelButton(
    111     views::ButtonListener* listener,
    112     const base::string16& text) {
    113   scoped_ptr<views::LabelButtonBorder> label_button_border(
    114       new views::LabelButtonBorder(views::Button::STYLE_TEXTBUTTON));
    115   const int kNormalImageSet[] = IMAGE_GRID(IDR_INFOBARBUTTON_NORMAL);
    116   label_button_border->SetPainter(
    117       false, views::Button::STATE_NORMAL,
    118       views::Painter::CreateImageGridPainter(kNormalImageSet));
    119   const int kHoveredImageSet[] = IMAGE_GRID(IDR_INFOBARBUTTON_HOVER);
    120   label_button_border->SetPainter(
    121       false, views::Button::STATE_HOVERED,
    122       views::Painter::CreateImageGridPainter(kHoveredImageSet));
    123   const int kPressedImageSet[] = IMAGE_GRID(IDR_INFOBARBUTTON_PRESSED);
    124   label_button_border->SetPainter(
    125       false, views::Button::STATE_PRESSED,
    126       views::Painter::CreateImageGridPainter(kPressedImageSet));
    127 
    128   views::LabelButton* label_button = new views::LabelButton(listener, text);
    129   label_button->SetBorder(label_button_border.PassAs<views::Border>());
    130   label_button->set_animate_on_state_change(false);
    131   label_button->SetTextColor(views::Button::STATE_NORMAL, SK_ColorBLACK);
    132   label_button->SetTextColor(views::Button::STATE_HOVERED, SK_ColorBLACK);
    133   ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();
    134   label_button->SetFontList(rb.GetFontList(ui::ResourceBundle::MediumFont));
    135   label_button->SizeToPreferredSize();
    136   label_button->SetFocusable(true);
    137   return label_button;
    138 }
    139 
    140 // static
    141 void InfoBarView::AssignWidths(Labels* labels, int available_width) {
    142   std::sort(labels->begin(), labels->end(), SortLabelsByDecreasingWidth);
    143   AssignWidthsSorted(labels, available_width);
    144 }
    145 
    146 void InfoBarView::Layout() {
    147   // Calculate the fill and stroke paths.  We do this here, rather than in
    148   // PlatformSpecificRecalculateHeight(), because this is also reached when our
    149   // width is changed, which affects both paths.
    150   stroke_path_.rewind();
    151   fill_path_.rewind();
    152   const infobars::InfoBarContainer::Delegate* delegate = container_delegate();
    153   if (delegate) {
    154     static_cast<InfoBarBackground*>(background())->set_separator_color(
    155         delegate->GetInfoBarSeparatorColor());
    156     int arrow_x;
    157     SkScalar arrow_fill_height =
    158         SkIntToScalar(std::max(arrow_height() - kSeparatorLineHeight, 0));
    159     SkScalar arrow_fill_half_width = SkIntToScalar(arrow_half_width());
    160     SkScalar separator_height = SkIntToScalar(kSeparatorLineHeight);
    161     if (delegate->DrawInfoBarArrows(&arrow_x) && arrow_fill_height) {
    162       // Skia pixel centers are at the half-values, so the arrow is horizontally
    163       // centered at |arrow_x| + 0.5.  Vertically, the stroke path is the center
    164       // of the separator, while the fill path is a closed path that extends up
    165       // through the entire height of the separator and down to the bottom of
    166       // the arrow where it joins the bar.
    167       stroke_path_.moveTo(
    168           SkIntToScalar(arrow_x) + SK_ScalarHalf - arrow_fill_half_width,
    169           SkIntToScalar(arrow_height()) - (separator_height * SK_ScalarHalf));
    170       stroke_path_.rLineTo(arrow_fill_half_width, -arrow_fill_height);
    171       stroke_path_.rLineTo(arrow_fill_half_width, arrow_fill_height);
    172 
    173       fill_path_ = stroke_path_;
    174       // Move the top of the fill path up to the top of the separator and then
    175       // extend it down all the way through.
    176       fill_path_.offset(0, -separator_height * SK_ScalarHalf);
    177       // This 0.01 hack prevents the fill from filling more pixels on the right
    178       // edge of the arrow than on the left.
    179       const SkScalar epsilon = 0.01f;
    180       fill_path_.rLineTo(-epsilon, 0);
    181       fill_path_.rLineTo(0, separator_height);
    182       fill_path_.rLineTo(epsilon - (arrow_fill_half_width * 2), 0);
    183       fill_path_.close();
    184     }
    185   }
    186   if (bar_height()) {
    187     fill_path_.addRect(0.0, SkIntToScalar(arrow_height()),
    188         SkIntToScalar(width()), SkIntToScalar(height() - kSeparatorLineHeight));
    189   }
    190 
    191   int start_x = kEdgeItemPadding;
    192   if (icon_ != NULL) {
    193     icon_->SetPosition(gfx::Point(start_x, OffsetY(icon_)));
    194     start_x = icon_->bounds().right() + kIconToLabelSpacing;
    195   }
    196 
    197   int content_minimum_width = ContentMinimumWidth();
    198   close_button_->SetPosition(gfx::Point(
    199       std::max(
    200           start_x + content_minimum_width +
    201               ((content_minimum_width > 0) ? kBeforeCloseButtonSpacing : 0),
    202           width() - kEdgeItemPadding - close_button_->width()),
    203       OffsetY(close_button_)));
    204 }
    205 
    206 void InfoBarView::ViewHierarchyChanged(
    207     const ViewHierarchyChangedDetails& details) {
    208   View::ViewHierarchyChanged(details);
    209 
    210   if (details.is_add && (details.child == this) && (close_button_ == NULL)) {
    211     gfx::Image image = delegate()->GetIcon();
    212     if (!image.IsEmpty()) {
    213       icon_ = new views::ImageView;
    214       icon_->SetImage(image.ToImageSkia());
    215       icon_->SizeToPreferredSize();
    216       AddChildView(icon_);
    217     }
    218 
    219     close_button_ = new views::ImageButton(this);
    220     ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();
    221     close_button_->SetImage(views::CustomButton::STATE_NORMAL,
    222                             rb.GetImageNamed(IDR_CLOSE_1).ToImageSkia());
    223     close_button_->SetImage(views::CustomButton::STATE_HOVERED,
    224                             rb.GetImageNamed(IDR_CLOSE_1_H).ToImageSkia());
    225     close_button_->SetImage(views::CustomButton::STATE_PRESSED,
    226                             rb.GetImageNamed(IDR_CLOSE_1_P).ToImageSkia());
    227     close_button_->SizeToPreferredSize();
    228     close_button_->SetAccessibleName(
    229         l10n_util::GetStringUTF16(IDS_ACCNAME_CLOSE));
    230     close_button_->SetFocusable(true);
    231     AddChildView(close_button_);
    232   } else if ((close_button_ != NULL) && (details.parent == this) &&
    233       (details.child != close_button_) && (close_button_->parent() == this) &&
    234       (child_at(child_count() - 1) != close_button_)) {
    235     // For accessibility, ensure the close button is the last child view.
    236     RemoveChildView(close_button_);
    237     AddChildView(close_button_);
    238   }
    239 
    240   // Ensure the infobar is tall enough to display its contents.
    241   const int kMinimumVerticalPadding = 6;
    242   int height = kDefaultBarTargetHeight;
    243   for (int i = 0; i < child_count(); ++i) {
    244     const int child_height = child_at(i)->height();
    245     height = std::max(height, child_height + kMinimumVerticalPadding);
    246   }
    247   SetBarTargetHeight(height);
    248 }
    249 
    250 void InfoBarView::PaintChildren(gfx::Canvas* canvas,
    251                                 const views::CullSet& cull_set) {
    252   canvas->Save();
    253 
    254   // TODO(scr): This really should be the |fill_path_|, but the clipPath seems
    255   // broken on non-Windows platforms (crbug.com/75154). For now, just clip to
    256   // the bar bounds.
    257   //
    258   // canvas->sk_canvas()->clipPath(fill_path_);
    259   DCHECK_EQ(total_height(), height())
    260       << "Infobar piecewise heights do not match overall height";
    261   canvas->ClipRect(gfx::Rect(0, arrow_height(), width(), bar_height()));
    262   views::View::PaintChildren(canvas, cull_set);
    263   canvas->Restore();
    264 }
    265 
    266 void InfoBarView::ButtonPressed(views::Button* sender,
    267                                 const ui::Event& event) {
    268   if (!owner())
    269     return;  // We're closing; don't call anything, it might access the owner.
    270   if (sender == close_button_) {
    271     delegate()->InfoBarDismissed();
    272     RemoveSelf();
    273   }
    274 }
    275 
    276 int InfoBarView::ContentMinimumWidth() const {
    277   return 0;
    278 }
    279 
    280 int InfoBarView::StartX() const {
    281   // Ensure we don't return a value greater than EndX(), so children can safely
    282   // set something's width to "EndX() - StartX()" without risking that being
    283   // negative.
    284   return std::min(EndX(), (icon_ != NULL) ?
    285       (icon_->bounds().right() + kIconToLabelSpacing) : kEdgeItemPadding);
    286 }
    287 
    288 int InfoBarView::EndX() const {
    289   return close_button_->x() - kBeforeCloseButtonSpacing;
    290 }
    291 
    292 int InfoBarView::OffsetY(views::View* view) const {
    293   return arrow_height() +
    294       std::max((bar_target_height() - view->height()) / 2, 0) -
    295       (bar_target_height() - bar_height());
    296 }
    297 
    298 const infobars::InfoBarContainer::Delegate* InfoBarView::container_delegate()
    299     const {
    300   const infobars::InfoBarContainer* infobar_container = container();
    301   return infobar_container ? infobar_container->delegate() : NULL;
    302 }
    303 
    304 void InfoBarView::RunMenuAt(ui::MenuModel* menu_model,
    305                             views::MenuButton* button,
    306                             views::MenuAnchorPosition anchor) {
    307   DCHECK(owner());  // We'd better not open any menus while we're closing.
    308   gfx::Point screen_point;
    309   views::View::ConvertPointToScreen(button, &screen_point);
    310   menu_runner_.reset(
    311       new views::MenuRunner(menu_model, views::MenuRunner::HAS_MNEMONICS));
    312   // Ignore the result since we don't need to handle a deleted menu specially.
    313   ignore_result(menu_runner_->RunMenuAt(GetWidget(),
    314                                         button,
    315                                         gfx::Rect(screen_point, button->size()),
    316                                         anchor,
    317                                         ui::MENU_SOURCE_NONE));
    318 }
    319 
    320 // static
    321 void InfoBarView::AssignWidthsSorted(Labels* labels, int available_width) {
    322   if (labels->empty())
    323     return;
    324   gfx::Size back_label_size(labels->back()->GetPreferredSize());
    325   back_label_size.set_width(
    326       std::min(back_label_size.width(),
    327                available_width / static_cast<int>(labels->size())));
    328   labels->back()->SetSize(back_label_size);
    329   labels->pop_back();
    330   AssignWidthsSorted(labels, available_width - back_label_size.width());
    331 }
    332 
    333 void InfoBarView::PlatformSpecificShow(bool animate) {
    334   // If we gain focus, we want to restore it to the previously-focused element
    335   // when we're hidden. So when we're in a Widget, create a focus tracker so
    336   // that if we gain focus we'll know what the previously-focused element was.
    337   SetFocusManager(GetFocusManager());
    338 
    339   NotifyAccessibilityEvent(ui::AX_EVENT_ALERT, true);
    340 }
    341 
    342 void InfoBarView::PlatformSpecificHide(bool animate) {
    343   // Cancel any menus we may have open.  It doesn't make sense to leave them
    344   // open while we're hidden, and if we're going to become unowned, we can't
    345   // allow the user to choose any options and potentially call functions that
    346   // try to access the owner.
    347   menu_runner_.reset();
    348 
    349   // It's possible to be called twice (once with |animate| true and once with it
    350   // false); in this case the second SetFocusManager() call will silently no-op.
    351   SetFocusManager(NULL);
    352 
    353   if (!animate)
    354     return;
    355 
    356   // Do not restore focus (and active state with it) if some other top-level
    357   // window became active.
    358   views::Widget* widget = GetWidget();
    359   if (!widget || widget->IsActive())
    360     FocusLastFocusedExternalView();
    361 }
    362 
    363 void InfoBarView::PlatformSpecificOnHeightsRecalculated() {
    364   // Ensure that notifying our container of our size change will result in a
    365   // re-layout.
    366   InvalidateLayout();
    367 }
    368 
    369 void InfoBarView::GetAccessibleState(ui::AXViewState* state) {
    370   state->name = l10n_util::GetStringUTF16(
    371       (delegate()->GetInfoBarType() ==
    372        infobars::InfoBarDelegate::WARNING_TYPE) ?
    373           IDS_ACCNAME_INFOBAR_WARNING : IDS_ACCNAME_INFOBAR_PAGE_ACTION);
    374   state->role = ui::AX_ROLE_ALERT;
    375   state->keyboard_shortcut = base::ASCIIToUTF16("Alt+Shift+A");
    376 }
    377 
    378 gfx::Size InfoBarView::GetPreferredSize() const {
    379   return gfx::Size(
    380       kEdgeItemPadding + (icon_ ? (icon_->width() + kIconToLabelSpacing) : 0) +
    381           ContentMinimumWidth() + kBeforeCloseButtonSpacing +
    382           close_button_->width() + kEdgeItemPadding,
    383       total_height());
    384 }
    385 
    386 void InfoBarView::OnWillChangeFocus(View* focused_before, View* focused_now) {
    387   views::ExternalFocusTracker::OnWillChangeFocus(focused_before, focused_now);
    388 
    389   // This will trigger some screen readers to read the entire contents of this
    390   // infobar.
    391   if (focused_before && focused_now && !Contains(focused_before) &&
    392       Contains(focused_now)) {
    393     NotifyAccessibilityEvent(ui::AX_EVENT_ALERT, true);
    394   }
    395 }
    396