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