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