Upstream version 7.36.149.0
[platform/framework/web/crosswalk.git] / src / chrome / browser / ui / views / location_bar / location_bar_view.cc
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/location_bar/location_bar_view.h"
6
7 #include <algorithm>
8 #include <map>
9
10 #include "base/command_line.h"
11 #include "base/i18n/rtl.h"
12 #include "base/prefs/pref_service.h"
13 #include "base/stl_util.h"
14 #include "base/strings/string_split.h"
15 #include "base/strings/utf_string_conversions.h"
16 #include "chrome/app/chrome_command_ids.h"
17 #include "chrome/browser/chrome_notification_types.h"
18 #include "chrome/browser/command_updater.h"
19 #include "chrome/browser/defaults.h"
20 #include "chrome/browser/extensions/api/omnibox/omnibox_api.h"
21 #include "chrome/browser/extensions/extension_service.h"
22 #include "chrome/browser/extensions/location_bar_controller.h"
23 #include "chrome/browser/extensions/tab_helper.h"
24 #include "chrome/browser/favicon/favicon_tab_helper.h"
25 #include "chrome/browser/profiles/profile.h"
26 #include "chrome/browser/search/instant_service.h"
27 #include "chrome/browser/search/instant_service_factory.h"
28 #include "chrome/browser/search/search.h"
29 #include "chrome/browser/search_engines/template_url.h"
30 #include "chrome/browser/search_engines/template_url_service.h"
31 #include "chrome/browser/search_engines/template_url_service_factory.h"
32 #include "chrome/browser/translate/translate_service.h"
33 #include "chrome/browser/translate/translate_tab_helper.h"
34 #include "chrome/browser/ui/browser.h"
35 #include "chrome/browser/ui/browser_finder.h"
36 #include "chrome/browser/ui/browser_instant_controller.h"
37 #include "chrome/browser/ui/browser_window.h"
38 #include "chrome/browser/ui/omnibox/location_bar_util.h"
39 #include "chrome/browser/ui/omnibox/omnibox_popup_model.h"
40 #include "chrome/browser/ui/omnibox/omnibox_popup_view.h"
41 #include "chrome/browser/ui/passwords/manage_passwords_icon.h"
42 #include "chrome/browser/ui/passwords/manage_passwords_ui_controller.h"
43 #include "chrome/browser/ui/tabs/tab_strip_model.h"
44 #include "chrome/browser/ui/toolbar/origin_chip_info.h"
45 #include "chrome/browser/ui/view_ids.h"
46 #include "chrome/browser/ui/views/browser_dialogs.h"
47 #include "chrome/browser/ui/views/location_bar/content_setting_image_view.h"
48 #include "chrome/browser/ui/views/location_bar/ev_bubble_view.h"
49 #include "chrome/browser/ui/views/location_bar/generated_credit_card_view.h"
50 #include "chrome/browser/ui/views/location_bar/keyword_hint_view.h"
51 #include "chrome/browser/ui/views/location_bar/location_bar_layout.h"
52 #include "chrome/browser/ui/views/location_bar/location_icon_view.h"
53 #include "chrome/browser/ui/views/location_bar/open_pdf_in_reader_view.h"
54 #include "chrome/browser/ui/views/location_bar/origin_chip_view.h"
55 #include "chrome/browser/ui/views/location_bar/page_action_image_view.h"
56 #include "chrome/browser/ui/views/location_bar/page_action_with_badge_view.h"
57 #include "chrome/browser/ui/views/location_bar/selected_keyword_view.h"
58 #include "chrome/browser/ui/views/location_bar/star_view.h"
59 #include "chrome/browser/ui/views/location_bar/translate_icon_view.h"
60 #include "chrome/browser/ui/views/location_bar/zoom_bubble_view.h"
61 #include "chrome/browser/ui/views/location_bar/zoom_view.h"
62 #include "chrome/browser/ui/views/passwords/manage_passwords_bubble_view.h"
63 #include "chrome/browser/ui/views/passwords/manage_passwords_icon_view.h"
64 #include "chrome/browser/ui/views/toolbar/toolbar_origin_chip_view.h"
65 #include "chrome/browser/ui/zoom/zoom_controller.h"
66 #include "chrome/common/chrome_switches.h"
67 #include "chrome/common/pref_names.h"
68 #include "content/public/browser/notification_service.h"
69 #include "content/public/browser/render_widget_host_view.h"
70 #include "content/public/browser/web_contents.h"
71 #include "extensions/browser/extension_system.h"
72 #include "extensions/common/feature_switch.h"
73 #include "extensions/common/permissions/permissions_data.h"
74 #include "grit/generated_resources.h"
75 #include "grit/theme_resources.h"
76 #include "ui/accessibility/ax_view_state.h"
77 #include "ui/base/dragdrop/drag_drop_types.h"
78 #include "ui/base/l10n/l10n_util.h"
79 #include "ui/base/resource/resource_bundle.h"
80 #include "ui/base/theme_provider.h"
81 #include "ui/events/event.h"
82 #include "ui/gfx/animation/slide_animation.h"
83 #include "ui/gfx/canvas.h"
84 #include "ui/gfx/color_utils.h"
85 #include "ui/gfx/image/image.h"
86 #include "ui/gfx/image/image_skia_operations.h"
87 #include "ui/gfx/skia_util.h"
88 #include "ui/gfx/text_utils.h"
89 #include "ui/native_theme/native_theme.h"
90 #include "ui/views/background.h"
91 #include "ui/views/border.h"
92 #include "ui/views/button_drag_utils.h"
93 #include "ui/views/controls/button/image_button.h"
94 #include "ui/views/controls/button/label_button.h"
95 #include "ui/views/controls/button/label_button_border.h"
96 #include "ui/views/controls/label.h"
97 #include "ui/views/widget/widget.h"
98
99 #if !defined(OS_CHROMEOS)
100 #include "chrome/browser/ui/views/first_run_bubble.h"
101 #endif
102
103 using content::WebContents;
104 using views::View;
105
106 namespace {
107
108 #if !defined(OS_CHROMEOS)
109 Browser* GetBrowserFromDelegate(LocationBarView::Delegate* delegate) {
110   WebContents* web_contents = delegate->GetWebContents();
111   return web_contents ? chrome::FindBrowserWithWebContents(web_contents) : NULL;
112 }
113 #endif
114
115 // Given a containing |height| and a |base_font_list|, shrinks the font size
116 // until the font list will fit within |height| while having its cap height
117 // vertically centered.  Returns the correctly-sized font list.
118 //
119 // The expected layout:
120 //   +--------+-----------------------------------------------+------------+
121 //   |        | y offset                                      | space      |
122 //   |        +--------+-------------------+------------------+ above      |
123 //   |        |        |                   | internal leading | cap height |
124 //   | box    | font   | ascent (baseline) +------------------+------------+
125 //   | height | height |                   | cap height                    |
126 //   |        |        |-------------------+------------------+------------+
127 //   |        |        | descent (height - baseline)          | space      |
128 //   |        +--------+--------------------------------------+ below      |
129 //   |        | space at bottom                               | cap height |
130 //   +--------+-----------------------------------------------+------------+
131 // Goal:
132 //     center of box height == center of cap height
133 //     (i.e. space above cap height == space below cap height)
134 // Restrictions:
135 //     y offset >= 0
136 //     space at bottom >= 0
137 //     (i.e. Entire font must be visible inside the box.)
138 gfx::FontList GetLargestFontListWithHeightBound(
139     const gfx::FontList& base_font_list,
140     int height) {
141   gfx::FontList font_list = base_font_list;
142   for (int font_size = font_list.GetFontSize(); font_size > 1; --font_size) {
143     const int internal_leading =
144         font_list.GetBaseline() - font_list.GetCapHeight();
145     // Some platforms don't support getting the cap height, and simply return
146     // the entire font ascent from GetCapHeight().  Centering the ascent makes
147     // the font look too low, so if GetCapHeight() returns the ascent, center
148     // the entire font height instead.
149     const int space =
150         height - ((internal_leading != 0) ?
151                   font_list.GetCapHeight() : font_list.GetHeight());
152     const int y_offset = space / 2 - internal_leading;
153     const int space_at_bottom = height - (y_offset + font_list.GetHeight());
154     if ((y_offset >= 0) && (space_at_bottom >= 0))
155       break;
156     font_list = font_list.DeriveWithSizeDelta(-1);
157   }
158   return font_list;
159 }
160
161 // Functor for moving BookmarkManagerPrivate page actions to the right via
162 // stable_partition.
163 class IsPageActionViewRightAligned {
164  public:
165   explicit IsPageActionViewRightAligned(ExtensionService* extension_service)
166       : extension_service_(extension_service) {}
167
168   bool operator()(PageActionWithBadgeView* page_action_view) {
169     return extensions::PermissionsData::HasAPIPermission(
170         extension_service_->GetExtensionById(
171             page_action_view->image_view()->page_action()->extension_id(),
172             false),
173         extensions::APIPermission::kBookmarkManagerPrivate);
174   }
175
176  private:
177   ExtensionService* extension_service_;
178
179   // NOTE: Can't DISALLOW_COPY_AND_ASSIGN as we pass this object by value to
180   // std::stable_partition().
181 };
182
183 }  // namespace
184
185
186 // LocationBarView -----------------------------------------------------------
187
188 // static
189 const int LocationBarView::kNormalEdgeThickness = 2;
190 const int LocationBarView::kPopupEdgeThickness = 1;
191 const int LocationBarView::kItemPadding = 3;
192 const int LocationBarView::kIconInternalPadding = 2;
193 const int LocationBarView::kBubblePadding = 1;
194 const char LocationBarView::kViewClassName[] = "LocationBarView";
195
196 LocationBarView::LocationBarView(Browser* browser,
197                                  Profile* profile,
198                                  CommandUpdater* command_updater,
199                                  Delegate* delegate,
200                                  bool is_popup_mode)
201     : LocationBar(profile),
202       OmniboxEditController(command_updater),
203       browser_(browser),
204       omnibox_view_(NULL),
205       delegate_(delegate),
206       origin_chip_view_(NULL),
207       toolbar_origin_chip_view_(NULL),
208       location_icon_view_(NULL),
209       ev_bubble_view_(NULL),
210       ime_inline_autocomplete_view_(NULL),
211       selected_keyword_view_(NULL),
212       suggested_text_view_(NULL),
213       keyword_hint_view_(NULL),
214       mic_search_view_(NULL),
215       zoom_view_(NULL),
216       generated_credit_card_view_(NULL),
217       open_pdf_in_reader_view_(NULL),
218       manage_passwords_icon_view_(NULL),
219       translate_icon_view_(NULL),
220       star_view_(NULL),
221       search_button_(NULL),
222       is_popup_mode_(is_popup_mode),
223       show_focus_rect_(false),
224       template_url_service_(NULL),
225       dropdown_animation_offset_(0),
226       animated_host_label_(NULL),
227       weak_ptr_factory_(this) {
228   edit_bookmarks_enabled_.Init(
229       prefs::kEditBookmarksEnabled, profile->GetPrefs(),
230       base::Bind(&LocationBarView::Update, base::Unretained(this),
231                  static_cast<content::WebContents*>(NULL)));
232
233   if (browser_)
234     browser_->search_model()->AddObserver(this);
235 }
236
237 LocationBarView::~LocationBarView() {
238   if (template_url_service_)
239     template_url_service_->RemoveObserver(this);
240   if (browser_)
241     browser_->search_model()->RemoveObserver(this);
242 }
243
244 ////////////////////////////////////////////////////////////////////////////////
245 // LocationBarView, public:
246
247 void LocationBarView::Init() {
248   // We need to be in a Widget, otherwise GetNativeTheme() may change and we're
249   // not prepared for that.
250   DCHECK(GetWidget());
251
252   const int kOmniboxPopupBorderImages[] =
253       IMAGE_GRID(IDR_OMNIBOX_POPUP_BORDER_AND_SHADOW);
254   const int kOmniboxBorderImages[] = IMAGE_GRID(IDR_TEXTFIELD);
255   border_painter_.reset(views::Painter::CreateImageGridPainter(
256       is_popup_mode_ ? kOmniboxPopupBorderImages : kOmniboxBorderImages));
257
258   location_icon_view_ = new LocationIconView(this);
259   location_icon_view_->set_drag_controller(this);
260   AddChildView(location_icon_view_);
261
262   // Determine the main font.
263   gfx::FontList font_list = ResourceBundle::GetSharedInstance().GetFontList(
264       ResourceBundle::BaseFont);
265   const int current_font_size = font_list.GetFontSize();
266   const int desired_font_size = browser_defaults::kOmniboxFontPixelSize;
267   if (current_font_size != desired_font_size) {
268     font_list =
269         font_list.DeriveWithSizeDelta(desired_font_size - current_font_size);
270   }
271   // Shrink large fonts to make them fit.
272   // TODO(pkasting): Stretch the location bar instead in this case.
273   const int location_height = GetInternalHeight(true);
274   font_list = GetLargestFontListWithHeightBound(font_list, location_height);
275
276   // Determine the font for use inside the bubbles.  The bubble background
277   // images have 1 px thick edges, which we don't want to overlap.
278   const int kBubbleInteriorVerticalPadding = 1;
279   const int bubble_vertical_padding =
280       (kBubblePadding + kBubbleInteriorVerticalPadding) * 2;
281   const gfx::FontList bubble_font_list(
282       GetLargestFontListWithHeightBound(
283           font_list, location_height - bubble_vertical_padding));
284
285   const SkColor background_color =
286       GetColor(ToolbarModel::NONE, LocationBarView::BACKGROUND);
287   ev_bubble_view_ = new EVBubbleView(
288       bubble_font_list, GetColor(ToolbarModel::EV_SECURE, SECURITY_TEXT),
289       background_color, this);
290   ev_bubble_view_->set_drag_controller(this);
291   AddChildView(ev_bubble_view_);
292
293   // Initialize the Omnibox view.
294   omnibox_view_ = new OmniboxViewViews(
295       this, profile(), command_updater(),
296       is_popup_mode_ ||
297           (browser_->is_app() && CommandLine::ForCurrentProcess()->
298               HasSwitch(switches::kEnableStreamlinedHostedApps)),
299       this, font_list);
300   omnibox_view_->Init();
301   omnibox_view_->SetFocusable(true);
302   AddChildView(omnibox_view_);
303
304   // Initialize the inline autocomplete view which is visible only when IME is
305   // turned on.  Use the same font with the omnibox and highlighted background.
306   ime_inline_autocomplete_view_ = new views::Label(base::string16(), font_list);
307   ime_inline_autocomplete_view_->SetHorizontalAlignment(gfx::ALIGN_LEFT);
308   ime_inline_autocomplete_view_->SetAutoColorReadabilityEnabled(false);
309   ime_inline_autocomplete_view_->set_background(
310       views::Background::CreateSolidBackground(GetNativeTheme()->GetSystemColor(
311           ui::NativeTheme::kColorId_TextfieldSelectionBackgroundFocused)));
312   ime_inline_autocomplete_view_->SetEnabledColor(
313       GetNativeTheme()->GetSystemColor(
314           ui::NativeTheme::kColorId_TextfieldSelectionColor));
315   ime_inline_autocomplete_view_->SetVisible(false);
316   AddChildView(ime_inline_autocomplete_view_);
317
318   animated_host_label_ = new views::Label(base::string16(), font_list);
319   animated_host_label_->SetVisible(false);
320   AddChildView(animated_host_label_);
321
322   origin_chip_view_ = new OriginChipView(this, profile(), font_list);
323   origin_chip_view_->SetFocusable(false);
324   origin_chip_view_->set_drag_controller(this);
325   AddChildView(origin_chip_view_);
326
327   const SkColor text_color = GetColor(ToolbarModel::NONE, TEXT);
328   selected_keyword_view_ = new SelectedKeywordView(
329       bubble_font_list, text_color, background_color, profile());
330   AddChildView(selected_keyword_view_);
331
332   suggested_text_view_ = new views::Label(base::string16(), font_list);
333   suggested_text_view_->SetHorizontalAlignment(gfx::ALIGN_LEFT);
334   suggested_text_view_->SetAutoColorReadabilityEnabled(false);
335   suggested_text_view_->SetEnabledColor(GetColor(
336       ToolbarModel::NONE, LocationBarView::DEEMPHASIZED_TEXT));
337   suggested_text_view_->SetVisible(false);
338   AddChildView(suggested_text_view_);
339
340   keyword_hint_view_ = new KeywordHintView(
341       profile(), font_list,
342       GetColor(ToolbarModel::NONE, LocationBarView::DEEMPHASIZED_TEXT),
343       background_color);
344   AddChildView(keyword_hint_view_);
345
346   mic_search_view_ = new views::ImageButton(this);
347   mic_search_view_->set_id(VIEW_ID_MIC_SEARCH_BUTTON);
348   mic_search_view_->SetAccessibilityFocusable(true);
349   mic_search_view_->SetTooltipText(
350       l10n_util::GetStringUTF16(IDS_TOOLTIP_MIC_SEARCH));
351   mic_search_view_->SetImage(
352       views::Button::STATE_NORMAL,
353       ui::ResourceBundle::GetSharedInstance().GetImageSkiaNamed(
354           IDR_OMNIBOX_MIC_SEARCH));
355   mic_search_view_->SetImageAlignment(views::ImageButton::ALIGN_CENTER,
356                                       views::ImageButton::ALIGN_MIDDLE);
357   mic_search_view_->SetVisible(false);
358   AddChildView(mic_search_view_);
359
360   for (int i = 0; i < CONTENT_SETTINGS_NUM_TYPES; ++i) {
361     ContentSettingImageView* content_blocked_view =
362         new ContentSettingImageView(static_cast<ContentSettingsType>(i), this,
363                                     bubble_font_list, text_color,
364                                     background_color);
365     content_setting_views_.push_back(content_blocked_view);
366     content_blocked_view->SetVisible(false);
367     AddChildView(content_blocked_view);
368   }
369
370   generated_credit_card_view_ = new GeneratedCreditCardView(delegate_);
371   AddChildView(generated_credit_card_view_);
372
373   zoom_view_ = new ZoomView(delegate_);
374   zoom_view_->set_id(VIEW_ID_ZOOM_BUTTON);
375   AddChildView(zoom_view_);
376
377   open_pdf_in_reader_view_ = new OpenPDFInReaderView();
378   AddChildView(open_pdf_in_reader_view_);
379
380   manage_passwords_icon_view_ = new ManagePasswordsIconView(command_updater());
381   AddChildView(manage_passwords_icon_view_);
382
383   translate_icon_view_ = new TranslateIconView(command_updater());
384   translate_icon_view_->SetVisible(false);
385   AddChildView(translate_icon_view_);
386
387   star_view_ = new StarView(command_updater());
388   star_view_->SetVisible(false);
389   AddChildView(star_view_);
390
391   search_button_ = new views::LabelButton(this, base::string16());
392   search_button_->set_triggerable_event_flags(
393       ui::EF_LEFT_MOUSE_BUTTON | ui::EF_MIDDLE_MOUSE_BUTTON);
394   search_button_->SetStyle(views::Button::STYLE_BUTTON);
395   search_button_->SetFocusable(false);
396   search_button_->set_min_size(gfx::Size());
397   scoped_ptr<views::LabelButtonBorder> search_button_border(
398       new views::LabelButtonBorder(search_button_->style()));
399   search_button_border->set_insets(gfx::Insets());
400   const int kSearchButtonNormalImages[] = IMAGE_GRID(IDR_OMNIBOX_SEARCH_BUTTON);
401   search_button_border->SetPainter(
402       false, views::Button::STATE_NORMAL,
403       views::Painter::CreateImageGridPainter(kSearchButtonNormalImages));
404   const int kSearchButtonHoveredImages[] =
405       IMAGE_GRID(IDR_OMNIBOX_SEARCH_BUTTON_HOVER);
406   search_button_border->SetPainter(
407       false, views::Button::STATE_HOVERED,
408       views::Painter::CreateImageGridPainter(kSearchButtonHoveredImages));
409   const int kSearchButtonPressedImages[] =
410       IMAGE_GRID(IDR_OMNIBOX_SEARCH_BUTTON_PRESSED);
411   search_button_border->SetPainter(
412       false, views::Button::STATE_PRESSED,
413       views::Painter::CreateImageGridPainter(kSearchButtonPressedImages));
414   search_button_border->SetPainter(false, views::Button::STATE_DISABLED, NULL);
415   search_button_border->SetPainter(true, views::Button::STATE_NORMAL, NULL);
416   search_button_border->SetPainter(true, views::Button::STATE_HOVERED, NULL);
417   search_button_border->SetPainter(true, views::Button::STATE_PRESSED, NULL);
418   search_button_border->SetPainter(true, views::Button::STATE_DISABLED, NULL);
419   search_button_->SetBorder(search_button_border.PassAs<views::Border>());
420   const int kSearchButtonWidth = 56;
421   search_button_->set_min_size(gfx::Size(kSearchButtonWidth, 0));
422   search_button_->SetVisible(false);
423   AddChildView(search_button_);
424
425   show_url_animation_.reset(new gfx::SlideAnimation(this));
426   show_url_animation_->SetTweenType(gfx::Tween::FAST_OUT_SLOW_IN);
427   show_url_animation_->SetSlideDuration(200);
428
429   hide_url_animation_.reset(new gfx::SlideAnimation(this));
430   hide_url_animation_->SetTweenType(gfx::Tween::FAST_OUT_SLOW_IN);
431   hide_url_animation_->SetSlideDuration(200);
432
433   content::Source<Profile> profile_source = content::Source<Profile>(profile());
434   registrar_.Add(this,
435                  chrome::NOTIFICATION_EXTENSION_LOCATION_BAR_UPDATED,
436                  profile_source);
437   registrar_.Add(
438       this, chrome::NOTIFICATION_EXTENSION_LOADED_DEPRECATED, profile_source);
439   registrar_.Add(this,
440                  chrome::NOTIFICATION_EXTENSION_UNLOADED_DEPRECATED,
441                  profile_source);
442
443   // Initialize the location entry. We do this to avoid a black flash which is
444   // visible when the location entry has just been initialized.
445   Update(NULL);
446 }
447
448 bool LocationBarView::IsInitialized() const {
449   return omnibox_view_ != NULL;
450 }
451
452 SkColor LocationBarView::GetColor(ToolbarModel::SecurityLevel security_level,
453                                   ColorKind kind) const {
454   const ui::NativeTheme* native_theme = GetNativeTheme();
455   switch (kind) {
456     case BACKGROUND:
457       return native_theme->GetSystemColor(
458           ui::NativeTheme::kColorId_TextfieldDefaultBackground);
459
460     case TEXT:
461       return native_theme->GetSystemColor(
462           ui::NativeTheme::kColorId_TextfieldDefaultColor);
463
464     case SELECTED_TEXT:
465       return native_theme->GetSystemColor(
466           ui::NativeTheme::kColorId_TextfieldSelectionColor);
467
468     case DEEMPHASIZED_TEXT:
469       return color_utils::AlphaBlend(
470           GetColor(security_level, TEXT),
471           GetColor(security_level, BACKGROUND),
472           128);
473
474     case SECURITY_TEXT: {
475       SkColor color;
476       switch (security_level) {
477         case ToolbarModel::EV_SECURE:
478         case ToolbarModel::SECURE:
479           color = SkColorSetRGB(7, 149, 0);
480           break;
481
482         case ToolbarModel::SECURITY_WARNING:
483         case ToolbarModel::SECURITY_POLICY_WARNING:
484           return GetColor(security_level, DEEMPHASIZED_TEXT);
485           break;
486
487         case ToolbarModel::SECURITY_ERROR:
488           color = SkColorSetRGB(162, 0, 0);
489           break;
490
491         default:
492           NOTREACHED();
493           return GetColor(security_level, TEXT);
494       }
495       return color_utils::GetReadableColor(
496           color, GetColor(security_level, BACKGROUND));
497     }
498
499     default:
500       NOTREACHED();
501       return GetColor(security_level, TEXT);
502   }
503 }
504
505 void LocationBarView::ZoomChangedForActiveTab(bool can_show_bubble) {
506   DCHECK(zoom_view_);
507   if (RefreshZoomView()) {
508     Layout();
509     SchedulePaint();
510   }
511
512   WebContents* web_contents = GetWebContents();
513   if (can_show_bubble && zoom_view_->visible() && web_contents)
514     ZoomBubbleView::ShowBubble(web_contents, true);
515 }
516
517 void LocationBarView::SetPreviewEnabledPageAction(ExtensionAction* page_action,
518                                                   bool preview_enabled) {
519   if (is_popup_mode_)
520     return;
521
522   DCHECK(page_action);
523   WebContents* web_contents = GetWebContents();
524
525   RefreshPageActionViews();
526   PageActionWithBadgeView* page_action_view =
527       static_cast<PageActionWithBadgeView*>(GetPageActionView(page_action));
528   DCHECK(page_action_view);
529   if (!page_action_view)
530     return;
531
532   page_action_view->image_view()->set_preview_enabled(preview_enabled);
533   page_action_view->UpdateVisibility(web_contents, GetToolbarModel()->GetURL());
534   Layout();
535   SchedulePaint();
536 }
537
538 PageActionWithBadgeView* LocationBarView::GetPageActionView(
539     ExtensionAction* page_action) {
540   DCHECK(page_action);
541   for (PageActionViews::const_iterator i(page_action_views_.begin());
542        i != page_action_views_.end(); ++i) {
543     if ((*i)->image_view()->page_action() == page_action)
544       return *i;
545   }
546   return NULL;
547 }
548
549 void LocationBarView::SetStarToggled(bool on) {
550   if (star_view_)
551     star_view_->SetToggled(on);
552 }
553
554 void LocationBarView::SetTranslateIconToggled(bool on) {
555   translate_icon_view_->SetToggled(on);
556 }
557
558 gfx::Point LocationBarView::GetOmniboxViewOrigin() const {
559   gfx::Point origin(omnibox_view_->bounds().origin());
560   // If the UI layout is RTL, the coordinate system is not transformed and
561   // therefore we need to adjust the X coordinate so that bubble appears on the
562   // right hand side of the location bar.
563   if (base::i18n::IsRTL())
564     origin.set_x(width() - origin.x());
565   views::View::ConvertPointToScreen(this, &origin);
566   return origin;
567 }
568
569 void LocationBarView::SetImeInlineAutocompletion(const base::string16& text) {
570   ime_inline_autocomplete_view_->SetText(text);
571   ime_inline_autocomplete_view_->SetVisible(!text.empty());
572 }
573
574 void LocationBarView::SetGrayTextAutocompletion(const base::string16& text) {
575   if (suggested_text_view_->text() != text) {
576     suggested_text_view_->SetText(text);
577     suggested_text_view_->SetVisible(!text.empty());
578     Layout();
579     SchedulePaint();
580   }
581 }
582
583 base::string16 LocationBarView::GetGrayTextAutocompletion() const {
584   return HasValidSuggestText() ? suggested_text_view_->text()
585                                : base::string16();
586 }
587
588 void LocationBarView::SetShowFocusRect(bool show) {
589   show_focus_rect_ = show;
590   SchedulePaint();
591 }
592
593 void LocationBarView::SelectAll() {
594   omnibox_view_->SelectAll(true);
595 }
596
597 views::ImageView* LocationBarView::GetLocationIconView() {
598   return toolbar_origin_chip_view_ ?
599       toolbar_origin_chip_view_->location_icon_view() : location_icon_view_;
600 }
601
602 const views::ImageView* LocationBarView::GetLocationIconView() const {
603   return toolbar_origin_chip_view_ ?
604       toolbar_origin_chip_view_->location_icon_view() : location_icon_view_;
605 }
606
607 views::View* LocationBarView::GetLocationBarAnchor() {
608   return GetLocationIconView();
609 }
610
611 gfx::Point LocationBarView::GetLocationBarAnchorPoint() const {
612   // The +1 in the next line creates a 1-px gap between icon and arrow tip.
613   gfx::Point icon_bottom(0, GetLocationIconView()->GetImageBounds().bottom() -
614       LocationBarView::kIconInternalPadding + 1);
615   gfx::Point icon_center(GetLocationIconView()->GetImageBounds().CenterPoint());
616   gfx::Point point(icon_center.x(), icon_bottom.y());
617   ConvertPointToTarget(GetLocationIconView(), this, &point);
618   return point;
619 }
620
621 views::View* LocationBarView::generated_credit_card_view() {
622   return generated_credit_card_view_;
623 }
624
625 int LocationBarView::GetInternalHeight(bool use_preferred_size) {
626   int total_height =
627       use_preferred_size ? GetPreferredSize().height() : height();
628   return std::max(total_height - (vertical_edge_thickness() * 2), 0);
629 }
630
631 void LocationBarView::GetOmniboxPopupPositioningInfo(
632     gfx::Point* top_left_screen_coord,
633     int* popup_width,
634     int* left_margin,
635     int* right_margin) {
636   // Because the popup might appear atop the attached bookmark bar, there won't
637   // necessarily be a client edge separating it from the rest of the toolbar.
638   // Therefore we position the popup high enough so it can draw its own client
639   // edge at the top, in the same place the toolbar would normally draw the
640   // client edge.
641   *top_left_screen_coord = gfx::Point(
642       0,
643       parent()->height() - views::NonClientFrameView::kClientEdgeThickness);
644   views::View::ConvertPointToScreen(parent(), top_left_screen_coord);
645   *popup_width = parent()->width();
646
647   gfx::Rect location_bar_bounds(bounds());
648   location_bar_bounds.Inset(kNormalEdgeThickness, 0);
649   *left_margin = location_bar_bounds.x();
650   *right_margin = *popup_width - location_bar_bounds.right();
651 }
652
653 ////////////////////////////////////////////////////////////////////////////////
654 // LocationBarView, public LocationBar implementation:
655
656 void LocationBarView::FocusLocation(bool select_all) {
657   omnibox_view_->SetFocus();
658   if (select_all)
659     omnibox_view_->SelectAll(true);
660 }
661
662 void LocationBarView::Revert() {
663   omnibox_view_->RevertAll();
664 }
665
666 OmniboxView* LocationBarView::GetOmniboxView() {
667   return omnibox_view_;
668 }
669
670 ////////////////////////////////////////////////////////////////////////////////
671 // LocationBarView, public views::View implementation:
672
673 bool LocationBarView::HasFocus() const {
674   return omnibox_view_->model()->has_focus();
675 }
676
677 void LocationBarView::GetAccessibleState(ui::AXViewState* state) {
678   if (!IsInitialized())
679     return;
680
681   state->role = ui::AX_ROLE_LOCATION_BAR;
682   state->name = l10n_util::GetStringUTF16(IDS_ACCNAME_LOCATION);
683   state->value = omnibox_view_->GetText();
684
685   base::string16::size_type entry_start;
686   base::string16::size_type entry_end;
687   omnibox_view_->GetSelectionBounds(&entry_start, &entry_end);
688   state->selection_start = entry_start;
689   state->selection_end = entry_end;
690
691   if (is_popup_mode_) {
692     state->AddStateFlag(ui::AX_STATE_READ_ONLY);
693   } else {
694     state->set_value_callback =
695         base::Bind(&LocationBarView::AccessibilitySetValue,
696                    weak_ptr_factory_.GetWeakPtr());
697   }
698 }
699
700 gfx::Size LocationBarView::GetPreferredSize() {
701   gfx::Size background_min_size(border_painter_->GetMinimumSize());
702   if (!IsInitialized())
703     return background_min_size;
704
705   gfx::Size origin_chip_view_min_size(origin_chip_view_->GetMinimumSize());
706   gfx::Size search_button_min_size(search_button_->GetMinimumSize());
707   gfx::Size min_size(background_min_size);
708   min_size.SetToMax(search_button_min_size);
709   min_size.set_width(origin_chip_view_min_size.width() +
710                      background_min_size.width() +
711                      search_button_min_size.width());
712   return min_size;
713 }
714
715 void LocationBarView::Layout() {
716   if (!IsInitialized())
717     return;
718
719   animated_host_label_->SetVisible(false);
720   origin_chip_view_->SetVisible(origin_chip_view_->ShouldShow());
721   selected_keyword_view_->SetVisible(false);
722   location_icon_view_->SetVisible(false);
723   ev_bubble_view_->SetVisible(false);
724   keyword_hint_view_->SetVisible(false);
725
726   // The textfield has 1 px of whitespace before the text in the RTL case only.
727   const int kEditLeadingInternalSpace = base::i18n::IsRTL() ? 1 : 0;
728   LocationBarLayout leading_decorations(
729       LocationBarLayout::LEFT_EDGE, kItemPadding - kEditLeadingInternalSpace);
730   LocationBarLayout trailing_decorations(LocationBarLayout::RIGHT_EDGE,
731                                          kItemPadding);
732
733   // Show and position the animated host label used in the show and hide URL
734   // animations.
735   if (show_url_animation_->is_animating() ||
736       hide_url_animation_->is_animating()) {
737     WebContents* web_contents = GetWebContents();
738     const GURL url = web_contents ? web_contents->GetURL() : GURL();
739     const base::string16 host =
740         OriginChip::LabelFromURLForProfile(url, profile());
741     animated_host_label_->SetText(host);
742
743     const base::string16 formatted_url = GetToolbarModel()->GetFormattedURL();
744
745     // Split the formatted URL on the host name in order to determine the size
746     // of the text leading up to it.
747     std::vector<base::string16> substrings;
748     base::SplitStringUsingSubstr(formatted_url, host, &substrings);
749     const base::string16 text_leading_host = substrings[0];
750     const int leading_text_width =
751         gfx::Canvas::GetStringWidth(text_leading_host,
752                                     origin_chip_view_->GetFontList());
753
754     const int position_of_host_name_in_chip = origin_chip_view_->host_label_x();
755     const int position_of_host_name_in_url =
756         position_of_host_name_in_chip + leading_text_width;
757
758     int host_label_x = position_of_host_name_in_chip;
759     if (show_url_animation_->is_animating()) {
760       host_label_x = show_url_animation_->
761           CurrentValueBetween(position_of_host_name_in_chip,
762                               position_of_host_name_in_url);
763     } else if (hide_url_animation_->is_animating()) {
764       host_label_x = hide_url_animation_->
765           CurrentValueBetween(position_of_host_name_in_url,
766                               position_of_host_name_in_chip);
767     }
768     animated_host_label_->SetBounds(
769         host_label_x, 0,
770         animated_host_label_->GetPreferredSize().width(), height());
771     animated_host_label_->SetVisible(true);
772   }
773
774   const int origin_chip_width = origin_chip_view_->visible() ?
775       origin_chip_view_->GetPreferredSize().width() : 0;
776   origin_chip_view_->SetBounds(0, 0, origin_chip_width, height());
777
778   const base::string16 keyword(omnibox_view_->model()->keyword());
779   const bool is_keyword_hint(omnibox_view_->model()->is_keyword_hint());
780   const int bubble_location_y = vertical_edge_thickness() + kBubblePadding;
781   // In some cases (e.g. fullscreen mode) we may have 0 height.  We still want
782   // to position our child views in this case, because other things may be
783   // positioned relative to them (e.g. the "bookmark added" bubble if the user
784   // hits ctrl-d).
785   const int location_height = GetInternalHeight(false);
786   const int bubble_height = std::max(location_height - (kBubblePadding * 2), 0);
787   if (!keyword.empty() && !is_keyword_hint) {
788     leading_decorations.AddDecoration(bubble_location_y, bubble_height, true, 0,
789                                       kBubblePadding, kItemPadding,
790                                       selected_keyword_view_);
791     if (selected_keyword_view_->keyword() != keyword) {
792       selected_keyword_view_->SetKeyword(keyword);
793       const TemplateURL* template_url =
794           TemplateURLServiceFactory::GetForProfile(profile())->
795           GetTemplateURLForKeyword(keyword);
796       if (template_url &&
797           (template_url->GetType() == TemplateURL::OMNIBOX_API_EXTENSION)) {
798         gfx::Image image = extensions::OmniboxAPI::Get(profile())->
799             GetOmniboxIcon(template_url->GetExtensionId());
800         selected_keyword_view_->SetImage(image.AsImageSkia());
801         selected_keyword_view_->set_is_extension_icon(true);
802       } else {
803         selected_keyword_view_->SetImage(
804             *(GetThemeProvider()->GetImageSkiaNamed(IDR_OMNIBOX_SEARCH)));
805         selected_keyword_view_->set_is_extension_icon(false);
806       }
807     }
808   } else if (!toolbar_origin_chip_view_ &&
809       !chrome::ShouldDisplayOriginChipV2() &&
810       (GetToolbarModel()->GetSecurityLevel(false) == ToolbarModel::EV_SECURE)) {
811     ev_bubble_view_->SetLabel(GetToolbarModel()->GetEVCertName());
812     // The largest fraction of the omnibox that can be taken by the EV bubble.
813     const double kMaxBubbleFraction = 0.5;
814     leading_decorations.AddDecoration(bubble_location_y, bubble_height, false,
815                                       kMaxBubbleFraction, kBubblePadding,
816                                       kItemPadding, ev_bubble_view_);
817   } else if (!origin_chip_view_->visible()) {
818     leading_decorations.AddDecoration(
819         vertical_edge_thickness(), location_height,
820         location_icon_view_);
821   }
822
823   if (star_view_->visible()) {
824     trailing_decorations.AddDecoration(
825         vertical_edge_thickness(), location_height, star_view_);
826   }
827   if (translate_icon_view_->visible()) {
828     trailing_decorations.AddDecoration(
829         vertical_edge_thickness(), location_height, translate_icon_view_);
830   }
831   if (open_pdf_in_reader_view_->visible()) {
832     trailing_decorations.AddDecoration(
833         vertical_edge_thickness(), location_height, open_pdf_in_reader_view_);
834   }
835   if (manage_passwords_icon_view_->visible()) {
836     trailing_decorations.AddDecoration(vertical_edge_thickness(),
837                                        location_height,
838                                        manage_passwords_icon_view_);
839   }
840   for (PageActionViews::const_iterator i(page_action_views_.begin());
841        i != page_action_views_.end(); ++i) {
842     if ((*i)->visible()) {
843       trailing_decorations.AddDecoration(
844           vertical_edge_thickness(), location_height, (*i));
845     }
846   }
847   if (zoom_view_->visible()) {
848     trailing_decorations.AddDecoration(vertical_edge_thickness(),
849                                        location_height, zoom_view_);
850   }
851   for (ContentSettingViews::const_reverse_iterator i(
852            content_setting_views_.rbegin()); i != content_setting_views_.rend();
853        ++i) {
854     if ((*i)->visible()) {
855       trailing_decorations.AddDecoration(
856           bubble_location_y, bubble_height, false, 0, kItemPadding,
857           kItemPadding, (*i));
858     }
859   }
860   if (generated_credit_card_view_->visible()) {
861     trailing_decorations.AddDecoration(vertical_edge_thickness(),
862                                        location_height,
863                                        generated_credit_card_view_);
864   }
865   if (mic_search_view_->visible()) {
866     trailing_decorations.AddDecoration(vertical_edge_thickness(),
867                                        location_height, mic_search_view_);
868   }
869   // Because IMEs may eat the tab key, we don't show "press tab to search" while
870   // IME composition is in progress.
871   if (!keyword.empty() && is_keyword_hint && !omnibox_view_->IsImeComposing()) {
872     trailing_decorations.AddDecoration(vertical_edge_thickness(),
873                                        location_height, true, 0, kItemPadding,
874                                        kItemPadding, keyword_hint_view_);
875     if (keyword_hint_view_->keyword() != keyword)
876       keyword_hint_view_->SetKeyword(keyword);
877   }
878
879   // Perform layout.
880   const int horizontal_edge_thickness = GetHorizontalEdgeThickness();
881   int full_width = width() - horizontal_edge_thickness - origin_chip_width;
882
883   // The search button images are made to look as if they overlay the normal
884   // edge images, but to align things, the search button needs to be inset
885   // horizontally by 1 px.
886   const int kSearchButtonInset = 1;
887   const gfx::Size search_button_size(search_button_->GetPreferredSize());
888   const int search_button_reserved_width =
889       search_button_size.width() + kSearchButtonInset;
890   full_width -= search_button_->visible() ?
891       search_button_reserved_width : horizontal_edge_thickness;
892   int entry_width = full_width;
893   leading_decorations.LayoutPass1(&entry_width);
894   trailing_decorations.LayoutPass1(&entry_width);
895   leading_decorations.LayoutPass2(&entry_width);
896   trailing_decorations.LayoutPass2(&entry_width);
897
898   int location_needed_width = omnibox_view_->GetTextWidth();
899   int available_width = entry_width - location_needed_width;
900   // The bounds must be wide enough for all the decorations to fit.
901   gfx::Rect location_bounds(
902       origin_chip_width + horizontal_edge_thickness, vertical_edge_thickness(),
903       std::max(full_width, full_width - entry_width), location_height);
904   leading_decorations.LayoutPass3(&location_bounds, &available_width);
905   trailing_decorations.LayoutPass3(&location_bounds, &available_width);
906
907   // Layout out the suggested text view right aligned to the location
908   // entry. Only show the suggested text if we can fit the text from one
909   // character before the end of the selection to the end of the text and the
910   // suggested text. If we can't it means either the suggested text is too big,
911   // or the user has scrolled.
912
913   // TODO(sky): We could potentially adjust this to take into account suggested
914   // text to force using minimum size if necessary, but currently the chance of
915   // showing keyword hints and suggested text is minimal and we're not confident
916   // this is the right approach for suggested text.
917
918   int omnibox_view_margin = 0;
919   if (suggested_text_view_->visible()) {
920     // We do not display the suggested text when it contains a mix of RTL and
921     // LTR characters since this could mean the suggestion should be displayed
922     // in the middle of the string.
923     base::i18n::TextDirection text_direction =
924         base::i18n::GetStringDirection(omnibox_view_->GetText());
925     if (text_direction !=
926         base::i18n::GetStringDirection(suggested_text_view_->text()))
927       text_direction = base::i18n::UNKNOWN_DIRECTION;
928
929     // TODO(sky): need to layout when the user changes caret position.
930     gfx::Size suggested_text_size(suggested_text_view_->GetPreferredSize());
931     if (suggested_text_size.width() > available_width ||
932         text_direction == base::i18n::UNKNOWN_DIRECTION) {
933       // Hide the suggested text if the user has scrolled or we can't fit all
934       // the suggested text, or we have a mix of RTL and LTR characters.
935       suggested_text_view_->SetBounds(0, 0, 0, 0);
936     } else {
937       location_needed_width =
938           std::min(location_needed_width,
939                    location_bounds.width() - suggested_text_size.width());
940       gfx::Rect suggested_text_bounds(location_bounds.x(), location_bounds.y(),
941                                       suggested_text_size.width(),
942                                       location_bounds.height());
943       // TODO(sky): figure out why this needs the -1.
944       suggested_text_bounds.Offset(location_needed_width - 1, 0);
945
946       // We reverse the order of the location entry and suggested text if:
947       // - Chrome is RTL but the text is fully LTR, or
948       // - Chrome is LTR but the text is fully RTL.
949       // This ensures the suggested text is correctly displayed to the right
950       // (or left) of the user text.
951       if (text_direction == (base::i18n::IsRTL() ?
952           base::i18n::LEFT_TO_RIGHT : base::i18n::RIGHT_TO_LEFT)) {
953         // TODO(sky): Figure out why we need the +1.
954         suggested_text_bounds.set_x(location_bounds.x() + 1);
955         // Use a margin to prevent omnibox text from overlapping suggest text.
956         omnibox_view_margin = suggested_text_bounds.width();
957       }
958       suggested_text_view_->SetBoundsRect(suggested_text_bounds);
959     }
960   }
961
962   const gfx::Insets insets = omnibox_view_->GetInsets();
963   omnibox_view_->SetBorder(views::Border::CreateEmptyBorder(
964       insets.top(), insets.left(), insets.bottom(), omnibox_view_margin));
965
966   // Layout |ime_inline_autocomplete_view_| next to the user input.
967   if (ime_inline_autocomplete_view_->visible()) {
968     int width =
969         gfx::GetStringWidth(ime_inline_autocomplete_view_->text(),
970                             ime_inline_autocomplete_view_->font_list()) +
971         ime_inline_autocomplete_view_->GetInsets().width();
972     // All the target languages (IMEs) are LTR, and we do not need to support
973     // RTL so far.  In other words, no testable RTL environment so far.
974     int x = location_needed_width;
975     if (width > entry_width)
976       x = 0;
977     else if (location_needed_width + width > entry_width)
978       x = entry_width - width;
979     location_bounds.set_width(x);
980     ime_inline_autocomplete_view_->SetBounds(
981         location_bounds.right(), location_bounds.y(),
982         std::min(width, entry_width), location_bounds.height());
983   }
984
985   omnibox_view_->SetBoundsRect(location_bounds);
986
987   search_button_->SetBoundsRect(gfx::Rect(
988       gfx::Point(width() - search_button_reserved_width, 0),
989       search_button_size));
990 }
991
992 ////////////////////////////////////////////////////////////////////////////////
993 // LocationBarView, public OmniboxEditController implementation:
994
995 void LocationBarView::Update(const WebContents* contents) {
996   mic_search_view_->SetVisible(
997       !GetToolbarModel()->input_in_progress() && browser_ &&
998       browser_->search_model()->voice_search_supported());
999   RefreshContentSettingViews();
1000   generated_credit_card_view_->Update();
1001   ZoomBubbleView::CloseBubble();
1002   RefreshZoomView();
1003   RefreshPageActionViews();
1004   RefreshTranslateIcon();
1005   RefreshManagePasswordsIconView();
1006   open_pdf_in_reader_view_->Update(
1007       GetToolbarModel()->input_in_progress() ? NULL : GetWebContents());
1008
1009   if (star_view_) {
1010     star_view_->SetVisible(
1011         browser_defaults::bookmarks_enabled && !is_popup_mode_ &&
1012         !GetToolbarModel()->input_in_progress() &&
1013         edit_bookmarks_enabled_.GetValue() &&
1014         !IsBookmarkStarHiddenByExtension());
1015   }
1016
1017   if (contents)
1018     omnibox_view_->OnTabChanged(contents);
1019   else
1020     omnibox_view_->Update();
1021
1022   OnChanged();  // NOTE: Calls Layout().
1023 }
1024
1025 void LocationBarView::ShowURL() {
1026   if (chrome::ShouldDisplayOriginChipV2()) {
1027     omnibox_view_->SetVisible(false);
1028     omnibox_view_->ShowURL();
1029     show_url_animation_->Show();
1030   } else {
1031     omnibox_view_->ShowURL();
1032   }
1033 }
1034
1035 ToolbarModel* LocationBarView::GetToolbarModel() {
1036   return delegate_->GetToolbarModel();
1037 }
1038
1039 WebContents* LocationBarView::GetWebContents() {
1040   return delegate_->GetWebContents();
1041 }
1042
1043 ////////////////////////////////////////////////////////////////////////////////
1044 // LocationBarView, private:
1045
1046 int LocationBarView::GetHorizontalEdgeThickness() const {
1047   // In maximized popup mode, there isn't any edge.
1048   return (is_popup_mode_ && browser_ && browser_->window() &&
1049       browser_->window()->IsMaximized()) ? 0 : vertical_edge_thickness();
1050 }
1051
1052 bool LocationBarView::RefreshContentSettingViews() {
1053   bool visibility_changed = false;
1054   for (ContentSettingViews::const_iterator i(content_setting_views_.begin());
1055        i != content_setting_views_.end(); ++i) {
1056     const bool was_visible = (*i)->visible();
1057     (*i)->Update(GetToolbarModel()->input_in_progress() ?
1058         NULL : GetWebContents());
1059     if (was_visible != (*i)->visible())
1060       visibility_changed = true;
1061   }
1062   return visibility_changed;
1063 }
1064
1065 void LocationBarView::DeletePageActionViews() {
1066   for (PageActionViews::const_iterator i(page_action_views_.begin());
1067        i != page_action_views_.end(); ++i)
1068     RemoveChildView(*i);
1069   STLDeleteElements(&page_action_views_);
1070 }
1071
1072 bool LocationBarView::RefreshPageActionViews() {
1073   if (is_popup_mode_)
1074     return false;
1075
1076   bool changed = false;
1077
1078   // Remember the previous visibility of the page actions so that we can
1079   // notify when this changes.
1080   std::map<ExtensionAction*, bool> old_visibility;
1081   for (PageActionViews::const_iterator i(page_action_views_.begin());
1082        i != page_action_views_.end(); ++i) {
1083     old_visibility[(*i)->image_view()->page_action()] = (*i)->visible();
1084   }
1085
1086   PageActions new_page_actions;
1087
1088   WebContents* web_contents = GetWebContents();
1089   if (web_contents) {
1090     extensions::TabHelper* extensions_tab_helper =
1091         extensions::TabHelper::FromWebContents(web_contents);
1092     extensions::LocationBarController* controller =
1093         extensions_tab_helper->location_bar_controller();
1094     new_page_actions = controller->GetCurrentActions();
1095   }
1096
1097   // On startup we sometimes haven't loaded any extensions. This makes sure
1098   // we catch up when the extensions (and any page actions) load.
1099   if (page_actions_ != new_page_actions) {
1100     changed = true;
1101
1102     page_actions_.swap(new_page_actions);
1103     DeletePageActionViews();  // Delete the old views (if any).
1104
1105     // Create the page action views.
1106     for (PageActions::const_iterator i = page_actions_.begin();
1107          i != page_actions_.end(); ++i) {
1108       PageActionWithBadgeView* page_action_view = new PageActionWithBadgeView(
1109           delegate_->CreatePageActionImageView(this, *i));
1110       page_action_view->SetVisible(false);
1111       page_action_views_.push_back(page_action_view);
1112     }
1113
1114     // Move rightmost extensions to the start.
1115     std::stable_partition(
1116         page_action_views_.begin(),
1117         page_action_views_.end(),
1118         IsPageActionViewRightAligned(
1119             extensions::ExtensionSystem::Get(profile())->extension_service()));
1120
1121     View* right_anchor = open_pdf_in_reader_view_;
1122     if (!right_anchor)
1123       right_anchor = star_view_;
1124     DCHECK(right_anchor);
1125
1126     // |page_action_views_| are ordered right-to-left.  Add them as children in
1127     // reverse order so the logical order and visual order match for
1128     // accessibility purposes.
1129     for (PageActionViews::reverse_iterator i = page_action_views_.rbegin();
1130          i != page_action_views_.rend(); ++i)
1131       AddChildViewAt(*i, GetIndexOf(right_anchor));
1132   }
1133
1134   if (!page_action_views_.empty() && web_contents) {
1135     Browser* browser = chrome::FindBrowserWithWebContents(web_contents);
1136     GURL url = browser->tab_strip_model()->GetActiveWebContents()->GetURL();
1137
1138     for (PageActionViews::const_iterator i(page_action_views_.begin());
1139          i != page_action_views_.end(); ++i) {
1140       (*i)->UpdateVisibility(
1141           GetToolbarModel()->input_in_progress() ? NULL : web_contents, url);
1142
1143       // Check if the visibility of the action changed and notify if it did.
1144       ExtensionAction* action = (*i)->image_view()->page_action();
1145       if (old_visibility.find(action) == old_visibility.end() ||
1146           old_visibility[action] != (*i)->visible()) {
1147         changed = true;
1148         content::NotificationService::current()->Notify(
1149             chrome::NOTIFICATION_EXTENSION_PAGE_ACTION_VISIBILITY_CHANGED,
1150             content::Source<ExtensionAction>(action),
1151             content::Details<WebContents>(web_contents));
1152       }
1153     }
1154   }
1155   return changed;
1156 }
1157
1158 bool LocationBarView::RefreshZoomView() {
1159   DCHECK(zoom_view_);
1160   WebContents* web_contents = GetWebContents();
1161   if (!web_contents)
1162     return false;
1163   const bool was_visible = zoom_view_->visible();
1164   zoom_view_->Update(ZoomController::FromWebContents(web_contents));
1165   return was_visible != zoom_view_->visible();
1166 }
1167
1168 void LocationBarView::RefreshTranslateIcon() {
1169   if (!TranslateService::IsTranslateBubbleEnabled())
1170     return;
1171
1172   WebContents* web_contents = GetWebContents();
1173   if (!web_contents)
1174     return;
1175   LanguageState& language_state = TranslateTabHelper::FromWebContents(
1176       web_contents)->GetLanguageState();
1177   bool enabled = language_state.translate_enabled();
1178   command_updater()->UpdateCommandEnabled(IDC_TRANSLATE_PAGE, enabled);
1179   translate_icon_view_->SetVisible(enabled);
1180   translate_icon_view_->SetToggled(language_state.IsPageTranslated());
1181 }
1182
1183 bool LocationBarView::RefreshManagePasswordsIconView() {
1184   DCHECK(manage_passwords_icon_view_);
1185   WebContents* web_contents = GetWebContents();
1186   if (!web_contents)
1187     return false;
1188   const bool was_visible = manage_passwords_icon_view_->visible();
1189   ManagePasswordsUIController::FromWebContents(
1190       web_contents)->UpdateIconAndBubbleState(manage_passwords_icon_view_);
1191   return was_visible != manage_passwords_icon_view_->visible();
1192 }
1193
1194 void LocationBarView::ShowFirstRunBubbleInternal() {
1195 #if !defined(OS_CHROMEOS)
1196   // First run bubble doesn't make sense for Chrome OS.
1197   Browser* browser = GetBrowserFromDelegate(delegate_);
1198   if (!browser)
1199     return; // Possible when browser is shutting down.
1200
1201   FirstRunBubble::ShowBubble(browser, GetLocationBarAnchor());
1202 #endif
1203 }
1204
1205 void LocationBarView::AccessibilitySetValue(const base::string16& new_value) {
1206   omnibox_view_->SetUserText(new_value, new_value, true);
1207 }
1208
1209 bool LocationBarView::HasValidSuggestText() const {
1210   return suggested_text_view_->visible() &&
1211       !suggested_text_view_->size().IsEmpty();
1212 }
1213
1214 void LocationBarView::OnShowURLAnimationEnded() {
1215   animated_host_label_->SetVisible(false);
1216   omnibox_view_->SetVisible(true);
1217   omnibox_view_->FadeIn();
1218   omnibox_view_->SetFocus();
1219
1220   // Sometimes the selection established by OmniboxView::ShowURL() is lost at
1221   // the call to SetFocus() above.  Select all again to be sure.
1222   // TODO(jdonnelly): Figure out why the selection is sometimes lost and
1223   // implement a more principled fix.
1224   omnibox_view_->SelectAll(true);
1225 }
1226
1227 void LocationBarView::OnHideURLAnimationEnded() {
1228   animated_host_label_->SetVisible(false);
1229   omnibox_view_->HideURL();
1230   omnibox_view_->SetVisible(true);
1231   origin_chip_view_->FadeIn();
1232 }
1233
1234 ////////////////////////////////////////////////////////////////////////////////
1235 // LocationBarView, private LocationBar implementation:
1236
1237 void LocationBarView::ShowFirstRunBubble() {
1238   // Wait until search engines have loaded to show the first run bubble.
1239   TemplateURLService* url_service =
1240       TemplateURLServiceFactory::GetForProfile(profile());
1241   if (!url_service->loaded()) {
1242     template_url_service_ = url_service;
1243     template_url_service_->AddObserver(this);
1244     template_url_service_->Load();
1245     return;
1246   }
1247   ShowFirstRunBubbleInternal();
1248 }
1249
1250 GURL LocationBarView::GetDestinationURL() const {
1251   return destination_url();
1252 }
1253
1254 WindowOpenDisposition LocationBarView::GetWindowOpenDisposition() const {
1255   return disposition();
1256 }
1257
1258 content::PageTransition LocationBarView::GetPageTransition() const {
1259   return transition();
1260 }
1261
1262 void LocationBarView::AcceptInput() {
1263   omnibox_view_->model()->AcceptInput(CURRENT_TAB, false);
1264 }
1265
1266 void LocationBarView::FocusSearch() {
1267   omnibox_view_->SetFocus();
1268   omnibox_view_->SetForcedQuery();
1269 }
1270
1271 void LocationBarView::UpdateContentSettingsIcons() {
1272   if (RefreshContentSettingViews()) {
1273     Layout();
1274     SchedulePaint();
1275   }
1276 }
1277
1278 void LocationBarView::UpdateManagePasswordsIconAndBubble() {
1279   if (RefreshManagePasswordsIconView()) {
1280     Layout();
1281     SchedulePaint();
1282   }
1283 }
1284
1285 void LocationBarView::UpdatePageActions() {
1286   size_t count_before = page_action_views_.size();
1287   bool changed = RefreshPageActionViews();
1288   if (page_action_views_.size() != count_before) {
1289     content::NotificationService::current()->Notify(
1290         chrome::NOTIFICATION_EXTENSION_PAGE_ACTION_COUNT_CHANGED,
1291         content::Source<LocationBar>(this),
1292         content::NotificationService::NoDetails());
1293   }
1294
1295   if (changed) {
1296     Layout();
1297     SchedulePaint();
1298   }
1299 }
1300
1301 void LocationBarView::InvalidatePageActions() {
1302   size_t count_before = page_action_views_.size();
1303   DeletePageActionViews();
1304   if (page_action_views_.size() != count_before) {
1305     content::NotificationService::current()->Notify(
1306         chrome::NOTIFICATION_EXTENSION_PAGE_ACTION_COUNT_CHANGED,
1307         content::Source<LocationBar>(this),
1308         content::NotificationService::NoDetails());
1309   }
1310 }
1311
1312 void LocationBarView::UpdateOpenPDFInReaderPrompt() {
1313   open_pdf_in_reader_view_->Update(
1314       GetToolbarModel()->input_in_progress() ? NULL : GetWebContents());
1315   Layout();
1316   SchedulePaint();
1317 }
1318
1319 void LocationBarView::UpdateGeneratedCreditCardView() {
1320   generated_credit_card_view_->Update();
1321   Layout();
1322   SchedulePaint();
1323 }
1324
1325 void LocationBarView::SaveStateToContents(WebContents* contents) {
1326   omnibox_view_->SaveStateToTab(contents);
1327 }
1328
1329 const OmniboxView* LocationBarView::GetOmniboxView() const {
1330   return omnibox_view_;
1331 }
1332
1333 LocationBarTesting* LocationBarView::GetLocationBarForTesting() {
1334   return this;
1335 }
1336
1337 ////////////////////////////////////////////////////////////////////////////////
1338 // LocationBarView, private LocationBarTesting implementation:
1339
1340 int LocationBarView::PageActionCount() {
1341   return page_action_views_.size();
1342 }
1343
1344 int LocationBarView::PageActionVisibleCount() {
1345   int result = 0;
1346   for (size_t i = 0; i < page_action_views_.size(); i++) {
1347     if (page_action_views_[i]->visible())
1348       ++result;
1349   }
1350   return result;
1351 }
1352
1353 ExtensionAction* LocationBarView::GetPageAction(size_t index) {
1354   if (index < page_action_views_.size())
1355     return page_action_views_[index]->image_view()->page_action();
1356
1357   NOTREACHED();
1358   return NULL;
1359 }
1360
1361 ExtensionAction* LocationBarView::GetVisiblePageAction(size_t index) {
1362   size_t current = 0;
1363   for (size_t i = 0; i < page_action_views_.size(); ++i) {
1364     if (page_action_views_[i]->visible()) {
1365       if (current == index)
1366         return page_action_views_[i]->image_view()->page_action();
1367
1368       ++current;
1369     }
1370   }
1371
1372   NOTREACHED();
1373   return NULL;
1374 }
1375
1376 void LocationBarView::TestPageActionPressed(size_t index) {
1377   size_t current = 0;
1378   for (size_t i = 0; i < page_action_views_.size(); ++i) {
1379     if (page_action_views_[i]->visible()) {
1380       if (current == index) {
1381         page_action_views_[i]->image_view()->ExecuteAction(
1382             ExtensionPopup::SHOW);
1383         return;
1384       }
1385       ++current;
1386     }
1387   }
1388
1389   NOTREACHED();
1390 }
1391
1392 bool LocationBarView::GetBookmarkStarVisibility() {
1393   DCHECK(star_view_);
1394   return star_view_->visible();
1395 }
1396
1397 ////////////////////////////////////////////////////////////////////////////////
1398 // LocationBarView, private views::View implementation:
1399
1400 const char* LocationBarView::GetClassName() const {
1401   return kViewClassName;
1402 }
1403
1404 void LocationBarView::OnBoundsChanged(const gfx::Rect& previous_bounds) {
1405   InstantServiceFactory::GetForProfile(profile())->OnOmniboxStartMarginChanged(
1406       bounds().x());
1407
1408   OmniboxPopupView* popup = omnibox_view_->model()->popup_model()->view();
1409   if (popup->IsOpen())
1410     popup->UpdatePopupAppearance();
1411 }
1412
1413 void LocationBarView::OnPaint(gfx::Canvas* canvas) {
1414   View::OnPaint(canvas);
1415
1416   // Fill the location bar background color behind the border.  Parts of the
1417   // border images are meant to rest atop the toolbar background and parts atop
1418   // the omnibox background, so we can't just blindly fill our entire bounds.
1419   gfx::Rect bounds(GetContentsBounds());
1420   bounds.Inset(GetHorizontalEdgeThickness(), vertical_edge_thickness());
1421   SkColor color(GetColor(ToolbarModel::NONE, BACKGROUND));
1422   if (is_popup_mode_) {
1423     canvas->FillRect(bounds, color);
1424   } else {
1425     SkPaint paint;
1426     paint.setStyle(SkPaint::kFill_Style);
1427     paint.setColor(color);
1428     const int kBorderCornerRadius = 2;
1429     canvas->DrawRoundRect(bounds, kBorderCornerRadius, paint);
1430   }
1431
1432   // The border itself will be drawn in PaintChildren() since it includes an
1433   // inner shadow which should be drawn over the contents.
1434 }
1435
1436 void LocationBarView::PaintChildren(gfx::Canvas* canvas) {
1437   // Paint all the children except for the origin chip and the search button,
1438   // which will be painted after the border.
1439   for (int i = 0, count = child_count(); i < count; ++i) {
1440     if (!child_at(i)->layer() &&
1441         (child_at(i) != origin_chip_view_) &&
1442         (child_at(i) != search_button_))
1443       child_at(i)->Paint(canvas);
1444   }
1445
1446   // For non-InstantExtendedAPI cases, if necessary, show focus rect. As we need
1447   // the focus rect to appear on top of children we paint here rather than
1448   // OnPaint().
1449   // Note: |Canvas::DrawFocusRect| paints a dashed rect with gray color.
1450   if (show_focus_rect_ && HasFocus())
1451     canvas->DrawFocusRect(omnibox_view_->bounds());
1452
1453   // Maximized popup windows don't draw the horizontal edges.  We implement this
1454   // by simply expanding the paint area outside the view by the edge thickness.
1455   gfx::Rect border_rect(GetContentsBounds());
1456   if (is_popup_mode_ && (GetHorizontalEdgeThickness() == 0))
1457     border_rect.Inset(-kPopupEdgeThickness, 0);
1458   views::Painter::PaintPainterAt(canvas, border_painter_.get(), border_rect);
1459
1460   // The origin chip and the search button must be painted after the border so
1461   // that the border shadow is not drawn over them.
1462   origin_chip_view_->Paint(canvas);
1463   search_button_->Paint(canvas);
1464 }
1465
1466 ////////////////////////////////////////////////////////////////////////////////
1467 // LocationBarView, private views::ButtonListener implementation:
1468
1469 void LocationBarView::ButtonPressed(views::Button* sender,
1470                                     const ui::Event& event) {
1471   if (sender == mic_search_view_) {
1472     command_updater()->ExecuteCommand(IDC_TOGGLE_SPEECH_INPUT);
1473     return;
1474   }
1475
1476   DCHECK_EQ(search_button_, sender);
1477   // TODO(pkasting): When macourteau adds UMA stats for this, wire them up here.
1478   omnibox_view_->model()->AcceptInput(
1479       ui::DispositionFromEventFlags(event.flags()), false);
1480 }
1481
1482 ////////////////////////////////////////////////////////////////////////////////
1483 // LocationBarView, private views::DragController implementation:
1484
1485 void LocationBarView::WriteDragDataForView(views::View* sender,
1486                                            const gfx::Point& press_pt,
1487                                            OSExchangeData* data) {
1488   DCHECK_NE(GetDragOperationsForView(sender, press_pt),
1489             ui::DragDropTypes::DRAG_NONE);
1490
1491   WebContents* web_contents = GetWebContents();
1492   FaviconTabHelper* favicon_tab_helper =
1493       FaviconTabHelper::FromWebContents(web_contents);
1494   gfx::ImageSkia favicon = favicon_tab_helper->GetFavicon().AsImageSkia();
1495   button_drag_utils::SetURLAndDragImage(web_contents->GetURL(),
1496                                         web_contents->GetTitle(),
1497                                         favicon,
1498                                         data,
1499                                         sender->GetWidget());
1500 }
1501
1502 int LocationBarView::GetDragOperationsForView(views::View* sender,
1503                                               const gfx::Point& p) {
1504   DCHECK((sender == location_icon_view_) || (sender == ev_bubble_view_) ||
1505          (sender == origin_chip_view_));
1506   WebContents* web_contents = delegate_->GetWebContents();
1507   return (web_contents && web_contents->GetURL().is_valid() &&
1508           (!GetOmniboxView()->IsEditingOrEmpty() ||
1509            sender == origin_chip_view_)) ?
1510       (ui::DragDropTypes::DRAG_COPY | ui::DragDropTypes::DRAG_LINK) :
1511       ui::DragDropTypes::DRAG_NONE;
1512 }
1513
1514 bool LocationBarView::CanStartDragForView(View* sender,
1515                                           const gfx::Point& press_pt,
1516                                           const gfx::Point& p) {
1517   return true;
1518 }
1519
1520 ////////////////////////////////////////////////////////////////////////////////
1521 // LocationBarView, private OmniboxEditController implementation:
1522
1523 void LocationBarView::OnChanged() {
1524   int icon_id = omnibox_view_->GetIcon();
1525   location_icon_view_->SetImage(GetThemeProvider()->GetImageSkiaNamed(icon_id));
1526   location_icon_view_->ShowTooltip(!GetOmniboxView()->IsEditingOrEmpty());
1527
1528   ToolbarModel* toolbar_model = GetToolbarModel();
1529   chrome::DisplaySearchButtonConditions conditions =
1530       chrome::GetDisplaySearchButtonConditions();
1531   bool meets_conditions =
1532       (conditions == chrome::DISPLAY_SEARCH_BUTTON_ALWAYS) ||
1533       ((conditions != chrome::DISPLAY_SEARCH_BUTTON_NEVER) &&
1534        (toolbar_model->WouldPerformSearchTermReplacement(true) ||
1535         ((conditions == chrome::DISPLAY_SEARCH_BUTTON_FOR_STR_OR_IIP) &&
1536          toolbar_model->input_in_progress())));
1537   search_button_->SetVisible(!is_popup_mode_ && meets_conditions);
1538   search_button_->SetImage(
1539       views::Button::STATE_NORMAL,
1540       *GetThemeProvider()->GetImageSkiaNamed((icon_id == IDR_OMNIBOX_SEARCH) ?
1541           IDR_OMNIBOX_SEARCH_BUTTON_LOUPE : IDR_OMNIBOX_SEARCH_BUTTON_ARROW));
1542
1543   if (toolbar_origin_chip_view_)
1544     toolbar_origin_chip_view_->OnChanged();
1545
1546   if (origin_chip_view_->visible())
1547     origin_chip_view_->OnChanged();
1548
1549   Layout();
1550   SchedulePaint();
1551 }
1552
1553 void LocationBarView::OnSetFocus() {
1554   GetFocusManager()->SetFocusedView(this);
1555 }
1556
1557 InstantController* LocationBarView::GetInstant() {
1558   return delegate_->GetInstant();
1559 }
1560
1561 const ToolbarModel* LocationBarView::GetToolbarModel() const {
1562   return delegate_->GetToolbarModel();
1563 }
1564
1565 void LocationBarView::HideURL() {
1566   omnibox_view_->SetVisible(false);
1567   hide_url_animation_->Show();
1568 }
1569
1570 ////////////////////////////////////////////////////////////////////////////////
1571 // LocationBarView, private DropdownBarHostDelegate implementation:
1572
1573 void LocationBarView::SetFocusAndSelection(bool select_all) {
1574   FocusLocation(select_all);
1575 }
1576
1577 void LocationBarView::SetAnimationOffset(int offset) {
1578   dropdown_animation_offset_ = offset;
1579 }
1580
1581 ////////////////////////////////////////////////////////////////////////////////
1582 // LocationBarView, private gfx::AnimationDelegate implementation:
1583
1584 void LocationBarView::AnimationProgressed(const gfx::Animation* animation) {
1585   if (animation == show_url_animation_.get() ||
1586       animation == hide_url_animation_.get()) {
1587     Layout();
1588     SchedulePaint();
1589   }
1590 }
1591
1592 void LocationBarView::AnimationEnded(const gfx::Animation* animation) {
1593   if (animation == show_url_animation_.get()) {
1594     show_url_animation_->Reset();
1595     OnShowURLAnimationEnded();
1596   } else if (animation == hide_url_animation_.get()) {
1597     hide_url_animation_->Reset();
1598     OnHideURLAnimationEnded();
1599   }
1600 }
1601
1602 ////////////////////////////////////////////////////////////////////////////////
1603 // LocationBarView, private TemplateURLServiceObserver implementation:
1604
1605 void LocationBarView::OnTemplateURLServiceChanged() {
1606   template_url_service_->RemoveObserver(this);
1607   template_url_service_ = NULL;
1608   // If the browser is no longer active, let's not show the info bubble, as this
1609   // would make the browser the active window again.
1610   if (omnibox_view_ && omnibox_view_->GetWidget()->IsActive())
1611     ShowFirstRunBubble();
1612 }
1613
1614 ////////////////////////////////////////////////////////////////////////////////
1615 // LocationBarView, private content::NotificationObserver implementation:
1616
1617 void LocationBarView::Observe(int type,
1618                               const content::NotificationSource& source,
1619                               const content::NotificationDetails& details) {
1620   switch (type) {
1621     case chrome::NOTIFICATION_EXTENSION_LOCATION_BAR_UPDATED: {
1622       // Only update if the updated action box was for the active tab contents.
1623       if (content::Details<WebContents>(details).ptr() == GetWebContents())
1624         UpdatePageActions();
1625       break;
1626     }
1627
1628     case chrome::NOTIFICATION_EXTENSION_LOADED_DEPRECATED:
1629     case chrome::NOTIFICATION_EXTENSION_UNLOADED_DEPRECATED:
1630       Update(NULL);
1631       break;
1632
1633     default:
1634       NOTREACHED() << "Unexpected notification.";
1635   }
1636 }
1637
1638 ////////////////////////////////////////////////////////////////////////////////
1639 // LocationBarView, private SearchModelObserver implementation:
1640
1641 void LocationBarView::ModelChanged(const SearchModel::State& old_state,
1642                                    const SearchModel::State& new_state) {
1643   const bool visible = !GetToolbarModel()->input_in_progress() &&
1644       new_state.voice_search_supported;
1645   if (mic_search_view_->visible() != visible) {
1646     mic_search_view_->SetVisible(visible);
1647     Layout();
1648   }
1649 }
1650