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