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