origin_chip_view.cc revision effb81e5f8246d0db0270817048dc992db66e9fb
1// Copyright 2014 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/location_bar/origin_chip_view.h"
6
7#include "base/files/file_path.h"
8#include "base/metrics/histogram.h"
9#include "base/strings/string_util.h"
10#include "base/strings/utf_string_conversions.h"
11#include "chrome/browser/browser_process.h"
12#include "chrome/browser/extensions/extension_icon_image.h"
13#include "chrome/browser/extensions/extension_service.h"
14#include "chrome/browser/favicon/favicon_tab_helper.h"
15#include "chrome/browser/profiles/profile.h"
16#include "chrome/browser/safe_browsing/safe_browsing_service.h"
17#include "chrome/browser/safe_browsing/ui_manager.h"
18#include "chrome/browser/search/search.h"
19#include "chrome/browser/themes/theme_properties.h"
20#include "chrome/browser/ui/browser.h"
21#include "chrome/browser/ui/elide_url.h"
22#include "chrome/browser/ui/omnibox/omnibox_view.h"
23#include "chrome/browser/ui/toolbar/origin_chip_info.h"
24#include "chrome/browser/ui/toolbar/toolbar_model.h"
25#include "chrome/browser/ui/views/location_bar/location_bar_view.h"
26#include "chrome/common/extensions/extension_constants.h"
27#include "chrome/common/extensions/manifest_handlers/icons_handler.h"
28#include "content/public/browser/user_metrics.h"
29#include "content/public/browser/web_contents.h"
30#include "content/public/common/url_constants.h"
31#include "extensions/browser/extension_system.h"
32#include "extensions/common/constants.h"
33#include "grit/generated_resources.h"
34#include "grit/theme_resources.h"
35#include "ui/base/l10n/l10n_util.h"
36#include "ui/base/resource/resource_bundle.h"
37#include "ui/base/theme_provider.h"
38#include "ui/gfx/animation/slide_animation.h"
39#include "ui/gfx/canvas.h"
40#include "ui/gfx/font_list.h"
41#include "ui/views/background.h"
42#include "ui/views/controls/button/label_button.h"
43#include "ui/views/controls/button/label_button_border.h"
44#include "ui/views/painter.h"
45
46
47// OriginChipExtensionIcon ----------------------------------------------------
48
49class OriginChipExtensionIcon : public extensions::IconImage::Observer {
50 public:
51  OriginChipExtensionIcon(LocationIconView* icon_view,
52                          Profile* profile,
53                          const extensions::Extension* extension);
54  virtual ~OriginChipExtensionIcon();
55
56  // IconImage::Observer:
57  virtual void OnExtensionIconImageChanged(
58      extensions::IconImage* image) OVERRIDE;
59
60 private:
61  LocationIconView* icon_view_;
62  scoped_ptr<extensions::IconImage> icon_image_;
63
64  DISALLOW_COPY_AND_ASSIGN(OriginChipExtensionIcon);
65};
66
67OriginChipExtensionIcon::OriginChipExtensionIcon(
68    LocationIconView* icon_view,
69    Profile* profile,
70    const extensions::Extension* extension)
71    : icon_view_(icon_view),
72      icon_image_(new extensions::IconImage(
73          profile,
74          extension,
75          extensions::IconsInfo::GetIcons(extension),
76          extension_misc::EXTENSION_ICON_BITTY,
77          extensions::IconsInfo::GetDefaultAppIcon(),
78          this)) {
79  // Forces load of the image.
80  icon_image_->image_skia().GetRepresentation(1.0f);
81
82  if (!icon_image_->image_skia().image_reps().empty())
83    OnExtensionIconImageChanged(icon_image_.get());
84}
85
86OriginChipExtensionIcon::~OriginChipExtensionIcon() {
87}
88
89void OriginChipExtensionIcon::OnExtensionIconImageChanged(
90    extensions::IconImage* image) {
91  if (icon_view_)
92    icon_view_->SetImage(&icon_image_->image_skia());
93}
94
95
96// OriginChipView -------------------------------------------------------------
97
98namespace {
99
100const int kEdgeThickness = 5;
101const int k16x16IconLeadingSpacing = 1;
102const int k16x16IconTrailingSpacing = 2;
103const int kIconTextSpacing = 3;
104const int kTrailingLabelMargin = 0;
105
106const int kNormalImages[3][9] = {
107  IMAGE_GRID(IDR_ORIGIN_CHIP_NORMAL),
108  IMAGE_GRID(IDR_ORIGIN_CHIP_HOVER),
109  IMAGE_GRID(IDR_ORIGIN_CHIP_PRESSED)
110};
111
112const int kMalwareImages[3][9] = {
113  IMAGE_GRID(IDR_ORIGIN_CHIP_MALWARE_NORMAL),
114  IMAGE_GRID(IDR_ORIGIN_CHIP_MALWARE_HOVER),
115  IMAGE_GRID(IDR_ORIGIN_CHIP_MALWARE_PRESSED)
116};
117
118const int kBrokenSSLImages[3][9] = {
119  IMAGE_GRID(IDR_ORIGIN_CHIP_BROKENSSL_NORMAL),
120  IMAGE_GRID(IDR_ORIGIN_CHIP_BROKENSSL_HOVER),
121  IMAGE_GRID(IDR_ORIGIN_CHIP_BROKENSSL_PRESSED)
122};
123
124const int kEVImages[3][9] = {
125  IMAGE_GRID(IDR_ORIGIN_CHIP_EV_NORMAL),
126  IMAGE_GRID(IDR_ORIGIN_CHIP_EV_HOVER),
127  IMAGE_GRID(IDR_ORIGIN_CHIP_EV_PRESSED)
128};
129
130}  // namespace
131
132OriginChipView::OriginChipView(LocationBarView* location_bar_view,
133                               Profile* profile,
134                               const gfx::FontList& font_list)
135    : LabelButton(this, base::string16()),
136      location_bar_view_(location_bar_view),
137      profile_(profile),
138      showing_16x16_icon_(false) {
139  scoped_refptr<SafeBrowsingService> sb_service =
140      g_browser_process->safe_browsing_service();
141  // May not be set for unit tests.
142  if (sb_service && sb_service->ui_manager())
143    sb_service->ui_manager()->AddObserver(this);
144
145  SetFontList(font_list);
146
147  image()->EnableCanvasFlippingForRTLUI(false);
148
149  // TODO(gbillock): Would be nice to just use stock LabelButton stuff here.
150  location_icon_view_ = new LocationIconView(location_bar_view_);
151  // Make location icon hover events count as hovering the origin chip.
152  location_icon_view_->set_interactive(false);
153  location_icon_view_->ShowTooltip(true);
154  AddChildView(location_icon_view_);
155
156  host_label_ = new views::Label(base::string16(), GetFontList());
157  AddChildView(host_label_);
158
159  fade_in_animation_.reset(new gfx::SlideAnimation(this));
160  fade_in_animation_->SetTweenType(gfx::Tween::LINEAR);
161  fade_in_animation_->SetSlideDuration(300);
162}
163
164OriginChipView::~OriginChipView() {
165  scoped_refptr<SafeBrowsingService> sb_service =
166      g_browser_process->safe_browsing_service();
167  if (sb_service.get() && sb_service->ui_manager())
168    sb_service->ui_manager()->RemoveObserver(this);
169}
170
171bool OriginChipView::ShouldShow() {
172  return chrome::ShouldDisplayOriginChipV2() &&
173      location_bar_view_->GetToolbarModel()->WouldOmitURLDueToOriginChip() &&
174      location_bar_view_->GetToolbarModel()->origin_chip_enabled();
175}
176
177void OriginChipView::Update(content::WebContents* web_contents) {
178  if (!web_contents)
179    return;
180
181  // Note: security level can change async as the connection is made.
182  GURL url = location_bar_view_->GetToolbarModel()->GetURL();
183  const ToolbarModel::SecurityLevel security_level =
184      location_bar_view_->GetToolbarModel()->GetSecurityLevel(true);
185
186  bool url_malware = OriginChip::IsMalware(url, web_contents);
187
188  // TODO(gbillock): We persist a malware setting while a new WebContents
189  // content is loaded, meaning that we end up transiently marking a safe
190  // page as malware. Need to fix that.
191
192  if ((url == url_displayed_) &&
193      (security_level == security_level_) &&
194      (url_malware == url_malware_))
195    return;
196
197  url_displayed_ = url;
198  url_malware_ = url_malware;
199  security_level_ = security_level;
200
201  if (url_malware_) {
202    SetBorderImages(kMalwareImages);
203  } else if (security_level_ == ToolbarModel::SECURITY_ERROR) {
204    SetBorderImages(kBrokenSSLImages);
205  } else if (security_level_ == ToolbarModel::EV_SECURE) {
206    SetBorderImages(kEVImages);
207  } else {
208    SetBorderImages(kNormalImages);
209  }
210
211  base::string16 host =
212      OriginChip::LabelFromURLForProfile(url_displayed_, profile_);
213  if (security_level_ == ToolbarModel::EV_SECURE) {
214    host = l10n_util::GetStringFUTF16(IDS_SITE_CHIP_EV_SSL_LABEL,
215        location_bar_view_->GetToolbarModel()->GetEVCertName(),
216        host);
217  }
218  host_label_->SetText(host);
219  host_label_->SetTooltipText(host);
220  host_label_->SetElideBehavior(views::Label::NO_ELIDE);
221
222  int icon = location_bar_view_->GetToolbarModel()->GetIconForSecurityLevel(
223      security_level_);
224  showing_16x16_icon_ = false;
225
226  if (url_displayed_.is_empty() ||
227      url_displayed_.SchemeIs(content::kChromeUIScheme)) {
228    icon = IDR_PRODUCT_LOGO_16;
229    showing_16x16_icon_ = true;
230  }
231
232  location_icon_view_->SetImage(GetThemeProvider()->GetImageSkiaNamed(icon));
233
234  if (url_displayed_.SchemeIs(extensions::kExtensionScheme)) {
235    icon = IDR_EXTENSIONS_FAVICON;
236    showing_16x16_icon_ = true;
237    location_icon_view_->SetImage(GetThemeProvider()->GetImageSkiaNamed(icon));
238
239    ExtensionService* service =
240        extensions::ExtensionSystem::Get(profile_)->extension_service();
241    const extensions::Extension* extension =
242        service->extensions()->GetExtensionOrAppByURL(url_displayed_);
243    extension_icon_.reset(
244        new OriginChipExtensionIcon(location_icon_view_, profile_, extension));
245  } else {
246    extension_icon_.reset();
247  }
248
249  Layout();
250  SchedulePaint();
251}
252
253void OriginChipView::SetBorderImages(const int images[3][9]) {
254  scoped_ptr<views::LabelButtonBorder> border(
255      new views::LabelButtonBorder(views::Button::STYLE_BUTTON));
256
257  views::Painter* painter = views::Painter::CreateImageGridPainter(images[0]);
258  border->SetPainter(false, Button::STATE_NORMAL, painter);
259  painter = views::Painter::CreateImageGridPainter(images[1]);
260  border->SetPainter(false, Button::STATE_HOVERED, painter);
261  painter = views::Painter::CreateImageGridPainter(images[2]);
262  border->SetPainter(false, Button::STATE_PRESSED, painter);
263
264  SetBorder(border.PassAs<views::Border>());
265
266  // Calculate a representative background color of the provided image grid and
267  // set it as the background color of the host label in order to color the text
268  // appropriately. We grab the color of the middle pixel of the middle image
269  // of the background, which we treat as the representative color of the entire
270  // background (reasonable, given the current appearance of these images).
271  const SkBitmap& bitmap(
272      GetThemeProvider()->GetImageSkiaNamed(
273          images[0][4])->GetRepresentation(1.0f).sk_bitmap());
274  SkAutoLockPixels pixel_lock(bitmap);
275  host_label_->SetBackgroundColor(
276      bitmap.getColor(bitmap.width() / 2, bitmap.height() / 2));
277}
278
279void OriginChipView::OnChanged() {
280  Update(location_bar_view_->GetWebContents());
281  // TODO(gbillock): Also need to potentially repaint infobars to make sure the
282  // arrows are pointing to the right spot. Only needed for some edge cases.
283}
284
285void OriginChipView::FadeIn() {
286  fade_in_animation_->Show();
287}
288
289void OriginChipView::AnimationProgressed(const gfx::Animation* animation) {
290  if (animation == fade_in_animation_.get())
291    SchedulePaint();
292  else
293    views::LabelButton::AnimationProgressed(animation);
294}
295
296void OriginChipView::AnimationEnded(const gfx::Animation* animation) {
297  if (animation == fade_in_animation_.get())
298    fade_in_animation_->Reset();
299  else
300    views::LabelButton::AnimationEnded(animation);
301}
302
303gfx::Size OriginChipView::GetPreferredSize() {
304  gfx::Size label_size = host_label_->GetPreferredSize();
305  gfx::Size icon_size = location_icon_view_->GetPreferredSize();
306  int icon_spacing = showing_16x16_icon_ ?
307      (k16x16IconLeadingSpacing + k16x16IconTrailingSpacing) : 0;
308  return gfx::Size(kEdgeThickness + icon_size.width() + icon_spacing +
309                   kIconTextSpacing + label_size.width() +
310                   kTrailingLabelMargin + kEdgeThickness,
311                   icon_size.height());
312}
313
314void OriginChipView::Layout() {
315  // TODO(gbillock): Eventually we almost certainly want to use
316  // LocationBarLayout for leading and trailing decorations.
317
318  location_icon_view_->SetBounds(
319      kEdgeThickness + (showing_16x16_icon_ ? k16x16IconLeadingSpacing : 0),
320      LocationBarView::kNormalEdgeThickness,
321      location_icon_view_->GetPreferredSize().width(),
322      height() - 2 * LocationBarView::kNormalEdgeThickness);
323
324  int host_label_x = location_icon_view_->x() + location_icon_view_->width() +
325      kIconTextSpacing;
326  host_label_x += showing_16x16_icon_ ? k16x16IconTrailingSpacing : 0;
327  int host_label_width =
328      width() - host_label_x - kEdgeThickness - kTrailingLabelMargin;
329  host_label_->SetBounds(host_label_x,
330                         LocationBarView::kNormalEdgeThickness,
331                         host_label_width,
332                         height() - 2 * LocationBarView::kNormalEdgeThickness);
333}
334
335void OriginChipView::OnPaintBorder(gfx::Canvas* canvas) {
336  if (fade_in_animation_->is_animating()) {
337    canvas->SaveLayerAlpha(static_cast<uint8>(
338        fade_in_animation_->CurrentValueBetween(0, 255)));
339    views::LabelButton::OnPaintBorder(canvas);
340    canvas->Restore();
341  } else {
342    views::LabelButton::OnPaintBorder(canvas);
343  }
344}
345
346int OriginChipView::ElideDomainTarget(int target_max_width) {
347  base::string16 host =
348      OriginChip::LabelFromURLForProfile(url_displayed_, profile_);
349  host_label_->SetText(host);
350  int width = GetPreferredSize().width();
351  if (width <= target_max_width)
352    return width;
353
354  gfx::Size label_size = host_label_->GetPreferredSize();
355  int padding_width = width - label_size.width();
356
357  host_label_->SetText(ElideHost(
358      location_bar_view_->GetToolbarModel()->GetURL(),
359      host_label_->font_list(), target_max_width - padding_width));
360  return GetPreferredSize().width();
361}
362
363// TODO(gbillock): Make the LocationBarView or OmniboxView the listener for
364// this button.
365void OriginChipView::ButtonPressed(views::Button* sender,
366                                 const ui::Event& event) {
367  // See if the event needs to be passed to the LocationIconView.
368  if (event.IsMouseEvent() || (event.type() == ui::ET_GESTURE_TAP)) {
369    location_icon_view_->set_interactive(true);
370    const ui::LocatedEvent& located_event =
371        static_cast<const ui::LocatedEvent&>(event);
372    if (GetEventHandlerForPoint(located_event.location()) ==
373            location_icon_view_) {
374      location_icon_view_->page_info_helper()->ProcessEvent(located_event);
375      location_icon_view_->set_interactive(false);
376      return;
377    }
378    location_icon_view_->set_interactive(false);
379  }
380
381  UMA_HISTOGRAM_COUNTS("OriginChip.Pressed", 1);
382  content::RecordAction(base::UserMetricsAction("OriginChipPress"));
383
384  location_bar_view_->ShowURL();
385}
386
387// Note: When OnSafeBrowsingHit would be called, OnSafeBrowsingMatch will
388// have already been called.
389void OriginChipView::OnSafeBrowsingHit(
390    const SafeBrowsingUIManager::UnsafeResource& resource) {}
391
392void OriginChipView::OnSafeBrowsingMatch(
393    const SafeBrowsingUIManager::UnsafeResource& resource) {
394  OnChanged();
395}
396