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