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