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