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 "chrome/browser/ui/views/infobars/infobar_view.h"
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 "components/infobars/core/infobar_delegate.h"
13 #include "grit/generated_resources.h"
14 #include "grit/theme_resources.h"
15 #include "grit/ui_resources.h"
16 #include "third_party/skia/include/effects/SkGradientShader.h"
17 #include "ui/accessibility/ax_view_state.h"
18 #include "ui/base/l10n/l10n_util.h"
19 #include "ui/base/resource/resource_bundle.h"
20 #include "ui/gfx/canvas.h"
21 #include "ui/gfx/image/image.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"
35 // Helpers --------------------------------------------------------------------
39 const int kEdgeItemPadding = views::kRelatedControlHorizontalSpacing;
40 const int kIconToLabelSpacing = views::kRelatedControlHorizontalSpacing;
41 const int kBeforeCloseButtonSpacing = views::kUnrelatedControlHorizontalSpacing;
43 bool SortLabelsByDecreasingWidth(views::Label* label_1, views::Label* label_2) {
44 return label_1->GetPreferredSize().width() >
45 label_2->GetPreferredSize().width();
51 // InfoBar --------------------------------------------------------------------
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;
63 // InfoBarView ----------------------------------------------------------------
66 const int InfoBarView::kButtonButtonSpacing = views::kRelatedButtonHSpacing;
67 const int InfoBarView::kEndOfLabelSpacing = views::kItemLabelSpacing;
69 InfoBarView::InfoBarView(scoped_ptr<infobars::InfoBarDelegate> delegate)
70 : infobars::InfoBar(delegate.Pass()),
71 views::ExternalFocusTracker(this, NULL),
74 set_owned_by_client(); // InfoBar deletes itself at the appropriate time.
76 new InfoBarBackground(infobars::InfoBar::delegate()->GetInfoBarType()));
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());
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);
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());
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));
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);
141 void InfoBarView::AssignWidths(Labels* labels, int available_width) {
142 std::sort(labels->begin(), labels->end(), SortLabelsByDecreasingWidth);
143 AssignWidthsSorted(labels, available_width);
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();
152 const infobars::InfoBarContainer::Delegate* delegate = container_delegate();
154 static_cast<InfoBarBackground*>(background())->set_separator_color(
155 delegate->GetInfoBarSeparatorColor());
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.
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);
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);
187 fill_path_.addRect(0.0, SkIntToScalar(arrow_height()),
188 SkIntToScalar(width()), SkIntToScalar(height() - kSeparatorLineHeight));
191 int start_x = kEdgeItemPadding;
193 icon_->SetPosition(gfx::Point(start_x, OffsetY(icon_)));
194 start_x = icon_->bounds().right() + kIconToLabelSpacing;
197 int content_minimum_width = ContentMinimumWidth();
198 close_button_->SetPosition(gfx::Point(
200 start_x + content_minimum_width +
201 ((content_minimum_width > 0) ? kBeforeCloseButtonSpacing : 0),
202 width() - kEdgeItemPadding - close_button_->width()),
203 OffsetY(close_button_)));
206 void InfoBarView::ViewHierarchyChanged(
207 const ViewHierarchyChangedDetails& details) {
208 View::ViewHierarchyChanged(details);
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();
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_);
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);
247 SetBarTargetHeight(height);
250 void InfoBarView::PaintChildren(gfx::Canvas* canvas,
251 const views::CullSet& cull_set) {
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
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);
266 void InfoBarView::ButtonPressed(views::Button* sender,
267 const ui::Event& event) {
269 return; // We're closing; don't call anything, it might access the owner.
270 if (sender == close_button_) {
271 delegate()->InfoBarDismissed();
276 int InfoBarView::ContentMinimumWidth() const {
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
284 return std::min(EndX(), (icon_ != NULL) ?
285 (icon_->bounds().right() + kIconToLabelSpacing) : kEdgeItemPadding);
288 int InfoBarView::EndX() const {
289 return close_button_->x() - kBeforeCloseButtonSpacing;
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());
298 const infobars::InfoBarContainer::Delegate* InfoBarView::container_delegate()
300 const infobars::InfoBarContainer* infobar_container = container();
301 return infobar_container ? infobar_container->delegate() : NULL;
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);
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(),
315 gfx::Rect(screen_point, button->size()),
317 ui::MENU_SOURCE_NONE));
321 void InfoBarView::AssignWidthsSorted(Labels* labels, int available_width) {
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);
330 AssignWidthsSorted(labels, available_width - back_label_size.width());
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());
339 NotifyAccessibilityEvent(ui::AX_EVENT_ALERT, true);
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();
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);
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();
363 void InfoBarView::PlatformSpecificOnHeightsRecalculated() {
364 // Ensure that notifying our container of our size change will result in a
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");
378 gfx::Size InfoBarView::GetPreferredSize() const {
380 kEdgeItemPadding + (icon_ ? (icon_->width() + kIconToLabelSpacing) : 0) +
381 ContentMinimumWidth() + kBeforeCloseButtonSpacing +
382 close_button_->width() + kEdgeItemPadding,
386 void InfoBarView::OnWillChangeFocus(View* focused_before, View* focused_now) {
387 views::ExternalFocusTracker::OnWillChangeFocus(focused_before, focused_now);
389 // This will trigger some screen readers to read the entire contents of this
391 if (focused_before && focused_now && !Contains(focused_before) &&
392 Contains(focused_now)) {
393 NotifyAccessibilityEvent(ui::AX_EVENT_ALERT, true);