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