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