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.
5 #include "chrome/browser/ui/views/location_bar/location_bar_view.h"
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/extension_action.h"
21 #include "chrome/browser/extensions/location_bar_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/instant_service.h"
26 #include "chrome/browser/search/instant_service_factory.h"
27 #include "chrome/browser/search/search.h"
28 #include "chrome/browser/search_engines/template_url_service_factory.h"
29 #include "chrome/browser/translate/chrome_translate_client.h"
30 #include "chrome/browser/translate/translate_service.h"
31 #include "chrome/browser/ui/browser.h"
32 #include "chrome/browser/ui/browser_finder.h"
33 #include "chrome/browser/ui/browser_instant_controller.h"
34 #include "chrome/browser/ui/browser_window.h"
35 #include "chrome/browser/ui/omnibox/omnibox_popup_model.h"
36 #include "chrome/browser/ui/omnibox/omnibox_popup_view.h"
37 #include "chrome/browser/ui/passwords/manage_passwords_icon.h"
38 #include "chrome/browser/ui/passwords/manage_passwords_ui_controller.h"
39 #include "chrome/browser/ui/tabs/tab_strip_model.h"
40 #include "chrome/browser/ui/view_ids.h"
41 #include "chrome/browser/ui/views/browser_dialogs.h"
42 #include "chrome/browser/ui/views/location_bar/add_to_app_launcher_view.h"
43 #include "chrome/browser/ui/views/location_bar/content_setting_image_view.h"
44 #include "chrome/browser/ui/views/location_bar/ev_bubble_view.h"
45 #include "chrome/browser/ui/views/location_bar/generated_credit_card_view.h"
46 #include "chrome/browser/ui/views/location_bar/keyword_hint_view.h"
47 #include "chrome/browser/ui/views/location_bar/location_bar_layout.h"
48 #include "chrome/browser/ui/views/location_bar/location_icon_view.h"
49 #include "chrome/browser/ui/views/location_bar/open_pdf_in_reader_view.h"
50 #include "chrome/browser/ui/views/location_bar/origin_chip_view.h"
51 #include "chrome/browser/ui/views/location_bar/page_action_image_view.h"
52 #include "chrome/browser/ui/views/location_bar/page_action_with_badge_view.h"
53 #include "chrome/browser/ui/views/location_bar/search_button.h"
54 #include "chrome/browser/ui/views/location_bar/selected_keyword_view.h"
55 #include "chrome/browser/ui/views/location_bar/star_view.h"
56 #include "chrome/browser/ui/views/location_bar/translate_icon_view.h"
57 #include "chrome/browser/ui/views/location_bar/zoom_bubble_view.h"
58 #include "chrome/browser/ui/views/location_bar/zoom_view.h"
59 #include "chrome/browser/ui/views/passwords/manage_passwords_bubble_view.h"
60 #include "chrome/browser/ui/views/passwords/manage_passwords_icon_view.h"
61 #include "chrome/browser/ui/views/translate/translate_bubble_view.h"
62 #include "chrome/browser/ui/zoom/zoom_controller.h"
63 #include "chrome/common/chrome_switches.h"
64 #include "chrome/common/pref_names.h"
65 #include "components/search_engines/template_url.h"
66 #include "components/search_engines/template_url_service.h"
67 #include "components/translate/core/browser/language_state.h"
68 #include "content/public/browser/notification_service.h"
69 #include "content/public/browser/render_widget_host_view.h"
70 #include "content/public/browser/web_contents.h"
71 #include "extensions/browser/extension_registry.h"
72 #include "extensions/common/feature_switch.h"
73 #include "extensions/common/permissions/permissions_data.h"
74 #include "grit/component_scaled_resources.h"
75 #include "grit/generated_resources.h"
76 #include "grit/theme_resources.h"
77 #include "ui/accessibility/ax_view_state.h"
78 #include "ui/base/dragdrop/drag_drop_types.h"
79 #include "ui/base/l10n/l10n_util.h"
80 #include "ui/base/resource/resource_bundle.h"
81 #include "ui/base/theme_provider.h"
82 #include "ui/events/event.h"
83 #include "ui/gfx/animation/slide_animation.h"
84 #include "ui/gfx/canvas.h"
85 #include "ui/gfx/color_utils.h"
86 #include "ui/gfx/image/image.h"
87 #include "ui/gfx/image/image_skia_operations.h"
88 #include "ui/gfx/scoped_canvas.h"
89 #include "ui/gfx/skia_util.h"
90 #include "ui/gfx/text_utils.h"
91 #include "ui/native_theme/native_theme.h"
92 #include "ui/views/background.h"
93 #include "ui/views/border.h"
94 #include "ui/views/button_drag_utils.h"
95 #include "ui/views/controls/button/image_button.h"
96 #include "ui/views/controls/label.h"
97 #include "ui/views/widget/widget.h"
99 #if !defined(OS_CHROMEOS)
100 #include "chrome/browser/ui/views/first_run_bubble.h"
103 using content::WebContents;
108 const gfx::Tween::Type kShowTweenType = gfx::Tween::LINEAR_OUT_SLOW_IN;
109 const gfx::Tween::Type kHideTweenType = gfx::Tween::FAST_OUT_LINEAR_IN;
111 // The search button images are made to look as if they overlay the normal edge
112 // images, but to align things, the search button needs to be inset horizontally
114 const int kSearchButtonInset = 1;
116 // Given a containing |height| and a |base_font_list|, shrinks the font size
117 // until the font list will fit within |height| while having its cap height
118 // vertically centered. Returns the correctly-sized font list.
120 // The expected layout:
121 // +--------+-----------------------------------------------+------------+
122 // | | y offset | space |
123 // | +--------+-------------------+------------------+ above |
124 // | | | | internal leading | cap height |
125 // | box | font | ascent (baseline) +------------------+------------+
126 // | height | height | | cap height |
127 // | | |-------------------+------------------+------------+
128 // | | | descent (height - baseline) | space |
129 // | +--------+--------------------------------------+ below |
130 // | | space at bottom | cap height |
131 // +--------+-----------------------------------------------+------------+
133 // center of box height == center of cap height
134 // (i.e. space above cap height == space below cap height)
137 // space at bottom >= 0
138 // (i.e. Entire font must be visible inside the box.)
139 gfx::FontList GetLargestFontListWithHeightBound(
140 const gfx::FontList& base_font_list,
142 gfx::FontList font_list = base_font_list;
143 for (int font_size = font_list.GetFontSize(); font_size > 1; --font_size) {
144 const int internal_leading =
145 font_list.GetBaseline() - font_list.GetCapHeight();
146 // Some platforms don't support getting the cap height, and simply return
147 // the entire font ascent from GetCapHeight(). Centering the ascent makes
148 // the font look too low, so if GetCapHeight() returns the ascent, center
149 // the entire font height instead.
151 height - ((internal_leading != 0) ?
152 font_list.GetCapHeight() : font_list.GetHeight());
153 const int y_offset = space / 2 - internal_leading;
154 const int space_at_bottom = height - (y_offset + font_list.GetHeight());
155 if ((y_offset >= 0) && (space_at_bottom >= 0))
157 font_list = font_list.DeriveWithSizeDelta(-1);
162 int GetEditLeadingInternalSpace() {
163 // The textfield has 1 px of whitespace before the text in the RTL case only.
164 return base::i18n::IsRTL() ? 1 : 0;
167 // Functor for moving BookmarkManagerPrivate page actions to the right via
169 class IsPageActionViewRightAligned {
171 explicit IsPageActionViewRightAligned(
172 extensions::ExtensionRegistry* extension_registry)
173 : extension_registry_(extension_registry) {}
175 bool operator()(PageActionWithBadgeView* page_action_view) {
176 return extension_registry_->enabled_extensions().GetByID(
177 page_action_view->image_view()->extension_action()->extension_id())->
179 HasAPIPermission(extensions::APIPermission::kBookmarkManagerPrivate);
183 extensions::ExtensionRegistry* extension_registry_;
185 // NOTE: Can't DISALLOW_COPY_AND_ASSIGN as we pass this object by value to
186 // std::stable_partition().
192 // LocationBarView -----------------------------------------------------------
195 const int LocationBarView::kNormalEdgeThickness = 2;
196 const int LocationBarView::kPopupEdgeThickness = 1;
197 const int LocationBarView::kItemPadding = 3;
198 const int LocationBarView::kIconInternalPadding = 2;
199 const int LocationBarView::kBubblePadding = 1;
200 const char LocationBarView::kViewClassName[] = "LocationBarView";
202 LocationBarView::LocationBarView(Browser* browser,
204 CommandUpdater* command_updater,
207 : LocationBar(profile),
208 OmniboxEditController(command_updater),
212 origin_chip_view_(NULL),
213 location_icon_view_(NULL),
214 ev_bubble_view_(NULL),
215 ime_inline_autocomplete_view_(NULL),
216 selected_keyword_view_(NULL),
217 suggested_text_view_(NULL),
218 keyword_hint_view_(NULL),
219 mic_search_view_(NULL),
221 generated_credit_card_view_(NULL),
222 open_pdf_in_reader_view_(NULL),
223 manage_passwords_icon_view_(NULL),
224 translate_icon_view_(NULL),
225 add_to_app_launcher_view_(NULL),
227 search_button_(NULL),
228 is_popup_mode_(is_popup_mode),
229 show_focus_rect_(false),
230 template_url_service_(NULL),
231 dropdown_animation_offset_(0),
232 starting_omnibox_offset_(0),
233 current_omnibox_offset_(0),
234 starting_omnibox_leading_inset_(0),
235 current_omnibox_leading_inset_(0),
236 current_omnibox_width_(0),
237 ending_omnibox_width_(0) {
238 edit_bookmarks_enabled_.Init(
239 prefs::kEditBookmarksEnabled, profile->GetPrefs(),
240 base::Bind(&LocationBarView::Update, base::Unretained(this),
241 static_cast<content::WebContents*>(NULL)));
244 browser_->search_model()->AddObserver(this);
247 LocationBarView::~LocationBarView() {
248 if (template_url_service_)
249 template_url_service_->RemoveObserver(this);
251 browser_->search_model()->RemoveObserver(this);
254 ////////////////////////////////////////////////////////////////////////////////
255 // LocationBarView, public:
257 void LocationBarView::Init() {
258 // We need to be in a Widget, otherwise GetNativeTheme() may change and we're
259 // not prepared for that.
262 const int kOmniboxPopupBorderImages[] =
263 IMAGE_GRID(IDR_OMNIBOX_POPUP_BORDER_AND_SHADOW);
264 const int kOmniboxBorderImages[] = IMAGE_GRID(IDR_TEXTFIELD);
265 border_painter_.reset(views::Painter::CreateImageGridPainter(
266 is_popup_mode_ ? kOmniboxPopupBorderImages : kOmniboxBorderImages));
268 location_icon_view_ = new LocationIconView(this);
269 location_icon_view_->set_drag_controller(this);
270 AddChildView(location_icon_view_);
272 // Determine the main font.
273 gfx::FontList font_list = ResourceBundle::GetSharedInstance().GetFontList(
274 ResourceBundle::BaseFont);
275 const int current_font_size = font_list.GetFontSize();
276 const int desired_font_size = browser_defaults::kOmniboxFontPixelSize;
277 if (current_font_size != desired_font_size) {
279 font_list.DeriveWithSizeDelta(desired_font_size - current_font_size);
281 // Shrink large fonts to make them fit.
282 // TODO(pkasting): Stretch the location bar instead in this case.
283 const int location_height = GetInternalHeight(true);
284 font_list = GetLargestFontListWithHeightBound(font_list, location_height);
286 // Determine the font for use inside the bubbles. The bubble background
287 // images have 1 px thick edges, which we don't want to overlap.
288 const int kBubbleInteriorVerticalPadding = 1;
289 const int bubble_vertical_padding =
290 (kBubblePadding + kBubbleInteriorVerticalPadding) * 2;
291 const gfx::FontList bubble_font_list(
292 GetLargestFontListWithHeightBound(
293 font_list, location_height - bubble_vertical_padding));
295 const SkColor background_color =
296 GetColor(ToolbarModel::NONE, LocationBarView::BACKGROUND);
297 ev_bubble_view_ = new EVBubbleView(
298 bubble_font_list, GetColor(ToolbarModel::EV_SECURE, SECURITY_TEXT),
299 background_color, this);
300 ev_bubble_view_->set_drag_controller(this);
301 AddChildView(ev_bubble_view_);
303 // Initialize the Omnibox view.
304 omnibox_view_ = new OmniboxViewViews(
305 this, profile(), command_updater(),
307 (browser_->is_app() && CommandLine::ForCurrentProcess()->
308 HasSwitch(switches::kEnableStreamlinedHostedApps)),
310 omnibox_view_->Init();
311 omnibox_view_->SetFocusable(true);
312 AddChildView(omnibox_view_);
314 // Initialize the inline autocomplete view which is visible only when IME is
315 // turned on. Use the same font with the omnibox and highlighted background.
316 ime_inline_autocomplete_view_ = new views::Label(base::string16(), font_list);
317 ime_inline_autocomplete_view_->SetHorizontalAlignment(gfx::ALIGN_LEFT);
318 ime_inline_autocomplete_view_->SetAutoColorReadabilityEnabled(false);
319 ime_inline_autocomplete_view_->set_background(
320 views::Background::CreateSolidBackground(GetNativeTheme()->GetSystemColor(
321 ui::NativeTheme::kColorId_TextfieldSelectionBackgroundFocused)));
322 ime_inline_autocomplete_view_->SetEnabledColor(
323 GetNativeTheme()->GetSystemColor(
324 ui::NativeTheme::kColorId_TextfieldSelectionColor));
325 ime_inline_autocomplete_view_->SetVisible(false);
326 AddChildView(ime_inline_autocomplete_view_);
328 origin_chip_view_ = new OriginChipView(this, profile(), font_list);
329 origin_chip_view_->SetFocusable(false);
330 origin_chip_view_->set_drag_controller(this);
331 AddChildView(origin_chip_view_);
333 const SkColor text_color = GetColor(ToolbarModel::NONE, TEXT);
334 selected_keyword_view_ = new SelectedKeywordView(
335 bubble_font_list, text_color, background_color, profile());
336 AddChildView(selected_keyword_view_);
338 suggested_text_view_ = new views::Label(base::string16(), font_list);
339 suggested_text_view_->SetHorizontalAlignment(gfx::ALIGN_LEFT);
340 suggested_text_view_->SetAutoColorReadabilityEnabled(false);
341 suggested_text_view_->SetEnabledColor(GetColor(
342 ToolbarModel::NONE, LocationBarView::DEEMPHASIZED_TEXT));
343 suggested_text_view_->SetVisible(false);
344 AddChildView(suggested_text_view_);
346 keyword_hint_view_ = new KeywordHintView(
347 profile(), font_list,
348 GetColor(ToolbarModel::NONE, LocationBarView::DEEMPHASIZED_TEXT),
350 AddChildView(keyword_hint_view_);
352 mic_search_view_ = new views::ImageButton(this);
353 mic_search_view_->set_id(VIEW_ID_MIC_SEARCH_BUTTON);
354 mic_search_view_->SetAccessibilityFocusable(true);
355 mic_search_view_->SetTooltipText(
356 l10n_util::GetStringUTF16(IDS_TOOLTIP_MIC_SEARCH));
357 mic_search_view_->SetImage(
358 views::Button::STATE_NORMAL,
359 ui::ResourceBundle::GetSharedInstance().GetImageSkiaNamed(
360 IDR_OMNIBOX_MIC_SEARCH));
361 mic_search_view_->SetImageAlignment(views::ImageButton::ALIGN_CENTER,
362 views::ImageButton::ALIGN_MIDDLE);
363 mic_search_view_->SetVisible(false);
364 AddChildView(mic_search_view_);
366 for (int i = 0; i < CONTENT_SETTINGS_NUM_TYPES; ++i) {
367 ContentSettingImageView* content_blocked_view =
368 new ContentSettingImageView(static_cast<ContentSettingsType>(i), this,
369 bubble_font_list, text_color,
371 content_setting_views_.push_back(content_blocked_view);
372 content_blocked_view->SetVisible(false);
373 AddChildView(content_blocked_view);
376 generated_credit_card_view_ = new GeneratedCreditCardView(delegate_);
377 AddChildView(generated_credit_card_view_);
379 zoom_view_ = new ZoomView(delegate_);
380 zoom_view_->set_id(VIEW_ID_ZOOM_BUTTON);
381 AddChildView(zoom_view_);
383 open_pdf_in_reader_view_ = new OpenPDFInReaderView();
384 AddChildView(open_pdf_in_reader_view_);
386 manage_passwords_icon_view_ = new ManagePasswordsIconView(command_updater());
387 AddChildView(manage_passwords_icon_view_);
389 translate_icon_view_ = new TranslateIconView(command_updater());
390 translate_icon_view_->SetVisible(false);
391 AddChildView(translate_icon_view_);
393 add_to_app_launcher_view_ = new AddToAppLauncherView(
394 this, bubble_font_list, text_color, background_color);
395 add_to_app_launcher_view_->SetVisible(false);
396 AddChildView(add_to_app_launcher_view_);
398 star_view_ = new StarView(command_updater());
399 star_view_->SetVisible(false);
400 AddChildView(star_view_);
402 search_button_ = new SearchButton(this);
403 search_button_->SetVisible(false);
404 AddChildView(search_button_);
406 show_url_animation_.reset(new gfx::SlideAnimation(this));
407 show_url_animation_->SetTweenType(kShowTweenType);
408 show_url_animation_->SetSlideDuration(200);
410 hide_url_animation_.reset(new gfx::SlideAnimation(this));
411 hide_url_animation_->SetTweenType(kHideTweenType);
412 hide_url_animation_->SetSlideDuration(175);
414 content::Source<Profile> profile_source = content::Source<Profile>(profile());
416 extensions::NOTIFICATION_EXTENSION_LOADED_DEPRECATED,
419 extensions::NOTIFICATION_EXTENSION_UNLOADED_DEPRECATED,
422 // Initialize the location entry. We do this to avoid a black flash which is
423 // visible when the location entry has just been initialized.
427 bool LocationBarView::IsInitialized() const {
428 return omnibox_view_ != NULL;
431 SkColor LocationBarView::GetColor(ToolbarModel::SecurityLevel security_level,
432 ColorKind kind) const {
433 const ui::NativeTheme* native_theme = GetNativeTheme();
436 return native_theme->GetSystemColor(
437 ui::NativeTheme::kColorId_TextfieldDefaultBackground);
440 return native_theme->GetSystemColor(
441 ui::NativeTheme::kColorId_TextfieldDefaultColor);
444 return native_theme->GetSystemColor(
445 ui::NativeTheme::kColorId_TextfieldSelectionColor);
447 case DEEMPHASIZED_TEXT:
448 return color_utils::AlphaBlend(
449 GetColor(security_level, TEXT),
450 GetColor(security_level, BACKGROUND),
453 case SECURITY_TEXT: {
455 switch (security_level) {
456 case ToolbarModel::EV_SECURE:
457 case ToolbarModel::SECURE:
458 color = SkColorSetRGB(7, 149, 0);
461 case ToolbarModel::SECURITY_WARNING:
462 case ToolbarModel::SECURITY_POLICY_WARNING:
463 return GetColor(security_level, DEEMPHASIZED_TEXT);
466 case ToolbarModel::SECURITY_ERROR:
467 color = SkColorSetRGB(162, 0, 0);
472 return GetColor(security_level, TEXT);
474 return color_utils::GetReadableColor(
475 color, GetColor(security_level, BACKGROUND));
480 return GetColor(security_level, TEXT);
484 void LocationBarView::ZoomChangedForActiveTab(bool can_show_bubble) {
486 if (RefreshZoomView()) {
491 WebContents* web_contents = GetWebContents();
492 if (can_show_bubble && zoom_view_->visible() && web_contents)
493 ZoomBubbleView::ShowBubble(web_contents, true);
496 void LocationBarView::SetPreviewEnabledPageAction(ExtensionAction* page_action,
497 bool preview_enabled) {
502 WebContents* web_contents = GetWebContents();
504 RefreshPageActionViews();
505 PageActionWithBadgeView* page_action_view =
506 static_cast<PageActionWithBadgeView*>(GetPageActionView(page_action));
507 DCHECK(page_action_view);
508 if (!page_action_view)
511 page_action_view->image_view()->set_preview_enabled(preview_enabled);
512 page_action_view->UpdateVisibility(web_contents);
517 PageActionWithBadgeView* LocationBarView::GetPageActionView(
518 ExtensionAction* page_action) {
520 for (PageActionViews::const_iterator i(page_action_views_.begin());
521 i != page_action_views_.end(); ++i) {
522 if ((*i)->image_view()->extension_action() == page_action)
528 void LocationBarView::SetStarToggled(bool on) {
530 star_view_->SetToggled(on);
533 void LocationBarView::SetTranslateIconToggled(bool on) {
534 translate_icon_view_->SetToggled(on);
537 gfx::Point LocationBarView::GetOmniboxViewOrigin() const {
538 gfx::Point origin(omnibox_view_->bounds().origin());
539 origin.set_x(GetMirroredXInView(origin.x() - current_omnibox_offset_));
540 views::View::ConvertPointToScreen(this, &origin);
544 void LocationBarView::SetImeInlineAutocompletion(const base::string16& text) {
545 ime_inline_autocomplete_view_->SetText(text);
546 ime_inline_autocomplete_view_->SetVisible(!text.empty());
549 void LocationBarView::SetGrayTextAutocompletion(const base::string16& text) {
550 if (suggested_text_view_->text() != text) {
551 suggested_text_view_->SetText(text);
552 suggested_text_view_->SetVisible(!text.empty());
558 base::string16 LocationBarView::GetGrayTextAutocompletion() const {
559 return HasValidSuggestText() ?
560 suggested_text_view_->text() : base::string16();
563 void LocationBarView::SetShowFocusRect(bool show) {
564 show_focus_rect_ = show;
568 void LocationBarView::SelectAll() {
569 omnibox_view_->SelectAll(true);
572 gfx::Point LocationBarView::GetLocationBarAnchorPoint() const {
573 // The +1 in the next line creates a 1-px gap between icon and arrow tip.
574 gfx::Point icon_bottom(0, location_icon_view_->GetImageBounds().bottom() -
575 LocationBarView::kIconInternalPadding + 1);
576 gfx::Point icon_center(location_icon_view_->GetImageBounds().CenterPoint());
577 gfx::Point point(icon_center.x(), icon_bottom.y());
578 ConvertPointToTarget(location_icon_view_, this, &point);
582 views::View* LocationBarView::generated_credit_card_view() {
583 return generated_credit_card_view_;
586 int LocationBarView::GetInternalHeight(bool use_preferred_size) {
588 use_preferred_size ? GetPreferredSize().height() : height();
589 return std::max(total_height - (vertical_edge_thickness() * 2), 0);
592 void LocationBarView::GetOmniboxPopupPositioningInfo(
593 gfx::Point* top_left_screen_coord,
597 // Because the popup might appear atop the attached bookmark bar, there won't
598 // necessarily be a client edge separating it from the rest of the toolbar.
599 // Therefore we position the popup high enough so it can draw its own client
600 // edge at the top, in the same place the toolbar would normally draw the
602 *top_left_screen_coord = gfx::Point(
604 parent()->height() - views::NonClientFrameView::kClientEdgeThickness);
605 views::View::ConvertPointToScreen(parent(), top_left_screen_coord);
606 *popup_width = parent()->width();
608 gfx::Rect location_bar_bounds(bounds());
609 location_bar_bounds.Inset(kNormalEdgeThickness, 0);
610 *left_margin = location_bar_bounds.x();
611 *right_margin = *popup_width - location_bar_bounds.right();
614 ////////////////////////////////////////////////////////////////////////////////
615 // LocationBarView, public LocationBar implementation:
617 void LocationBarView::FocusLocation(bool select_all) {
618 omnibox_view_->SetFocus();
620 omnibox_view_->SelectAll(true);
623 void LocationBarView::Revert() {
624 omnibox_view_->RevertAll();
627 OmniboxView* LocationBarView::GetOmniboxView() {
628 return omnibox_view_;
631 ////////////////////////////////////////////////////////////////////////////////
632 // LocationBarView, public views::View implementation:
634 bool LocationBarView::HasFocus() const {
635 return omnibox_view_->model()->has_focus();
638 void LocationBarView::GetAccessibleState(ui::AXViewState* state) {
639 state->role = ui::AX_ROLE_GROUP;
642 gfx::Size LocationBarView::GetPreferredSize() const {
643 // Compute minimum height.
644 gfx::Size min_size(border_painter_->GetMinimumSize());
645 if (!IsInitialized())
647 gfx::Size search_button_min_size(search_button_->GetMinimumSize());
648 min_size.SetToMax(search_button_min_size);
650 // Compute width of omnibox-leading content.
651 const int horizontal_edge_thickness = GetHorizontalEdgeThickness();
652 int leading_width = horizontal_edge_thickness;
653 // TODO(pkasting): Make the origin chip min width sane, and make the chip
654 // handle being shrunken down more gracefully; then uncomment this.
655 /*if (GetToolbarModel()->ShouldShowOriginChip())
656 leading_width += origin_chip_view_->GetMinimumSize().width();*/
657 if (ShouldShowKeywordBubble()) {
658 // The selected keyword view can collapse completely.
659 } else if (ShouldShowEVBubble()) {
660 leading_width += kBubblePadding +
661 ev_bubble_view_->GetMinimumSizeForLabelText(
662 GetToolbarModel()->GetEVCertName()).width();
663 } else if (!origin_chip_view_->visible()) {
665 kItemPadding + location_icon_view_->GetMinimumSize().width();
667 leading_width += kItemPadding - GetEditLeadingInternalSpace();
669 // Compute width of omnibox-trailing content.
670 int trailing_width = search_button_->visible() ?
671 (search_button_->GetMinimumSize().width() + kSearchButtonInset) :
672 horizontal_edge_thickness;
673 trailing_width += IncrementalMinimumWidth(star_view_) +
674 IncrementalMinimumWidth(translate_icon_view_) +
675 IncrementalMinimumWidth(open_pdf_in_reader_view_) +
676 IncrementalMinimumWidth(manage_passwords_icon_view_) +
677 IncrementalMinimumWidth(zoom_view_) +
678 IncrementalMinimumWidth(generated_credit_card_view_) +
679 IncrementalMinimumWidth(mic_search_view_) +
680 IncrementalMinimumWidth(add_to_app_launcher_view_) + kItemPadding;
681 for (PageActionViews::const_iterator i(page_action_views_.begin());
682 i != page_action_views_.end(); ++i)
683 trailing_width += IncrementalMinimumWidth((*i));
684 for (ContentSettingViews::const_iterator i(content_setting_views_.begin());
685 i != content_setting_views_.end(); ++i)
686 trailing_width += IncrementalMinimumWidth((*i));
689 leading_width + omnibox_view_->GetMinimumSize().width() + trailing_width);
693 void LocationBarView::Layout() {
694 if (!IsInitialized())
697 origin_chip_view_->SetVisible(GetToolbarModel()->ShouldShowOriginChip());
698 selected_keyword_view_->SetVisible(false);
699 location_icon_view_->SetVisible(false);
700 ev_bubble_view_->SetVisible(false);
701 keyword_hint_view_->SetVisible(false);
703 LocationBarLayout leading_decorations(
704 LocationBarLayout::LEFT_EDGE,
705 kItemPadding - GetEditLeadingInternalSpace());
706 LocationBarLayout trailing_decorations(LocationBarLayout::RIGHT_EDGE,
709 const int origin_chip_preferred_width =
710 origin_chip_view_->GetPreferredSize().width();
711 const int origin_chip_width =
712 origin_chip_view_->visible() ? origin_chip_preferred_width : 0;
713 // Always give the origin chip view its desired size and lay it out, even when
714 // it's not visible, so we can calculate the correct animation values below
715 // when switching to tabs that have the origin chip hidden.
716 origin_chip_view_->SetBounds(0, 0, origin_chip_preferred_width, height());
717 origin_chip_view_->Layout();
719 const int bubble_location_y = vertical_edge_thickness() + kBubblePadding;
720 const base::string16 keyword(omnibox_view_->model()->keyword());
721 // In some cases (e.g. fullscreen mode) we may have 0 height. We still want
722 // to position our child views in this case, because other things may be
723 // positioned relative to them (e.g. the "bookmark added" bubble if the user
725 const int location_height = GetInternalHeight(false);
726 const int bubble_height = std::max(location_height - (kBubblePadding * 2), 0);
727 if (ShouldShowKeywordBubble()) {
728 leading_decorations.AddDecoration(bubble_location_y, bubble_height, true, 0,
729 kBubblePadding, kItemPadding,
730 selected_keyword_view_);
731 if (selected_keyword_view_->keyword() != keyword) {
732 selected_keyword_view_->SetKeyword(keyword);
733 const TemplateURL* template_url =
734 TemplateURLServiceFactory::GetForProfile(profile())->
735 GetTemplateURLForKeyword(keyword);
737 (template_url->GetType() == TemplateURL::OMNIBOX_API_EXTENSION)) {
738 gfx::Image image = extensions::OmniboxAPI::Get(profile())->
739 GetOmniboxIcon(template_url->GetExtensionId());
740 selected_keyword_view_->SetImage(image.AsImageSkia());
741 selected_keyword_view_->set_is_extension_icon(true);
743 selected_keyword_view_->SetImage(
744 *(GetThemeProvider()->GetImageSkiaNamed(IDR_OMNIBOX_SEARCH)));
745 selected_keyword_view_->set_is_extension_icon(false);
748 } else if (ShouldShowEVBubble()) {
749 ev_bubble_view_->SetLabel(GetToolbarModel()->GetEVCertName());
750 // The largest fraction of the omnibox that can be taken by the EV bubble.
751 const double kMaxBubbleFraction = 0.5;
752 leading_decorations.AddDecoration(bubble_location_y, bubble_height, false,
753 kMaxBubbleFraction, kBubblePadding,
754 kItemPadding, ev_bubble_view_);
755 } else if (!origin_chip_view_->visible()) {
756 leading_decorations.AddDecoration(
757 vertical_edge_thickness(), location_height,
758 location_icon_view_);
761 if (star_view_->visible()) {
762 trailing_decorations.AddDecoration(
763 vertical_edge_thickness(), location_height, star_view_);
765 if (add_to_app_launcher_view_->visible()) {
766 trailing_decorations.AddDecoration(
767 vertical_edge_thickness(), location_height, add_to_app_launcher_view_);
769 if (translate_icon_view_->visible()) {
770 trailing_decorations.AddDecoration(
771 vertical_edge_thickness(), location_height, translate_icon_view_);
773 if (open_pdf_in_reader_view_->visible()) {
774 trailing_decorations.AddDecoration(
775 vertical_edge_thickness(), location_height, open_pdf_in_reader_view_);
777 if (manage_passwords_icon_view_->visible()) {
778 trailing_decorations.AddDecoration(vertical_edge_thickness(),
780 manage_passwords_icon_view_);
782 for (PageActionViews::const_iterator i(page_action_views_.begin());
783 i != page_action_views_.end(); ++i) {
784 if ((*i)->visible()) {
785 trailing_decorations.AddDecoration(
786 vertical_edge_thickness(), location_height, (*i));
789 if (zoom_view_->visible()) {
790 trailing_decorations.AddDecoration(vertical_edge_thickness(),
791 location_height, zoom_view_);
793 for (ContentSettingViews::const_reverse_iterator i(
794 content_setting_views_.rbegin()); i != content_setting_views_.rend();
796 if ((*i)->visible()) {
797 trailing_decorations.AddDecoration(
798 bubble_location_y, bubble_height, false, 0, kItemPadding,
802 if (generated_credit_card_view_->visible()) {
803 trailing_decorations.AddDecoration(vertical_edge_thickness(),
805 generated_credit_card_view_);
807 if (mic_search_view_->visible()) {
808 trailing_decorations.AddDecoration(vertical_edge_thickness(),
809 location_height, mic_search_view_);
811 // Because IMEs may eat the tab key, we don't show "press tab to search" while
812 // IME composition is in progress.
813 if (!keyword.empty() && omnibox_view_->model()->is_keyword_hint() &&
814 !omnibox_view_->IsImeComposing()) {
815 trailing_decorations.AddDecoration(vertical_edge_thickness(),
816 location_height, true, 0, kItemPadding,
817 kItemPadding, keyword_hint_view_);
818 if (keyword_hint_view_->keyword() != keyword)
819 keyword_hint_view_->SetKeyword(keyword);
823 const int horizontal_edge_thickness = GetHorizontalEdgeThickness();
824 int full_width = width() - horizontal_edge_thickness - origin_chip_width;
826 const gfx::Size search_button_size(search_button_->GetPreferredSize());
827 const int search_button_reserved_width =
828 search_button_size.width() + kSearchButtonInset;
829 full_width -= search_button_->visible() ?
830 search_button_reserved_width : horizontal_edge_thickness;
831 int entry_width = full_width;
832 leading_decorations.LayoutPass1(&entry_width);
833 trailing_decorations.LayoutPass1(&entry_width);
834 leading_decorations.LayoutPass2(&entry_width);
835 trailing_decorations.LayoutPass2(&entry_width);
837 int location_needed_width = omnibox_view_->GetTextWidth();
838 int available_width = entry_width - location_needed_width;
839 // The bounds must be wide enough for all the decorations to fit.
840 gfx::Rect location_bounds(
841 origin_chip_width + horizontal_edge_thickness, vertical_edge_thickness(),
842 std::max(full_width, full_width - entry_width), location_height);
843 leading_decorations.LayoutPass3(&location_bounds, &available_width);
844 trailing_decorations.LayoutPass3(&location_bounds, &available_width);
846 // Calculate the animation parameters (see comments on these members in the
847 // header). We have to do this in Layout, after |origin_chip_view_| is laid
848 // out, because that may affect the host label offset in the origin chip.
849 const base::string16& chip_text(origin_chip_view_->host_label_text());
850 // If the chip is clicked, the omnibox text will become the toolbar model's
851 // formatted URL. We can't ask the omnibox for its current text, because
852 // while the chip is visible the current text is empty.
853 size_t prefix_end = 0;
854 const base::string16& omnibox_text(
855 GetToolbarModel()->GetFormattedURL(&prefix_end));
856 // Do a case-insensitive search to better match cases like
857 // "Settings" <-> "chrome://settings". Skip any pre-hostname text.
858 size_t chip_text_offset = std::search(
859 omnibox_text.begin() + prefix_end, omnibox_text.end(),
860 chip_text.begin(), chip_text.end(),
861 base::CaseInsensitiveCompare<base::char16>()) - omnibox_text.begin();
862 // If we couldn't find the chip text, try checking whether the omnibox text
863 // starts with it, as is true for e.g. file: URLs.
864 if ((chip_text_offset >= omnibox_text.length()) &&
865 StartsWith(omnibox_text, chip_text, true))
866 chip_text_offset = 0;
867 const gfx::FontList& font_list = omnibox_view_->GetFontList();
868 const int chip_text_width = gfx::GetStringWidth(chip_text, font_list);
869 const int old_starting_offset = starting_omnibox_offset_;
870 const int old_starting_leading_inset = starting_omnibox_leading_inset_;
871 const int old_ending_width = ending_omnibox_width_;
872 starting_omnibox_offset_ = current_omnibox_offset_ = 0;
873 starting_omnibox_leading_inset_ = current_omnibox_leading_inset_ = 0;
874 ending_omnibox_width_ = gfx::GetStringWidth(omnibox_text, font_list);
875 if (chip_text_offset < omnibox_text.length()) {
876 if (base::i18n::IsRTL())
877 chip_text_offset += chip_text.length();
878 base::string16 extra_omnibox_text(base::i18n::IsRTL() ?
879 omnibox_text.substr(chip_text_offset) :
880 omnibox_text.substr(0, chip_text_offset));
881 starting_omnibox_leading_inset_ =
882 gfx::GetStringWidth(extra_omnibox_text, font_list);
883 starting_omnibox_offset_ = origin_chip_view_->HostLabelOffset() -
884 starting_omnibox_leading_inset_;
885 current_omnibox_width_ = chip_text_width;
887 // If the chip text wasn't found in the omnibox text, then instead of
888 // starting the show animation clipped to the "hostname", we'll start with
889 // the entire omnibox text visible, clipped to the remaining chip width, and
890 // only animate any necessary expansion of that width, without moving the
892 current_omnibox_width_ = origin_chip_view_->WidthFromStartOfLabels();
895 // End the animations immediately if the parameters have changed.
896 if ((starting_omnibox_offset_ != old_starting_offset) ||
897 (starting_omnibox_leading_inset_ != old_starting_leading_inset) ||
898 (ending_omnibox_width_ != old_ending_width))
899 EndOriginChipAnimations(true);
901 // Also end the animations immediately if there's nothing to animate (but do
902 // allow the chip to fade back in).
903 const ui::NativeTheme* native_theme = GetNativeTheme();
904 const SkColor ending_selection_text_color = native_theme->GetSystemColor(
905 ui::NativeTheme::kColorId_TextfieldSelectionColor);
906 const SkColor ending_selection_background_color =
907 native_theme->GetSystemColor(
908 ui::NativeTheme::kColorId_TextfieldSelectionBackgroundFocused);
909 if ((starting_omnibox_offset_ == 0) &&
910 (starting_omnibox_leading_inset_ == 0) &&
911 (ending_omnibox_width_ == chip_text_width) &&
912 (hide_url_animation_->is_animating() ||
913 ((ending_selection_text_color ==
914 origin_chip_view_->pressed_text_color()) &&
915 (ending_selection_background_color ==
916 origin_chip_view_->pressed_background_color()))))
917 EndOriginChipAnimations(false);
919 if (show_url_animation_->is_animating()) {
920 omnibox_view_->SetSelectionTextColor(gfx::Tween::ColorValueBetween(
921 show_url_animation_->GetCurrentValue(),
922 origin_chip_view_->pressed_text_color(),
923 ending_selection_text_color));
924 omnibox_view_->SetSelectionBackgroundColor(gfx::Tween::ColorValueBetween(
925 show_url_animation_->GetCurrentValue(),
926 origin_chip_view_->pressed_background_color(),
927 ending_selection_background_color));
928 current_omnibox_offset_ =
929 show_url_animation_->CurrentValueBetween(starting_omnibox_offset_, 0);
930 current_omnibox_leading_inset_ = show_url_animation_->CurrentValueBetween(
931 starting_omnibox_leading_inset_, 0);
932 current_omnibox_width_ = show_url_animation_->CurrentValueBetween(
933 chip_text_width, ending_omnibox_width_);
934 } else if (hide_url_animation_->is_animating()) {
935 current_omnibox_offset_ =
936 hide_url_animation_->CurrentValueBetween(0, starting_omnibox_offset_);
937 current_omnibox_leading_inset_ = hide_url_animation_->CurrentValueBetween(
938 0, starting_omnibox_leading_inset_);
939 current_omnibox_width_ = hide_url_animation_->CurrentValueBetween(
940 ending_omnibox_width_, chip_text_width);
942 // Contract |available_width| as necessary, but never expand it. This way,
943 // we'll never draw suggested text at first and then have it disappear
944 // midway through the animation.
945 if (current_omnibox_offset_ > 0)
946 available_width -= current_omnibox_offset_;
947 location_bounds.Inset(current_omnibox_offset_, 0, 0, 0);
949 // Layout out the suggested text view right aligned to the location
950 // entry. Only show the suggested text if we can fit the text from one
951 // character before the end of the selection to the end of the text and the
952 // suggested text. If we can't it means either the suggested text is too big,
953 // or the user has scrolled.
955 // TODO(sky): We could potentially adjust this to take into account suggested
956 // text to force using minimum size if necessary, but currently the chance of
957 // showing keyword hints and suggested text is minimal and we're not confident
958 // this is the right approach for suggested text.
960 int omnibox_view_margin = 0;
961 if (suggested_text_view_->visible()) {
962 // We do not display the suggested text when it contains a mix of RTL and
963 // LTR characters since this could mean the suggestion should be displayed
964 // in the middle of the string.
965 base::i18n::TextDirection text_direction =
966 base::i18n::GetStringDirection(omnibox_view_->GetText());
967 if (text_direction !=
968 base::i18n::GetStringDirection(suggested_text_view_->text()))
969 text_direction = base::i18n::UNKNOWN_DIRECTION;
971 // TODO(sky): need to layout when the user changes caret position.
972 gfx::Size suggested_text_size(suggested_text_view_->GetPreferredSize());
973 if (suggested_text_size.width() > available_width ||
974 text_direction == base::i18n::UNKNOWN_DIRECTION) {
975 // Hide the suggested text if the user has scrolled or we can't fit all
976 // the suggested text, or we have a mix of RTL and LTR characters.
977 suggested_text_view_->SetBounds(0, 0, 0, 0);
979 location_needed_width =
980 std::min(location_needed_width,
981 location_bounds.width() - suggested_text_size.width());
982 gfx::Rect suggested_text_bounds(location_bounds.x(), location_bounds.y(),
983 suggested_text_size.width(),
984 location_bounds.height());
985 // TODO(sky): figure out why this needs the -1.
986 suggested_text_bounds.Offset(location_needed_width - 1, 0);
988 // We reverse the order of the location entry and suggested text if:
989 // - Chrome is RTL but the text is fully LTR, or
990 // - Chrome is LTR but the text is fully RTL.
991 // This ensures the suggested text is correctly displayed to the right
992 // (or left) of the user text.
993 if (text_direction == (base::i18n::IsRTL() ?
994 base::i18n::LEFT_TO_RIGHT : base::i18n::RIGHT_TO_LEFT)) {
995 // TODO(sky): Figure out why we need the +1.
996 suggested_text_bounds.set_x(location_bounds.x() + 1);
997 // Use a margin to prevent omnibox text from overlapping suggest text.
998 omnibox_view_margin = suggested_text_bounds.width();
1000 suggested_text_view_->SetBoundsRect(suggested_text_bounds);
1004 const gfx::Insets insets = omnibox_view_->GetInsets();
1005 omnibox_view_->SetBorder(views::Border::CreateEmptyBorder(
1006 insets.top(), insets.left(), insets.bottom(), omnibox_view_margin));
1008 // Layout |ime_inline_autocomplete_view_| next to the user input.
1009 if (ime_inline_autocomplete_view_->visible()) {
1011 gfx::GetStringWidth(ime_inline_autocomplete_view_->text(),
1012 ime_inline_autocomplete_view_->font_list()) +
1013 ime_inline_autocomplete_view_->GetInsets().width();
1014 // All the target languages (IMEs) are LTR, and we do not need to support
1015 // RTL so far. In other words, no testable RTL environment so far.
1016 int x = location_needed_width;
1017 if (width > entry_width)
1019 else if (location_needed_width + width > entry_width)
1020 x = entry_width - width;
1021 location_bounds.set_width(x);
1022 ime_inline_autocomplete_view_->SetBounds(
1023 location_bounds.right(), location_bounds.y(),
1024 std::min(width, entry_width), location_bounds.height());
1027 omnibox_view_->SetBoundsRect(location_bounds);
1029 search_button_->SetBoundsRect(gfx::Rect(
1030 gfx::Point(width() - search_button_reserved_width, 0),
1031 search_button_size));
1034 ////////////////////////////////////////////////////////////////////////////////
1035 // LocationBarView, public OmniboxEditController implementation:
1037 void LocationBarView::Update(const WebContents* contents) {
1038 mic_search_view_->SetVisible(
1039 !GetToolbarModel()->input_in_progress() && browser_ &&
1040 browser_->search_model()->voice_search_supported());
1041 RefreshContentSettingViews();
1042 generated_credit_card_view_->Update();
1043 ZoomBubbleView::CloseBubble();
1044 TranslateBubbleView::CloseBubble();
1046 RefreshPageActionViews();
1047 RefreshTranslateIcon();
1048 RefreshManagePasswordsIconView();
1049 content::WebContents* web_contents_for_sub_views =
1050 GetToolbarModel()->input_in_progress() ? NULL : GetWebContents();
1051 open_pdf_in_reader_view_->Update(web_contents_for_sub_views);
1052 add_to_app_launcher_view_->Update(web_contents_for_sub_views);
1055 star_view_->SetVisible(
1056 browser_defaults::bookmarks_enabled && !is_popup_mode_ &&
1057 !GetToolbarModel()->input_in_progress() &&
1058 edit_bookmarks_enabled_.GetValue() &&
1059 !IsBookmarkStarHiddenByExtension());
1063 omnibox_view_->OnTabChanged(contents);
1065 omnibox_view_->Update();
1067 OnChanged(); // NOTE: Calls Layout().
1070 void LocationBarView::ShowURL() {
1071 // Start the animation before calling ShowURL(), since the latter eventually
1072 // calls back to Layout(), and if the animation is not marked as "running",
1073 // we'll draw the omnibox in its final position briefly until the first
1074 // animation callback reaches us.
1075 if (chrome::ShouldDisplayOriginChip()) {
1076 // If we're currently hiding, reverse the hide by swapping to the show
1077 // animation, offset so that the text is in the same position.
1078 if (hide_url_animation_->is_animating()) {
1079 const double show_value = GetValueForAnimation(false);
1080 hide_url_animation_->Reset();
1081 show_url_animation_->Show();
1082 // This must be done after calling Show() and is not equivalent to
1083 // calling Reset(n) before Show(); Reset() would have caused the entire
1084 // animation curve (and time) to run between this value and the final
1085 // value, whereas Show() + SetCurrentValue() skips the animation forward
1086 // to the supplied value.
1087 show_url_animation_->SetCurrentValue(show_value);
1089 show_url_animation_->Show();
1092 omnibox_view_->ShowURL();
1095 void LocationBarView::EndOriginChipAnimations(bool cancel_fade) {
1096 show_url_animation_->End();
1097 hide_url_animation_->End();
1099 origin_chip_view_->CancelFade();
1102 ToolbarModel* LocationBarView::GetToolbarModel() {
1103 return delegate_->GetToolbarModel();
1106 WebContents* LocationBarView::GetWebContents() {
1107 return delegate_->GetWebContents();
1110 ////////////////////////////////////////////////////////////////////////////////
1111 // LocationBarView, private:
1114 int LocationBarView::IncrementalMinimumWidth(views::View* view) {
1115 return view->visible() ? (kItemPadding + view->GetMinimumSize().width()) : 0;
1118 int LocationBarView::GetHorizontalEdgeThickness() const {
1119 // In maximized popup mode, there isn't any edge.
1120 return (is_popup_mode_ && browser_ && browser_->window() &&
1121 browser_->window()->IsMaximized()) ? 0 : vertical_edge_thickness();
1124 bool LocationBarView::RefreshContentSettingViews() {
1125 bool visibility_changed = false;
1126 for (ContentSettingViews::const_iterator i(content_setting_views_.begin());
1127 i != content_setting_views_.end(); ++i) {
1128 const bool was_visible = (*i)->visible();
1129 (*i)->Update(GetToolbarModel()->input_in_progress() ?
1130 NULL : GetWebContents());
1131 if (was_visible != (*i)->visible())
1132 visibility_changed = true;
1134 return visibility_changed;
1137 void LocationBarView::DeletePageActionViews() {
1138 for (PageActionViews::const_iterator i(page_action_views_.begin());
1139 i != page_action_views_.end(); ++i)
1140 RemoveChildView(*i);
1141 STLDeleteElements(&page_action_views_);
1144 bool LocationBarView::RefreshPageActionViews() {
1148 bool changed = false;
1150 // Remember the previous visibility of the page actions so that we can
1151 // notify when this changes.
1152 std::map<ExtensionAction*, bool> old_visibility;
1153 for (PageActionViews::const_iterator i(page_action_views_.begin());
1154 i != page_action_views_.end(); ++i) {
1155 old_visibility[(*i)->image_view()->extension_action()] = (*i)->visible();
1158 PageActions new_page_actions;
1160 WebContents* web_contents = GetWebContents();
1162 extensions::TabHelper* extensions_tab_helper =
1163 extensions::TabHelper::FromWebContents(web_contents);
1164 extensions::LocationBarController* controller =
1165 extensions_tab_helper->location_bar_controller();
1166 new_page_actions = controller->GetCurrentActions();
1169 // On startup we sometimes haven't loaded any extensions. This makes sure
1170 // we catch up when the extensions (and any page actions) load.
1171 if (page_actions_ != new_page_actions) {
1174 page_actions_.swap(new_page_actions);
1175 DeletePageActionViews(); // Delete the old views (if any).
1177 // Create the page action views.
1178 for (PageActions::const_iterator i = page_actions_.begin();
1179 i != page_actions_.end(); ++i) {
1180 PageActionWithBadgeView* page_action_view = new PageActionWithBadgeView(
1181 delegate_->CreatePageActionImageView(this, *i));
1182 page_action_view->SetVisible(false);
1183 page_action_views_.push_back(page_action_view);
1186 // Move rightmost extensions to the start.
1187 std::stable_partition(
1188 page_action_views_.begin(),
1189 page_action_views_.end(),
1190 IsPageActionViewRightAligned(
1191 extensions::ExtensionRegistry::Get(profile())));
1193 View* right_anchor = open_pdf_in_reader_view_;
1195 right_anchor = star_view_;
1196 DCHECK(right_anchor);
1198 // |page_action_views_| are ordered right-to-left. Add them as children in
1199 // reverse order so the logical order and visual order match for
1200 // accessibility purposes.
1201 for (PageActionViews::reverse_iterator i = page_action_views_.rbegin();
1202 i != page_action_views_.rend(); ++i)
1203 AddChildViewAt(*i, GetIndexOf(right_anchor));
1206 if (!page_action_views_.empty() && web_contents) {
1207 for (PageActionViews::const_iterator i(page_action_views_.begin());
1208 i != page_action_views_.end(); ++i) {
1209 (*i)->UpdateVisibility(
1210 GetToolbarModel()->input_in_progress() ? NULL : web_contents);
1212 // Check if the visibility of the action changed and notify if it did.
1213 ExtensionAction* action = (*i)->image_view()->extension_action();
1214 if (old_visibility.find(action) == old_visibility.end() ||
1215 old_visibility[action] != (*i)->visible()) {
1217 content::NotificationService::current()->Notify(
1218 extensions::NOTIFICATION_EXTENSION_PAGE_ACTION_VISIBILITY_CHANGED,
1219 content::Source<ExtensionAction>(action),
1220 content::Details<WebContents>(web_contents));
1227 bool LocationBarView::RefreshZoomView() {
1229 WebContents* web_contents = GetWebContents();
1232 const bool was_visible = zoom_view_->visible();
1233 zoom_view_->Update(ZoomController::FromWebContents(web_contents));
1234 return was_visible != zoom_view_->visible();
1237 void LocationBarView::RefreshTranslateIcon() {
1238 if (!TranslateService::IsTranslateBubbleEnabled())
1241 WebContents* web_contents = GetWebContents();
1244 translate::LanguageState& language_state =
1245 ChromeTranslateClient::FromWebContents(web_contents)->GetLanguageState();
1246 bool enabled = language_state.translate_enabled();
1247 command_updater()->UpdateCommandEnabled(IDC_TRANSLATE_PAGE, enabled);
1248 translate_icon_view_->SetVisible(enabled);
1249 translate_icon_view_->SetToggled(language_state.IsPageTranslated());
1252 bool LocationBarView::RefreshManagePasswordsIconView() {
1253 DCHECK(manage_passwords_icon_view_);
1254 WebContents* web_contents = GetWebContents();
1257 const bool was_visible = manage_passwords_icon_view_->visible();
1258 ManagePasswordsUIController::FromWebContents(
1259 web_contents)->UpdateIconAndBubbleState(manage_passwords_icon_view_);
1260 return was_visible != manage_passwords_icon_view_->visible();
1263 void LocationBarView::ShowFirstRunBubbleInternal() {
1264 // First run bubble doesn't make sense for Chrome OS.
1265 #if !defined(OS_CHROMEOS)
1266 WebContents* web_contents = delegate_->GetWebContents();
1269 Browser* browser = chrome::FindBrowserWithWebContents(web_contents);
1271 FirstRunBubble::ShowBubble(browser, location_icon_view_);
1275 bool LocationBarView::HasValidSuggestText() const {
1276 return suggested_text_view_->visible() &&
1277 !suggested_text_view_->size().IsEmpty();
1280 bool LocationBarView::ShouldShowKeywordBubble() const {
1281 return !omnibox_view_->model()->keyword().empty() &&
1282 !omnibox_view_->model()->is_keyword_hint();
1285 bool LocationBarView::ShouldShowEVBubble() const {
1286 return !chrome::ShouldDisplayOriginChip() &&
1287 (GetToolbarModel()->GetSecurityLevel(false) == ToolbarModel::EV_SECURE);
1290 double LocationBarView::GetValueForAnimation(bool hide) const {
1291 int calculated_offset;
1292 const gfx::Tween::Type tween_type = hide ? kHideTweenType : kShowTweenType;
1293 int start_offset = starting_omnibox_offset_, end_offset = 0;
1295 std::swap(start_offset, end_offset);
1296 const int desired_offset = abs(current_omnibox_offset_);
1297 // Binary-search the value space (0 <= value <= 1) to find the appropriate
1298 // position. We only bother to iterate to within 1/64 of the desired value,
1299 // because the longer of the two animations will only run for twelve frames
1300 // anyway (200 ms * 60 Hz), so at this point we'll have a maximum error of
1301 // less than a fifth of an animation frame, which the user isn't going to
1304 // We have to use this method because Tween::CalculateValue() is not
1305 // necessarily easily invertible. Luckily, this only runs when the user
1306 // reverses the animation (rare), and the limit on how many iterations we'll
1307 // do ensures the cost is unnoticeable.
1309 double step = value / 2;
1311 calculated_offset = abs(gfx::Tween::IntValueBetween(
1312 gfx::Tween::CalculateValue(tween_type, value), start_offset,
1314 if (calculated_offset < desired_offset)
1316 else if (calculated_offset > desired_offset)
1319 } while ((calculated_offset != desired_offset) && (step >= (1.0 / 64)));
1323 void LocationBarView::ResetShowAnimationAndColors() {
1324 show_url_animation_->Reset();
1325 omnibox_view_->UseDefaultSelectionTextColor();
1326 omnibox_view_->UseDefaultSelectionBackgroundColor();
1329 ////////////////////////////////////////////////////////////////////////////////
1330 // LocationBarView, private LocationBar implementation:
1332 void LocationBarView::ShowFirstRunBubble() {
1333 // Wait until search engines have loaded to show the first run bubble.
1334 TemplateURLService* url_service =
1335 TemplateURLServiceFactory::GetForProfile(profile());
1336 if (!url_service->loaded()) {
1337 template_url_service_ = url_service;
1338 template_url_service_->AddObserver(this);
1339 template_url_service_->Load();
1342 ShowFirstRunBubbleInternal();
1345 GURL LocationBarView::GetDestinationURL() const {
1346 return destination_url();
1349 WindowOpenDisposition LocationBarView::GetWindowOpenDisposition() const {
1350 return disposition();
1353 content::PageTransition LocationBarView::GetPageTransition() const {
1354 return transition();
1357 void LocationBarView::AcceptInput() {
1358 omnibox_view_->model()->AcceptInput(CURRENT_TAB, false);
1361 void LocationBarView::FocusSearch() {
1362 omnibox_view_->SetFocus();
1363 omnibox_view_->SetForcedQuery();
1366 void LocationBarView::UpdateContentSettingsIcons() {
1367 if (RefreshContentSettingViews()) {
1373 void LocationBarView::UpdateManagePasswordsIconAndBubble() {
1374 if (RefreshManagePasswordsIconView()) {
1380 void LocationBarView::UpdatePageActions() {
1381 size_t count_before = page_action_views_.size();
1382 bool changed = RefreshPageActionViews();
1383 if (page_action_views_.size() != count_before) {
1384 content::NotificationService::current()->Notify(
1385 extensions::NOTIFICATION_EXTENSION_PAGE_ACTION_COUNT_CHANGED,
1386 content::Source<LocationBar>(this),
1387 content::NotificationService::NoDetails());
1396 void LocationBarView::InvalidatePageActions() {
1397 size_t count_before = page_action_views_.size();
1398 DeletePageActionViews();
1399 if (page_action_views_.size() != count_before) {
1400 content::NotificationService::current()->Notify(
1401 extensions::NOTIFICATION_EXTENSION_PAGE_ACTION_COUNT_CHANGED,
1402 content::Source<LocationBar>(this),
1403 content::NotificationService::NoDetails());
1407 void LocationBarView::UpdateOpenPDFInReaderPrompt() {
1408 open_pdf_in_reader_view_->Update(
1409 GetToolbarModel()->input_in_progress() ? NULL : GetWebContents());
1414 void LocationBarView::UpdateGeneratedCreditCardView() {
1415 generated_credit_card_view_->Update();
1420 void LocationBarView::SaveStateToContents(WebContents* contents) {
1421 // If we're about to switch tabs, complete any current animations, so that if
1422 // the user is in the midst of hiding the URL, when he returns to this tab,
1423 // the URL will be hidden rather than shown.
1424 // NOTE: This must be called before SaveStateToTab().
1425 EndOriginChipAnimations(true);
1426 omnibox_view_->SaveStateToTab(contents);
1429 const OmniboxView* LocationBarView::GetOmniboxView() const {
1430 return omnibox_view_;
1433 LocationBarTesting* LocationBarView::GetLocationBarForTesting() {
1437 ////////////////////////////////////////////////////////////////////////////////
1438 // LocationBarView, private LocationBarTesting implementation:
1440 int LocationBarView::PageActionCount() {
1441 return page_action_views_.size();
1444 int LocationBarView::PageActionVisibleCount() {
1446 for (size_t i = 0; i < page_action_views_.size(); i++) {
1447 if (page_action_views_[i]->visible())
1453 ExtensionAction* LocationBarView::GetPageAction(size_t index) {
1454 if (index < page_action_views_.size())
1455 return page_action_views_[index]->image_view()->extension_action();
1461 ExtensionAction* LocationBarView::GetVisiblePageAction(size_t index) {
1463 for (size_t i = 0; i < page_action_views_.size(); ++i) {
1464 if (page_action_views_[i]->visible()) {
1465 if (current == index)
1466 return page_action_views_[i]->image_view()->extension_action();
1476 void LocationBarView::TestPageActionPressed(size_t index) {
1478 for (size_t i = 0; i < page_action_views_.size(); ++i) {
1479 if (page_action_views_[i]->visible()) {
1480 if (current == index) {
1481 page_action_views_[i]->image_view()->view_controller()->
1482 ExecuteAction(ExtensionPopup::SHOW, true);
1492 bool LocationBarView::GetBookmarkStarVisibility() {
1494 return star_view_->visible();
1497 ////////////////////////////////////////////////////////////////////////////////
1498 // LocationBarView, private views::View implementation:
1500 const char* LocationBarView::GetClassName() const {
1501 return kViewClassName;
1504 void LocationBarView::OnBoundsChanged(const gfx::Rect& previous_bounds) {
1505 InstantServiceFactory::GetForProfile(profile())->OnOmniboxStartMarginChanged(
1508 OmniboxPopupView* popup = omnibox_view_->model()->popup_model()->view();
1509 if (popup->IsOpen())
1510 popup->UpdatePopupAppearance();
1513 void LocationBarView::OnFocus() {
1514 // Explicitly focus the omnibox so a focus ring will be displayed around it on
1516 omnibox_view_->SetFocus();
1519 void LocationBarView::OnPaint(gfx::Canvas* canvas) {
1520 View::OnPaint(canvas);
1522 // Fill the location bar background color behind the border. Parts of the
1523 // border images are meant to rest atop the toolbar background and parts atop
1524 // the omnibox background, so we can't just blindly fill our entire bounds.
1525 gfx::Rect bounds(GetContentsBounds());
1526 bounds.Inset(GetHorizontalEdgeThickness(), vertical_edge_thickness());
1527 SkColor color(GetColor(ToolbarModel::NONE, BACKGROUND));
1528 if (is_popup_mode_) {
1529 canvas->FillRect(bounds, color);
1532 paint.setStyle(SkPaint::kFill_Style);
1533 paint.setColor(color);
1534 const int kBorderCornerRadius = 2;
1535 canvas->DrawRoundRect(bounds, kBorderCornerRadius, paint);
1538 // The border itself will be drawn in PaintChildren() since it includes an
1539 // inner shadow which should be drawn over the contents.
1542 void LocationBarView::PaintChildren(gfx::Canvas* canvas,
1543 const views::CullSet& cull_set) {
1544 // Paint all the children except for the omnibox itself, which may need to be
1545 // clipped if it's animating in, and the origin chip and the search button,
1546 // which will be painted after the border.
1547 for (int i = 0, count = child_count(); i < count; ++i) {
1548 views::View* child = child_at(i);
1549 if (!child->layer() && (child != omnibox_view_) &&
1550 (child != origin_chip_view_) && (child != search_button_))
1551 child->Paint(canvas, cull_set);
1555 gfx::ScopedCanvas scoped_canvas(canvas);
1556 if (show_url_animation_->is_animating() ||
1557 hide_url_animation_->is_animating()) {
1558 gfx::Rect clip_rect(omnibox_view_->bounds());
1559 clip_rect.Inset(current_omnibox_leading_inset_, 0, 0, 0);
1560 clip_rect.set_width(current_omnibox_width_);
1561 clip_rect.set_x(GetMirroredXForRect(clip_rect));
1562 canvas->ClipRect(clip_rect);
1564 omnibox_view_->Paint(canvas, cull_set);
1567 // For non-InstantExtendedAPI cases, if necessary, show focus rect. As we need
1568 // the focus rect to appear on top of children we paint here rather than
1570 // Note: |Canvas::DrawFocusRect| paints a dashed rect with gray color.
1571 if (show_focus_rect_ && HasFocus())
1572 canvas->DrawFocusRect(omnibox_view_->bounds());
1574 // Maximized popup windows don't draw the horizontal edges. We implement this
1575 // by simply expanding the paint area outside the view by the edge thickness.
1576 gfx::Rect border_rect(GetContentsBounds());
1577 if (is_popup_mode_ && (GetHorizontalEdgeThickness() == 0))
1578 border_rect.Inset(-kPopupEdgeThickness, 0);
1579 views::Painter::PaintPainterAt(canvas, border_painter_.get(), border_rect);
1581 // The origin chip and the search button must be painted after the border so
1582 // that the border shadow is not drawn over them.
1583 origin_chip_view_->Paint(canvas, cull_set);
1584 search_button_->Paint(canvas, cull_set);
1587 ////////////////////////////////////////////////////////////////////////////////
1588 // LocationBarView, private views::ButtonListener implementation:
1590 void LocationBarView::ButtonPressed(views::Button* sender,
1591 const ui::Event& event) {
1592 if (sender == mic_search_view_) {
1593 command_updater()->ExecuteCommand(IDC_TOGGLE_SPEECH_INPUT);
1597 DCHECK_EQ(search_button_, sender);
1598 // TODO(pkasting): When macourteau adds UMA stats for this, wire them up here.
1599 omnibox_view_->model()->AcceptInput(
1600 ui::DispositionFromEventFlags(event.flags()), false);
1603 ////////////////////////////////////////////////////////////////////////////////
1604 // LocationBarView, private views::DragController implementation:
1606 void LocationBarView::WriteDragDataForView(views::View* sender,
1607 const gfx::Point& press_pt,
1608 OSExchangeData* data) {
1609 DCHECK_NE(GetDragOperationsForView(sender, press_pt),
1610 ui::DragDropTypes::DRAG_NONE);
1612 WebContents* web_contents = GetWebContents();
1613 FaviconTabHelper* favicon_tab_helper =
1614 FaviconTabHelper::FromWebContents(web_contents);
1615 gfx::ImageSkia favicon = favicon_tab_helper->GetFavicon().AsImageSkia();
1616 button_drag_utils::SetURLAndDragImage(web_contents->GetURL(),
1617 web_contents->GetTitle(),
1621 sender->GetWidget());
1624 int LocationBarView::GetDragOperationsForView(views::View* sender,
1625 const gfx::Point& p) {
1626 DCHECK((sender == location_icon_view_) || (sender == ev_bubble_view_) ||
1627 (sender == origin_chip_view_));
1628 WebContents* web_contents = delegate_->GetWebContents();
1629 return (web_contents && web_contents->GetURL().is_valid() &&
1630 (!GetOmniboxView()->IsEditingOrEmpty() ||
1631 sender == origin_chip_view_)) ?
1632 (ui::DragDropTypes::DRAG_COPY | ui::DragDropTypes::DRAG_LINK) :
1633 ui::DragDropTypes::DRAG_NONE;
1636 bool LocationBarView::CanStartDragForView(View* sender,
1637 const gfx::Point& press_pt,
1638 const gfx::Point& p) {
1642 ////////////////////////////////////////////////////////////////////////////////
1643 // LocationBarView, private OmniboxEditController implementation:
1645 void LocationBarView::OnChanged() {
1646 int icon_id = omnibox_view_->GetIcon();
1647 location_icon_view_->SetImage(GetThemeProvider()->GetImageSkiaNamed(icon_id));
1648 location_icon_view_->ShowTooltip(!GetOmniboxView()->IsEditingOrEmpty());
1650 ToolbarModel* toolbar_model = GetToolbarModel();
1651 chrome::DisplaySearchButtonConditions conditions =
1652 chrome::GetDisplaySearchButtonConditions();
1653 bool meets_conditions =
1654 (conditions == chrome::DISPLAY_SEARCH_BUTTON_ALWAYS) ||
1655 ((conditions != chrome::DISPLAY_SEARCH_BUTTON_NEVER) &&
1656 (toolbar_model->WouldPerformSearchTermReplacement(true) ||
1657 ((conditions == chrome::DISPLAY_SEARCH_BUTTON_FOR_STR_OR_IIP) &&
1658 toolbar_model->input_in_progress())));
1659 search_button_->SetVisible(!is_popup_mode_ && meets_conditions);
1660 search_button_->UpdateIcon(icon_id == IDR_OMNIBOX_SEARCH);
1662 origin_chip_view_->OnChanged();
1668 void LocationBarView::OnSetFocus() {
1669 GetFocusManager()->SetFocusedView(this);
1672 InstantController* LocationBarView::GetInstant() {
1673 return delegate_->GetInstant();
1676 const ToolbarModel* LocationBarView::GetToolbarModel() const {
1677 return delegate_->GetToolbarModel();
1680 void LocationBarView::HideURL() {
1681 DCHECK(chrome::ShouldDisplayOriginChip());
1683 // If we're currently showing, reverse the hide by swapping to the hide
1684 // animation, offset so that the text is in the same position.
1685 if (show_url_animation_->is_animating()) {
1686 const double hide_value = GetValueForAnimation(true);
1687 ResetShowAnimationAndColors();
1688 hide_url_animation_->Show();
1689 // This must be done after calling Show() and is not equivalent to Reset(n);
1690 // see comments in ShowURL().
1691 hide_url_animation_->SetCurrentValue(hide_value);
1693 hide_url_animation_->Show();
1697 ////////////////////////////////////////////////////////////////////////////////
1698 // LocationBarView, private DropdownBarHostDelegate implementation:
1700 void LocationBarView::SetFocusAndSelection(bool select_all) {
1701 FocusLocation(select_all);
1704 void LocationBarView::SetAnimationOffset(int offset) {
1705 dropdown_animation_offset_ = offset;
1708 ////////////////////////////////////////////////////////////////////////////////
1709 // LocationBarView, private gfx::AnimationDelegate implementation:
1711 void LocationBarView::AnimationProgressed(const gfx::Animation* animation) {
1712 DCHECK((animation == show_url_animation_.get()) ||
1713 (animation == hide_url_animation_.get()));
1718 void LocationBarView::AnimationEnded(const gfx::Animation* animation) {
1719 if (animation == show_url_animation_.get()) {
1720 ResetShowAnimationAndColors();
1724 DCHECK(animation == hide_url_animation_.get());
1725 hide_url_animation_->Reset();
1726 origin_chip_view_->FadeIn();
1727 omnibox_view_->HideURL(); // Calls OnChanged(), triggering layout.
1731 ////////////////////////////////////////////////////////////////////////////////
1732 // LocationBarView, private TemplateURLServiceObserver implementation:
1734 void LocationBarView::OnTemplateURLServiceChanged() {
1735 template_url_service_->RemoveObserver(this);
1736 template_url_service_ = NULL;
1737 // If the browser is no longer active, let's not show the info bubble, as this
1738 // would make the browser the active window again.
1739 if (omnibox_view_ && omnibox_view_->GetWidget()->IsActive())
1740 ShowFirstRunBubble();
1743 ////////////////////////////////////////////////////////////////////////////////
1744 // LocationBarView, private content::NotificationObserver implementation:
1746 void LocationBarView::Observe(int type,
1747 const content::NotificationSource& source,
1748 const content::NotificationDetails& details) {
1750 case extensions::NOTIFICATION_EXTENSION_LOADED_DEPRECATED:
1751 case extensions::NOTIFICATION_EXTENSION_UNLOADED_DEPRECATED:
1756 NOTREACHED() << "Unexpected notification.";
1760 ////////////////////////////////////////////////////////////////////////////////
1761 // LocationBarView, private SearchModelObserver implementation:
1763 void LocationBarView::ModelChanged(const SearchModel::State& old_state,
1764 const SearchModel::State& new_state) {
1765 const bool visible = !GetToolbarModel()->input_in_progress() &&
1766 new_state.voice_search_supported;
1767 if (mic_search_view_->visible() != visible) {
1768 mic_search_view_->SetVisible(visible);