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/extension_service.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.h"
29 #include "chrome/browser/search_engines/template_url_service.h"
30 #include "chrome/browser/search_engines/template_url_service_factory.h"
31 #include "chrome/browser/translate/chrome_translate_client.h"
32 #include "chrome/browser/translate/translate_service.h"
33 #include "chrome/browser/ui/browser.h"
34 #include "chrome/browser/ui/browser_finder.h"
35 #include "chrome/browser/ui/browser_instant_controller.h"
36 #include "chrome/browser/ui/browser_window.h"
37 #include "chrome/browser/ui/omnibox/location_bar_util.h"
38 #include "chrome/browser/ui/omnibox/omnibox_popup_model.h"
39 #include "chrome/browser/ui/omnibox/omnibox_popup_view.h"
40 #include "chrome/browser/ui/passwords/manage_passwords_icon.h"
41 #include "chrome/browser/ui/passwords/manage_passwords_ui_controller.h"
42 #include "chrome/browser/ui/tabs/tab_strip_model.h"
43 #include "chrome/browser/ui/view_ids.h"
44 #include "chrome/browser/ui/views/browser_dialogs.h"
45 #include "chrome/browser/ui/views/location_bar/add_to_app_launcher_view.h"
46 #include "chrome/browser/ui/views/location_bar/content_setting_image_view.h"
47 #include "chrome/browser/ui/views/location_bar/ev_bubble_view.h"
48 #include "chrome/browser/ui/views/location_bar/generated_credit_card_view.h"
49 #include "chrome/browser/ui/views/location_bar/keyword_hint_view.h"
50 #include "chrome/browser/ui/views/location_bar/location_bar_layout.h"
51 #include "chrome/browser/ui/views/location_bar/location_icon_view.h"
52 #include "chrome/browser/ui/views/location_bar/open_pdf_in_reader_view.h"
53 #include "chrome/browser/ui/views/location_bar/origin_chip_view.h"
54 #include "chrome/browser/ui/views/location_bar/page_action_image_view.h"
55 #include "chrome/browser/ui/views/location_bar/page_action_with_badge_view.h"
56 #include "chrome/browser/ui/views/location_bar/search_button.h"
57 #include "chrome/browser/ui/views/location_bar/selected_keyword_view.h"
58 #include "chrome/browser/ui/views/location_bar/star_view.h"
59 #include "chrome/browser/ui/views/location_bar/translate_icon_view.h"
60 #include "chrome/browser/ui/views/location_bar/zoom_bubble_view.h"
61 #include "chrome/browser/ui/views/location_bar/zoom_view.h"
62 #include "chrome/browser/ui/views/passwords/manage_passwords_bubble_view.h"
63 #include "chrome/browser/ui/views/passwords/manage_passwords_icon_view.h"
64 #include "chrome/browser/ui/zoom/zoom_controller.h"
65 #include "chrome/common/chrome_switches.h"
66 #include "chrome/common/pref_names.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_system.h"
72 #include "extensions/common/feature_switch.h"
73 #include "extensions/common/permissions/permissions_data.h"
74 #include "grit/generated_resources.h"
75 #include "grit/theme_resources.h"
76 #include "ui/accessibility/ax_view_state.h"
77 #include "ui/base/dragdrop/drag_drop_types.h"
78 #include "ui/base/l10n/l10n_util.h"
79 #include "ui/base/resource/resource_bundle.h"
80 #include "ui/base/theme_provider.h"
81 #include "ui/events/event.h"
82 #include "ui/gfx/animation/slide_animation.h"
83 #include "ui/gfx/canvas.h"
84 #include "ui/gfx/color_utils.h"
85 #include "ui/gfx/image/image.h"
86 #include "ui/gfx/image/image_skia_operations.h"
87 #include "ui/gfx/scoped_canvas.h"
88 #include "ui/gfx/skia_util.h"
89 #include "ui/gfx/text_utils.h"
90 #include "ui/native_theme/native_theme.h"
91 #include "ui/views/background.h"
92 #include "ui/views/border.h"
93 #include "ui/views/button_drag_utils.h"
94 #include "ui/views/controls/button/image_button.h"
95 #include "ui/views/controls/label.h"
96 #include "ui/views/widget/widget.h"
97
98 #if !defined(OS_CHROMEOS)
99 #include "chrome/browser/ui/views/first_run_bubble.h"
100 #endif
101
102 using content::WebContents;
103 using views::View;
104
105 namespace {
106
107 const gfx::Tween::Type kShowTweenType = gfx::Tween::LINEAR_OUT_SLOW_IN;
108 const gfx::Tween::Type kHideTweenType = gfx::Tween::FAST_OUT_LINEAR_IN;
109
110 // The search button images are made to look as if they overlay the normal edge
111 // images, but to align things, the search button needs to be inset horizontally
112 // by 1 px.
113 const int kSearchButtonInset = 1;
114
115 // Given a containing |height| and a |base_font_list|, shrinks the font size
116 // until the font list will fit within |height| while having its cap height
117 // vertically centered. Returns the correctly-sized font list.
118 //
119 // The expected layout:
120 // +--------+-----------------------------------------------+------------+
121 // | | y offset | space |
122 // | +--------+-------------------+------------------+ above |
123 // | | | | internal leading | cap height |
124 // | box | font | ascent (baseline) +------------------+------------+
125 // | height | height | | cap height |
126 // | | |-------------------+------------------+------------+
127 // | | | descent (height - baseline) | space |
128 // | +--------+--------------------------------------+ below |
129 // | | space at bottom | cap height |
130 // +--------+-----------------------------------------------+------------+
131 // Goal:
132 // center of box height == center of cap height
133 // (i.e. space above cap height == space below cap height)
134 // Restrictions:
135 // y offset >= 0
136 // space at bottom >= 0
137 // (i.e. Entire font must be visible inside the box.)
GetLargestFontListWithHeightBound(const gfx::FontList & base_font_list,int height)138 gfx::FontList GetLargestFontListWithHeightBound(
139 const gfx::FontList& base_font_list,
140 int height) {
141 gfx::FontList font_list = base_font_list;
142 for (int font_size = font_list.GetFontSize(); font_size > 1; --font_size) {
143 const int internal_leading =
144 font_list.GetBaseline() - font_list.GetCapHeight();
145 // Some platforms don't support getting the cap height, and simply return
146 // the entire font ascent from GetCapHeight(). Centering the ascent makes
147 // the font look too low, so if GetCapHeight() returns the ascent, center
148 // the entire font height instead.
149 const int space =
150 height - ((internal_leading != 0) ?
151 font_list.GetCapHeight() : font_list.GetHeight());
152 const int y_offset = space / 2 - internal_leading;
153 const int space_at_bottom = height - (y_offset + font_list.GetHeight());
154 if ((y_offset >= 0) && (space_at_bottom >= 0))
155 break;
156 font_list = font_list.DeriveWithSizeDelta(-1);
157 }
158 return font_list;
159 }
160
GetEditLeadingInternalSpace()161 int GetEditLeadingInternalSpace() {
162 // The textfield has 1 px of whitespace before the text in the RTL case only.
163 return base::i18n::IsRTL() ? 1 : 0;
164 }
165
166 // Functor for moving BookmarkManagerPrivate page actions to the right via
167 // stable_partition.
168 class IsPageActionViewRightAligned {
169 public:
IsPageActionViewRightAligned(ExtensionService * extension_service)170 explicit IsPageActionViewRightAligned(ExtensionService* extension_service)
171 : extension_service_(extension_service) {}
172
operator ()(PageActionWithBadgeView * page_action_view)173 bool operator()(PageActionWithBadgeView* page_action_view) {
174 return extension_service_
175 ->GetExtensionById(
176 page_action_view->image_view()->page_action()->extension_id(),
177 false)
178 ->permissions_data()
179 ->HasAPIPermission(extensions::APIPermission::kBookmarkManagerPrivate);
180 }
181
182 private:
183 ExtensionService* extension_service_;
184
185 // NOTE: Can't DISALLOW_COPY_AND_ASSIGN as we pass this object by value to
186 // std::stable_partition().
187 };
188
189 } // namespace
190
191
192 // LocationBarView -----------------------------------------------------------
193
194 // static
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";
201
LocationBarView(Browser * browser,Profile * profile,CommandUpdater * command_updater,Delegate * delegate,bool is_popup_mode)202 LocationBarView::LocationBarView(Browser* browser,
203 Profile* profile,
204 CommandUpdater* command_updater,
205 Delegate* delegate,
206 bool is_popup_mode)
207 : LocationBar(profile),
208 OmniboxEditController(command_updater),
209 browser_(browser),
210 omnibox_view_(NULL),
211 delegate_(delegate),
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),
220 zoom_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),
226 star_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 weak_ptr_factory_(this) {
239 edit_bookmarks_enabled_.Init(
240 prefs::kEditBookmarksEnabled, profile->GetPrefs(),
241 base::Bind(&LocationBarView::Update, base::Unretained(this),
242 static_cast<content::WebContents*>(NULL)));
243
244 if (browser_)
245 browser_->search_model()->AddObserver(this);
246 }
247
~LocationBarView()248 LocationBarView::~LocationBarView() {
249 if (template_url_service_)
250 template_url_service_->RemoveObserver(this);
251 if (browser_)
252 browser_->search_model()->RemoveObserver(this);
253 }
254
255 ////////////////////////////////////////////////////////////////////////////////
256 // LocationBarView, public:
257
Init()258 void LocationBarView::Init() {
259 // We need to be in a Widget, otherwise GetNativeTheme() may change and we're
260 // not prepared for that.
261 DCHECK(GetWidget());
262
263 const int kOmniboxPopupBorderImages[] =
264 IMAGE_GRID(IDR_OMNIBOX_POPUP_BORDER_AND_SHADOW);
265 const int kOmniboxBorderImages[] = IMAGE_GRID(IDR_TEXTFIELD);
266 border_painter_.reset(views::Painter::CreateImageGridPainter(
267 is_popup_mode_ ? kOmniboxPopupBorderImages : kOmniboxBorderImages));
268
269 location_icon_view_ = new LocationIconView(this);
270 location_icon_view_->set_drag_controller(this);
271 AddChildView(location_icon_view_);
272
273 // Determine the main font.
274 gfx::FontList font_list = ResourceBundle::GetSharedInstance().GetFontList(
275 ResourceBundle::BaseFont);
276 const int current_font_size = font_list.GetFontSize();
277 const int desired_font_size = browser_defaults::kOmniboxFontPixelSize;
278 if (current_font_size != desired_font_size) {
279 font_list =
280 font_list.DeriveWithSizeDelta(desired_font_size - current_font_size);
281 }
282 // Shrink large fonts to make them fit.
283 // TODO(pkasting): Stretch the location bar instead in this case.
284 const int location_height = GetInternalHeight(true);
285 font_list = GetLargestFontListWithHeightBound(font_list, location_height);
286
287 // Determine the font for use inside the bubbles. The bubble background
288 // images have 1 px thick edges, which we don't want to overlap.
289 const int kBubbleInteriorVerticalPadding = 1;
290 const int bubble_vertical_padding =
291 (kBubblePadding + kBubbleInteriorVerticalPadding) * 2;
292 const gfx::FontList bubble_font_list(
293 GetLargestFontListWithHeightBound(
294 font_list, location_height - bubble_vertical_padding));
295
296 const SkColor background_color =
297 GetColor(ToolbarModel::NONE, LocationBarView::BACKGROUND);
298 ev_bubble_view_ = new EVBubbleView(
299 bubble_font_list, GetColor(ToolbarModel::EV_SECURE, SECURITY_TEXT),
300 background_color, this);
301 ev_bubble_view_->set_drag_controller(this);
302 AddChildView(ev_bubble_view_);
303
304 // Initialize the Omnibox view.
305 omnibox_view_ = new OmniboxViewViews(
306 this, profile(), command_updater(),
307 is_popup_mode_ ||
308 (browser_->is_app() && CommandLine::ForCurrentProcess()->
309 HasSwitch(switches::kEnableStreamlinedHostedApps)),
310 this, font_list);
311 omnibox_view_->Init();
312 omnibox_view_->SetFocusable(true);
313 AddChildView(omnibox_view_);
314
315 // Initialize the inline autocomplete view which is visible only when IME is
316 // turned on. Use the same font with the omnibox and highlighted background.
317 ime_inline_autocomplete_view_ = new views::Label(base::string16(), font_list);
318 ime_inline_autocomplete_view_->SetHorizontalAlignment(gfx::ALIGN_LEFT);
319 ime_inline_autocomplete_view_->SetAutoColorReadabilityEnabled(false);
320 ime_inline_autocomplete_view_->set_background(
321 views::Background::CreateSolidBackground(GetNativeTheme()->GetSystemColor(
322 ui::NativeTheme::kColorId_TextfieldSelectionBackgroundFocused)));
323 ime_inline_autocomplete_view_->SetEnabledColor(
324 GetNativeTheme()->GetSystemColor(
325 ui::NativeTheme::kColorId_TextfieldSelectionColor));
326 ime_inline_autocomplete_view_->SetVisible(false);
327 AddChildView(ime_inline_autocomplete_view_);
328
329 origin_chip_view_ = new OriginChipView(this, profile(), font_list);
330 origin_chip_view_->SetFocusable(false);
331 origin_chip_view_->set_drag_controller(this);
332 AddChildView(origin_chip_view_);
333
334 const SkColor text_color = GetColor(ToolbarModel::NONE, TEXT);
335 selected_keyword_view_ = new SelectedKeywordView(
336 bubble_font_list, text_color, background_color, profile());
337 AddChildView(selected_keyword_view_);
338
339 suggested_text_view_ = new views::Label(base::string16(), font_list);
340 suggested_text_view_->SetHorizontalAlignment(gfx::ALIGN_LEFT);
341 suggested_text_view_->SetAutoColorReadabilityEnabled(false);
342 suggested_text_view_->SetEnabledColor(GetColor(
343 ToolbarModel::NONE, LocationBarView::DEEMPHASIZED_TEXT));
344 suggested_text_view_->SetVisible(false);
345 AddChildView(suggested_text_view_);
346
347 keyword_hint_view_ = new KeywordHintView(
348 profile(), font_list,
349 GetColor(ToolbarModel::NONE, LocationBarView::DEEMPHASIZED_TEXT),
350 background_color);
351 AddChildView(keyword_hint_view_);
352
353 mic_search_view_ = new views::ImageButton(this);
354 mic_search_view_->set_id(VIEW_ID_MIC_SEARCH_BUTTON);
355 mic_search_view_->SetAccessibilityFocusable(true);
356 mic_search_view_->SetTooltipText(
357 l10n_util::GetStringUTF16(IDS_TOOLTIP_MIC_SEARCH));
358 mic_search_view_->SetImage(
359 views::Button::STATE_NORMAL,
360 ui::ResourceBundle::GetSharedInstance().GetImageSkiaNamed(
361 IDR_OMNIBOX_MIC_SEARCH));
362 mic_search_view_->SetImageAlignment(views::ImageButton::ALIGN_CENTER,
363 views::ImageButton::ALIGN_MIDDLE);
364 mic_search_view_->SetVisible(false);
365 AddChildView(mic_search_view_);
366
367 for (int i = 0; i < CONTENT_SETTINGS_NUM_TYPES; ++i) {
368 ContentSettingImageView* content_blocked_view =
369 new ContentSettingImageView(static_cast<ContentSettingsType>(i), this,
370 bubble_font_list, text_color,
371 background_color);
372 content_setting_views_.push_back(content_blocked_view);
373 content_blocked_view->SetVisible(false);
374 AddChildView(content_blocked_view);
375 }
376
377 generated_credit_card_view_ = new GeneratedCreditCardView(delegate_);
378 AddChildView(generated_credit_card_view_);
379
380 zoom_view_ = new ZoomView(delegate_);
381 zoom_view_->set_id(VIEW_ID_ZOOM_BUTTON);
382 AddChildView(zoom_view_);
383
384 open_pdf_in_reader_view_ = new OpenPDFInReaderView();
385 AddChildView(open_pdf_in_reader_view_);
386
387 manage_passwords_icon_view_ = new ManagePasswordsIconView(command_updater());
388 AddChildView(manage_passwords_icon_view_);
389
390 translate_icon_view_ = new TranslateIconView(command_updater());
391 translate_icon_view_->SetVisible(false);
392 AddChildView(translate_icon_view_);
393
394 add_to_app_launcher_view_ = new AddToAppLauncherView(
395 this, bubble_font_list, text_color, background_color);
396 add_to_app_launcher_view_->SetVisible(false);
397 AddChildView(add_to_app_launcher_view_);
398
399 star_view_ = new StarView(command_updater());
400 star_view_->SetVisible(false);
401 AddChildView(star_view_);
402
403 search_button_ = new SearchButton(this);
404 search_button_->SetVisible(false);
405 AddChildView(search_button_);
406
407 show_url_animation_.reset(new gfx::SlideAnimation(this));
408 show_url_animation_->SetTweenType(kShowTweenType);
409 show_url_animation_->SetSlideDuration(200);
410
411 hide_url_animation_.reset(new gfx::SlideAnimation(this));
412 hide_url_animation_->SetTweenType(kHideTweenType);
413 hide_url_animation_->SetSlideDuration(175);
414
415 content::Source<Profile> profile_source = content::Source<Profile>(profile());
416 registrar_.Add(
417 this, chrome::NOTIFICATION_EXTENSION_LOADED_DEPRECATED, profile_source);
418 registrar_.Add(this,
419 chrome::NOTIFICATION_EXTENSION_UNLOADED_DEPRECATED,
420 profile_source);
421
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.
424 Update(NULL);
425 }
426
IsInitialized() const427 bool LocationBarView::IsInitialized() const {
428 return omnibox_view_ != NULL;
429 }
430
GetColor(ToolbarModel::SecurityLevel security_level,ColorKind kind) const431 SkColor LocationBarView::GetColor(ToolbarModel::SecurityLevel security_level,
432 ColorKind kind) const {
433 const ui::NativeTheme* native_theme = GetNativeTheme();
434 switch (kind) {
435 case BACKGROUND:
436 return native_theme->GetSystemColor(
437 ui::NativeTheme::kColorId_TextfieldDefaultBackground);
438
439 case TEXT:
440 return native_theme->GetSystemColor(
441 ui::NativeTheme::kColorId_TextfieldDefaultColor);
442
443 case SELECTED_TEXT:
444 return native_theme->GetSystemColor(
445 ui::NativeTheme::kColorId_TextfieldSelectionColor);
446
447 case DEEMPHASIZED_TEXT:
448 return color_utils::AlphaBlend(
449 GetColor(security_level, TEXT),
450 GetColor(security_level, BACKGROUND),
451 128);
452
453 case SECURITY_TEXT: {
454 SkColor color;
455 switch (security_level) {
456 case ToolbarModel::EV_SECURE:
457 case ToolbarModel::SECURE:
458 color = SkColorSetRGB(7, 149, 0);
459 break;
460
461 case ToolbarModel::SECURITY_WARNING:
462 case ToolbarModel::SECURITY_POLICY_WARNING:
463 return GetColor(security_level, DEEMPHASIZED_TEXT);
464 break;
465
466 case ToolbarModel::SECURITY_ERROR:
467 color = SkColorSetRGB(162, 0, 0);
468 break;
469
470 default:
471 NOTREACHED();
472 return GetColor(security_level, TEXT);
473 }
474 return color_utils::GetReadableColor(
475 color, GetColor(security_level, BACKGROUND));
476 }
477
478 default:
479 NOTREACHED();
480 return GetColor(security_level, TEXT);
481 }
482 }
483
ZoomChangedForActiveTab(bool can_show_bubble)484 void LocationBarView::ZoomChangedForActiveTab(bool can_show_bubble) {
485 DCHECK(zoom_view_);
486 if (RefreshZoomView()) {
487 Layout();
488 SchedulePaint();
489 }
490
491 WebContents* web_contents = GetWebContents();
492 if (can_show_bubble && zoom_view_->visible() && web_contents)
493 ZoomBubbleView::ShowBubble(web_contents, true);
494 }
495
SetPreviewEnabledPageAction(ExtensionAction * page_action,bool preview_enabled)496 void LocationBarView::SetPreviewEnabledPageAction(ExtensionAction* page_action,
497 bool preview_enabled) {
498 if (is_popup_mode_)
499 return;
500
501 DCHECK(page_action);
502 WebContents* web_contents = GetWebContents();
503
504 RefreshPageActionViews();
505 PageActionWithBadgeView* page_action_view =
506 static_cast<PageActionWithBadgeView*>(GetPageActionView(page_action));
507 DCHECK(page_action_view);
508 if (!page_action_view)
509 return;
510
511 page_action_view->image_view()->set_preview_enabled(preview_enabled);
512 page_action_view->UpdateVisibility(web_contents, GetToolbarModel()->GetURL());
513 Layout();
514 SchedulePaint();
515 }
516
GetPageActionView(ExtensionAction * page_action)517 PageActionWithBadgeView* LocationBarView::GetPageActionView(
518 ExtensionAction* page_action) {
519 DCHECK(page_action);
520 for (PageActionViews::const_iterator i(page_action_views_.begin());
521 i != page_action_views_.end(); ++i) {
522 if ((*i)->image_view()->page_action() == page_action)
523 return *i;
524 }
525 return NULL;
526 }
527
SetStarToggled(bool on)528 void LocationBarView::SetStarToggled(bool on) {
529 if (star_view_)
530 star_view_->SetToggled(on);
531 }
532
SetTranslateIconToggled(bool on)533 void LocationBarView::SetTranslateIconToggled(bool on) {
534 translate_icon_view_->SetToggled(on);
535 }
536
GetOmniboxViewOrigin() const537 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);
541 return origin;
542 }
543
SetImeInlineAutocompletion(const base::string16 & text)544 void LocationBarView::SetImeInlineAutocompletion(const base::string16& text) {
545 ime_inline_autocomplete_view_->SetText(text);
546 ime_inline_autocomplete_view_->SetVisible(!text.empty());
547 }
548
SetGrayTextAutocompletion(const base::string16 & text)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());
553 Layout();
554 SchedulePaint();
555 }
556 }
557
GetGrayTextAutocompletion() const558 base::string16 LocationBarView::GetGrayTextAutocompletion() const {
559 return HasValidSuggestText() ?
560 suggested_text_view_->text() : base::string16();
561 }
562
SetShowFocusRect(bool show)563 void LocationBarView::SetShowFocusRect(bool show) {
564 show_focus_rect_ = show;
565 SchedulePaint();
566 }
567
SelectAll()568 void LocationBarView::SelectAll() {
569 omnibox_view_->SelectAll(true);
570 }
571
GetLocationBarAnchorPoint() const572 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);
579 return point;
580 }
581
generated_credit_card_view()582 views::View* LocationBarView::generated_credit_card_view() {
583 return generated_credit_card_view_;
584 }
585
GetInternalHeight(bool use_preferred_size)586 int LocationBarView::GetInternalHeight(bool use_preferred_size) {
587 int total_height =
588 use_preferred_size ? GetPreferredSize().height() : height();
589 return std::max(total_height - (vertical_edge_thickness() * 2), 0);
590 }
591
GetOmniboxPopupPositioningInfo(gfx::Point * top_left_screen_coord,int * popup_width,int * left_margin,int * right_margin)592 void LocationBarView::GetOmniboxPopupPositioningInfo(
593 gfx::Point* top_left_screen_coord,
594 int* popup_width,
595 int* left_margin,
596 int* right_margin) {
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
601 // client edge.
602 *top_left_screen_coord = gfx::Point(
603 0,
604 parent()->height() - views::NonClientFrameView::kClientEdgeThickness);
605 views::View::ConvertPointToScreen(parent(), top_left_screen_coord);
606 *popup_width = parent()->width();
607
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();
612 }
613
614 ////////////////////////////////////////////////////////////////////////////////
615 // LocationBarView, public LocationBar implementation:
616
FocusLocation(bool select_all)617 void LocationBarView::FocusLocation(bool select_all) {
618 omnibox_view_->SetFocus();
619 if (select_all)
620 omnibox_view_->SelectAll(true);
621 }
622
Revert()623 void LocationBarView::Revert() {
624 omnibox_view_->RevertAll();
625 }
626
GetOmniboxView()627 OmniboxView* LocationBarView::GetOmniboxView() {
628 return omnibox_view_;
629 }
630
631 ////////////////////////////////////////////////////////////////////////////////
632 // LocationBarView, public views::View implementation:
633
HasFocus() const634 bool LocationBarView::HasFocus() const {
635 return omnibox_view_->model()->has_focus();
636 }
637
GetAccessibleState(ui::AXViewState * state)638 void LocationBarView::GetAccessibleState(ui::AXViewState* state) {
639 if (!IsInitialized())
640 return;
641
642 state->role = ui::AX_ROLE_LOCATION_BAR;
643 state->name = l10n_util::GetStringUTF16(IDS_ACCNAME_LOCATION);
644 state->value = omnibox_view_->GetText();
645
646 base::string16::size_type entry_start;
647 base::string16::size_type entry_end;
648 omnibox_view_->GetSelectionBounds(&entry_start, &entry_end);
649 state->selection_start = entry_start;
650 state->selection_end = entry_end;
651
652 if (is_popup_mode_) {
653 state->AddStateFlag(ui::AX_STATE_READ_ONLY);
654 } else {
655 state->set_value_callback =
656 base::Bind(&LocationBarView::AccessibilitySetValue,
657 weak_ptr_factory_.GetWeakPtr());
658 }
659 }
660
GetPreferredSize() const661 gfx::Size LocationBarView::GetPreferredSize() const {
662 // Compute minimum height.
663 gfx::Size min_size(border_painter_->GetMinimumSize());
664 if (!IsInitialized())
665 return min_size;
666 gfx::Size search_button_min_size(search_button_->GetMinimumSize());
667 min_size.SetToMax(search_button_min_size);
668
669 // Compute width of omnibox-leading content.
670 const int horizontal_edge_thickness = GetHorizontalEdgeThickness();
671 int leading_width = horizontal_edge_thickness;
672 // TODO(pkasting): Make the origin chip min width sane, and make the chip
673 // handle being shrunken down more gracefully; then uncomment this.
674 /*if (GetToolbarModel()->ShouldShowOriginChip())
675 leading_width += origin_chip_view_->GetMinimumSize().width();*/
676 if (ShouldShowKeywordBubble()) {
677 // The selected keyword view can collapse completely.
678 } else if (ShouldShowEVBubble()) {
679 leading_width += kBubblePadding +
680 ev_bubble_view_->GetMinimumSizeForLabelText(
681 GetToolbarModel()->GetEVCertName()).width();
682 } else if (!origin_chip_view_->visible()) {
683 leading_width +=
684 kItemPadding + location_icon_view_->GetMinimumSize().width();
685 }
686 leading_width += kItemPadding - GetEditLeadingInternalSpace();
687
688 // Compute width of omnibox-trailing content.
689 int trailing_width = search_button_->visible() ?
690 (search_button_->GetMinimumSize().width() + kSearchButtonInset) :
691 horizontal_edge_thickness;
692 trailing_width += IncrementalMinimumWidth(star_view_) +
693 IncrementalMinimumWidth(translate_icon_view_) +
694 IncrementalMinimumWidth(open_pdf_in_reader_view_) +
695 IncrementalMinimumWidth(manage_passwords_icon_view_) +
696 IncrementalMinimumWidth(zoom_view_) +
697 IncrementalMinimumWidth(generated_credit_card_view_) +
698 IncrementalMinimumWidth(mic_search_view_) +
699 IncrementalMinimumWidth(add_to_app_launcher_view_) + kItemPadding;
700 for (PageActionViews::const_iterator i(page_action_views_.begin());
701 i != page_action_views_.end(); ++i)
702 trailing_width += IncrementalMinimumWidth((*i));
703 for (ContentSettingViews::const_iterator i(content_setting_views_.begin());
704 i != content_setting_views_.end(); ++i)
705 trailing_width += IncrementalMinimumWidth((*i));
706
707 min_size.set_width(
708 leading_width + omnibox_view_->GetMinimumSize().width() + trailing_width);
709 return min_size;
710 }
711
Layout()712 void LocationBarView::Layout() {
713 if (!IsInitialized())
714 return;
715
716 origin_chip_view_->SetVisible(GetToolbarModel()->ShouldShowOriginChip());
717 selected_keyword_view_->SetVisible(false);
718 location_icon_view_->SetVisible(false);
719 ev_bubble_view_->SetVisible(false);
720 keyword_hint_view_->SetVisible(false);
721
722 LocationBarLayout leading_decorations(
723 LocationBarLayout::LEFT_EDGE,
724 kItemPadding - GetEditLeadingInternalSpace());
725 LocationBarLayout trailing_decorations(LocationBarLayout::RIGHT_EDGE,
726 kItemPadding);
727
728 const int origin_chip_preferred_width =
729 origin_chip_view_->GetPreferredSize().width();
730 const int origin_chip_width =
731 origin_chip_view_->visible() ? origin_chip_preferred_width : 0;
732 // Always give the origin chip view its desired size and lay it out, even when
733 // it's not visible, so we can calculate the correct animation values below
734 // when switching to tabs that have the origin chip hidden.
735 origin_chip_view_->SetBounds(0, 0, origin_chip_preferred_width, height());
736 origin_chip_view_->Layout();
737
738 const int bubble_location_y = vertical_edge_thickness() + kBubblePadding;
739 const base::string16 keyword(omnibox_view_->model()->keyword());
740 // In some cases (e.g. fullscreen mode) we may have 0 height. We still want
741 // to position our child views in this case, because other things may be
742 // positioned relative to them (e.g. the "bookmark added" bubble if the user
743 // hits ctrl-d).
744 const int location_height = GetInternalHeight(false);
745 const int bubble_height = std::max(location_height - (kBubblePadding * 2), 0);
746 if (ShouldShowKeywordBubble()) {
747 leading_decorations.AddDecoration(bubble_location_y, bubble_height, true, 0,
748 kBubblePadding, kItemPadding,
749 selected_keyword_view_);
750 if (selected_keyword_view_->keyword() != keyword) {
751 selected_keyword_view_->SetKeyword(keyword);
752 const TemplateURL* template_url =
753 TemplateURLServiceFactory::GetForProfile(profile())->
754 GetTemplateURLForKeyword(keyword);
755 if (template_url &&
756 (template_url->GetType() == TemplateURL::OMNIBOX_API_EXTENSION)) {
757 gfx::Image image = extensions::OmniboxAPI::Get(profile())->
758 GetOmniboxIcon(template_url->GetExtensionId());
759 selected_keyword_view_->SetImage(image.AsImageSkia());
760 selected_keyword_view_->set_is_extension_icon(true);
761 } else {
762 selected_keyword_view_->SetImage(
763 *(GetThemeProvider()->GetImageSkiaNamed(IDR_OMNIBOX_SEARCH)));
764 selected_keyword_view_->set_is_extension_icon(false);
765 }
766 }
767 } else if (ShouldShowEVBubble()) {
768 ev_bubble_view_->SetLabel(GetToolbarModel()->GetEVCertName());
769 // The largest fraction of the omnibox that can be taken by the EV bubble.
770 const double kMaxBubbleFraction = 0.5;
771 leading_decorations.AddDecoration(bubble_location_y, bubble_height, false,
772 kMaxBubbleFraction, kBubblePadding,
773 kItemPadding, ev_bubble_view_);
774 } else if (!origin_chip_view_->visible()) {
775 leading_decorations.AddDecoration(
776 vertical_edge_thickness(), location_height,
777 location_icon_view_);
778 }
779
780 if (star_view_->visible()) {
781 trailing_decorations.AddDecoration(
782 vertical_edge_thickness(), location_height, star_view_);
783 }
784 if (add_to_app_launcher_view_->visible()) {
785 trailing_decorations.AddDecoration(
786 vertical_edge_thickness(), location_height, add_to_app_launcher_view_);
787 }
788 if (translate_icon_view_->visible()) {
789 trailing_decorations.AddDecoration(
790 vertical_edge_thickness(), location_height, translate_icon_view_);
791 }
792 if (open_pdf_in_reader_view_->visible()) {
793 trailing_decorations.AddDecoration(
794 vertical_edge_thickness(), location_height, open_pdf_in_reader_view_);
795 }
796 if (manage_passwords_icon_view_->visible()) {
797 trailing_decorations.AddDecoration(vertical_edge_thickness(),
798 location_height,
799 manage_passwords_icon_view_);
800 }
801 for (PageActionViews::const_iterator i(page_action_views_.begin());
802 i != page_action_views_.end(); ++i) {
803 if ((*i)->visible()) {
804 trailing_decorations.AddDecoration(
805 vertical_edge_thickness(), location_height, (*i));
806 }
807 }
808 if (zoom_view_->visible()) {
809 trailing_decorations.AddDecoration(vertical_edge_thickness(),
810 location_height, zoom_view_);
811 }
812 for (ContentSettingViews::const_reverse_iterator i(
813 content_setting_views_.rbegin()); i != content_setting_views_.rend();
814 ++i) {
815 if ((*i)->visible()) {
816 trailing_decorations.AddDecoration(
817 bubble_location_y, bubble_height, false, 0, kItemPadding,
818 kItemPadding, (*i));
819 }
820 }
821 if (generated_credit_card_view_->visible()) {
822 trailing_decorations.AddDecoration(vertical_edge_thickness(),
823 location_height,
824 generated_credit_card_view_);
825 }
826 if (mic_search_view_->visible()) {
827 trailing_decorations.AddDecoration(vertical_edge_thickness(),
828 location_height, mic_search_view_);
829 }
830 // Because IMEs may eat the tab key, we don't show "press tab to search" while
831 // IME composition is in progress.
832 if (!keyword.empty() && omnibox_view_->model()->is_keyword_hint() &&
833 !omnibox_view_->IsImeComposing()) {
834 trailing_decorations.AddDecoration(vertical_edge_thickness(),
835 location_height, true, 0, kItemPadding,
836 kItemPadding, keyword_hint_view_);
837 if (keyword_hint_view_->keyword() != keyword)
838 keyword_hint_view_->SetKeyword(keyword);
839 }
840
841 // Perform layout.
842 const int horizontal_edge_thickness = GetHorizontalEdgeThickness();
843 int full_width = width() - horizontal_edge_thickness - origin_chip_width;
844
845 const gfx::Size search_button_size(search_button_->GetPreferredSize());
846 const int search_button_reserved_width =
847 search_button_size.width() + kSearchButtonInset;
848 full_width -= search_button_->visible() ?
849 search_button_reserved_width : horizontal_edge_thickness;
850 int entry_width = full_width;
851 leading_decorations.LayoutPass1(&entry_width);
852 trailing_decorations.LayoutPass1(&entry_width);
853 leading_decorations.LayoutPass2(&entry_width);
854 trailing_decorations.LayoutPass2(&entry_width);
855
856 int location_needed_width = omnibox_view_->GetTextWidth();
857 int available_width = entry_width - location_needed_width;
858 // The bounds must be wide enough for all the decorations to fit.
859 gfx::Rect location_bounds(
860 origin_chip_width + horizontal_edge_thickness, vertical_edge_thickness(),
861 std::max(full_width, full_width - entry_width), location_height);
862 leading_decorations.LayoutPass3(&location_bounds, &available_width);
863 trailing_decorations.LayoutPass3(&location_bounds, &available_width);
864
865 // Calculate the animation parameters (see comments on these members in the
866 // header). We have to do this in Layout, after |origin_chip_view_| is laid
867 // out, because that may affect the host label offset in the origin chip.
868 const base::string16& chip_text(origin_chip_view_->host_label_text());
869 // If the chip is clicked, the omnibox text will become the toolbar model's
870 // formatted URL. We can't ask the omnibox for its current text, because
871 // while the chip is visible the current text is empty.
872 size_t prefix_end = 0;
873 const base::string16& omnibox_text(
874 GetToolbarModel()->GetFormattedURL(&prefix_end));
875 // Do a case-insensitive search to better match cases like
876 // "Settings" <-> "chrome://settings". Skip any pre-hostname text.
877 size_t chip_text_offset = std::search(
878 omnibox_text.begin() + prefix_end, omnibox_text.end(),
879 chip_text.begin(), chip_text.end(),
880 base::CaseInsensitiveCompare<base::char16>()) - omnibox_text.begin();
881 // If we couldn't find the chip text, try checking whether the omnibox text
882 // starts with it, as is true for e.g. file: URLs.
883 if ((chip_text_offset >= omnibox_text.length()) &&
884 StartsWith(omnibox_text, chip_text, true))
885 chip_text_offset = 0;
886 const gfx::FontList& font_list = omnibox_view_->GetFontList();
887 const int chip_text_width = gfx::GetStringWidth(chip_text, font_list);
888 const int old_starting_offset = starting_omnibox_offset_;
889 const int old_starting_leading_inset = starting_omnibox_leading_inset_;
890 const int old_ending_width = ending_omnibox_width_;
891 starting_omnibox_offset_ = current_omnibox_offset_ = 0;
892 starting_omnibox_leading_inset_ = current_omnibox_leading_inset_ = 0;
893 ending_omnibox_width_ = gfx::GetStringWidth(omnibox_text, font_list);
894 if (chip_text_offset < omnibox_text.length()) {
895 if (base::i18n::IsRTL())
896 chip_text_offset += chip_text.length();
897 base::string16 extra_omnibox_text(base::i18n::IsRTL() ?
898 omnibox_text.substr(chip_text_offset) :
899 omnibox_text.substr(0, chip_text_offset));
900 starting_omnibox_leading_inset_ =
901 gfx::GetStringWidth(extra_omnibox_text, font_list);
902 starting_omnibox_offset_ = origin_chip_view_->HostLabelOffset() -
903 starting_omnibox_leading_inset_;
904 current_omnibox_width_ = chip_text_width;
905 } else {
906 // If the chip text wasn't found in the omnibox text, then instead of
907 // starting the show animation clipped to the "hostname", we'll start with
908 // the entire omnibox text visible, clipped to the remaining chip width, and
909 // only animate any necessary expansion of that width, without moving the
910 // omnibox bounds.
911 current_omnibox_width_ = origin_chip_view_->WidthFromStartOfLabels();
912 }
913
914 // End the animations immediately if the parameters have changed.
915 if ((starting_omnibox_offset_ != old_starting_offset) ||
916 (starting_omnibox_leading_inset_ != old_starting_leading_inset) ||
917 (ending_omnibox_width_ != old_ending_width))
918 EndOriginChipAnimations(true);
919
920 // Also end the animations immediately if there's nothing to animate (but do
921 // allow the chip to fade back in).
922 const ui::NativeTheme* native_theme = GetNativeTheme();
923 const SkColor ending_selection_text_color = native_theme->GetSystemColor(
924 ui::NativeTheme::kColorId_TextfieldSelectionColor);
925 const SkColor ending_selection_background_color =
926 native_theme->GetSystemColor(
927 ui::NativeTheme::kColorId_TextfieldSelectionBackgroundFocused);
928 if ((starting_omnibox_offset_ == 0) &&
929 (starting_omnibox_leading_inset_ == 0) &&
930 (ending_omnibox_width_ == chip_text_width) &&
931 (hide_url_animation_->is_animating() ||
932 ((ending_selection_text_color ==
933 origin_chip_view_->pressed_text_color()) &&
934 (ending_selection_background_color ==
935 origin_chip_view_->pressed_background_color()))))
936 EndOriginChipAnimations(false);
937
938 if (show_url_animation_->is_animating()) {
939 omnibox_view_->SetSelectionTextColor(gfx::Tween::ColorValueBetween(
940 show_url_animation_->GetCurrentValue(),
941 origin_chip_view_->pressed_text_color(),
942 ending_selection_text_color));
943 omnibox_view_->SetSelectionBackgroundColor(gfx::Tween::ColorValueBetween(
944 show_url_animation_->GetCurrentValue(),
945 origin_chip_view_->pressed_background_color(),
946 ending_selection_background_color));
947 current_omnibox_offset_ =
948 show_url_animation_->CurrentValueBetween(starting_omnibox_offset_, 0);
949 current_omnibox_leading_inset_ = show_url_animation_->CurrentValueBetween(
950 starting_omnibox_leading_inset_, 0);
951 current_omnibox_width_ = show_url_animation_->CurrentValueBetween(
952 chip_text_width, ending_omnibox_width_);
953 } else if (hide_url_animation_->is_animating()) {
954 current_omnibox_offset_ =
955 hide_url_animation_->CurrentValueBetween(0, starting_omnibox_offset_);
956 current_omnibox_leading_inset_ = hide_url_animation_->CurrentValueBetween(
957 0, starting_omnibox_leading_inset_);
958 current_omnibox_width_ = hide_url_animation_->CurrentValueBetween(
959 ending_omnibox_width_, chip_text_width);
960 }
961 // Contract |available_width| as necessary, but never expand it. This way,
962 // we'll never draw suggested text at first and then have it disappear
963 // midway through the animation.
964 if (current_omnibox_offset_ > 0)
965 available_width -= current_omnibox_offset_;
966 location_bounds.Inset(current_omnibox_offset_, 0, 0, 0);
967
968 // Layout out the suggested text view right aligned to the location
969 // entry. Only show the suggested text if we can fit the text from one
970 // character before the end of the selection to the end of the text and the
971 // suggested text. If we can't it means either the suggested text is too big,
972 // or the user has scrolled.
973
974 // TODO(sky): We could potentially adjust this to take into account suggested
975 // text to force using minimum size if necessary, but currently the chance of
976 // showing keyword hints and suggested text is minimal and we're not confident
977 // this is the right approach for suggested text.
978
979 int omnibox_view_margin = 0;
980 if (suggested_text_view_->visible()) {
981 // We do not display the suggested text when it contains a mix of RTL and
982 // LTR characters since this could mean the suggestion should be displayed
983 // in the middle of the string.
984 base::i18n::TextDirection text_direction =
985 base::i18n::GetStringDirection(omnibox_view_->GetText());
986 if (text_direction !=
987 base::i18n::GetStringDirection(suggested_text_view_->text()))
988 text_direction = base::i18n::UNKNOWN_DIRECTION;
989
990 // TODO(sky): need to layout when the user changes caret position.
991 gfx::Size suggested_text_size(suggested_text_view_->GetPreferredSize());
992 if (suggested_text_size.width() > available_width ||
993 text_direction == base::i18n::UNKNOWN_DIRECTION) {
994 // Hide the suggested text if the user has scrolled or we can't fit all
995 // the suggested text, or we have a mix of RTL and LTR characters.
996 suggested_text_view_->SetBounds(0, 0, 0, 0);
997 } else {
998 location_needed_width =
999 std::min(location_needed_width,
1000 location_bounds.width() - suggested_text_size.width());
1001 gfx::Rect suggested_text_bounds(location_bounds.x(), location_bounds.y(),
1002 suggested_text_size.width(),
1003 location_bounds.height());
1004 // TODO(sky): figure out why this needs the -1.
1005 suggested_text_bounds.Offset(location_needed_width - 1, 0);
1006
1007 // We reverse the order of the location entry and suggested text if:
1008 // - Chrome is RTL but the text is fully LTR, or
1009 // - Chrome is LTR but the text is fully RTL.
1010 // This ensures the suggested text is correctly displayed to the right
1011 // (or left) of the user text.
1012 if (text_direction == (base::i18n::IsRTL() ?
1013 base::i18n::LEFT_TO_RIGHT : base::i18n::RIGHT_TO_LEFT)) {
1014 // TODO(sky): Figure out why we need the +1.
1015 suggested_text_bounds.set_x(location_bounds.x() + 1);
1016 // Use a margin to prevent omnibox text from overlapping suggest text.
1017 omnibox_view_margin = suggested_text_bounds.width();
1018 }
1019 suggested_text_view_->SetBoundsRect(suggested_text_bounds);
1020 }
1021 }
1022
1023 const gfx::Insets insets = omnibox_view_->GetInsets();
1024 omnibox_view_->SetBorder(views::Border::CreateEmptyBorder(
1025 insets.top(), insets.left(), insets.bottom(), omnibox_view_margin));
1026
1027 // Layout |ime_inline_autocomplete_view_| next to the user input.
1028 if (ime_inline_autocomplete_view_->visible()) {
1029 int width =
1030 gfx::GetStringWidth(ime_inline_autocomplete_view_->text(),
1031 ime_inline_autocomplete_view_->font_list()) +
1032 ime_inline_autocomplete_view_->GetInsets().width();
1033 // All the target languages (IMEs) are LTR, and we do not need to support
1034 // RTL so far. In other words, no testable RTL environment so far.
1035 int x = location_needed_width;
1036 if (width > entry_width)
1037 x = 0;
1038 else if (location_needed_width + width > entry_width)
1039 x = entry_width - width;
1040 location_bounds.set_width(x);
1041 ime_inline_autocomplete_view_->SetBounds(
1042 location_bounds.right(), location_bounds.y(),
1043 std::min(width, entry_width), location_bounds.height());
1044 }
1045
1046 omnibox_view_->SetBoundsRect(location_bounds);
1047
1048 search_button_->SetBoundsRect(gfx::Rect(
1049 gfx::Point(width() - search_button_reserved_width, 0),
1050 search_button_size));
1051 }
1052
1053 ////////////////////////////////////////////////////////////////////////////////
1054 // LocationBarView, public OmniboxEditController implementation:
1055
Update(const WebContents * contents)1056 void LocationBarView::Update(const WebContents* contents) {
1057 mic_search_view_->SetVisible(
1058 !GetToolbarModel()->input_in_progress() && browser_ &&
1059 browser_->search_model()->voice_search_supported());
1060 RefreshContentSettingViews();
1061 generated_credit_card_view_->Update();
1062 ZoomBubbleView::CloseBubble();
1063 RefreshZoomView();
1064 RefreshPageActionViews();
1065 RefreshTranslateIcon();
1066 RefreshManagePasswordsIconView();
1067 content::WebContents* web_contents_for_sub_views =
1068 GetToolbarModel()->input_in_progress() ? NULL : GetWebContents();
1069 open_pdf_in_reader_view_->Update(web_contents_for_sub_views);
1070 add_to_app_launcher_view_->Update(web_contents_for_sub_views);
1071
1072 if (star_view_) {
1073 star_view_->SetVisible(
1074 browser_defaults::bookmarks_enabled && !is_popup_mode_ &&
1075 !GetToolbarModel()->input_in_progress() &&
1076 edit_bookmarks_enabled_.GetValue() &&
1077 !IsBookmarkStarHiddenByExtension());
1078 }
1079
1080 if (contents)
1081 omnibox_view_->OnTabChanged(contents);
1082 else
1083 omnibox_view_->Update();
1084
1085 OnChanged(); // NOTE: Calls Layout().
1086 }
1087
ShowURL()1088 void LocationBarView::ShowURL() {
1089 // Start the animation before calling ShowURL(), since the latter eventually
1090 // calls back to Layout(), and if the animation is not marked as "running",
1091 // we'll draw the omnibox in its final position briefly until the first
1092 // animation callback reaches us.
1093 if (chrome::ShouldDisplayOriginChip()) {
1094 // If we're currently hiding, reverse the hide by swapping to the show
1095 // animation, offset so that the text is in the same position.
1096 if (hide_url_animation_->is_animating()) {
1097 const double show_value = GetValueForAnimation(false);
1098 hide_url_animation_->Reset();
1099 show_url_animation_->Show();
1100 // This must be done after calling Show() and is not equivalent to
1101 // calling Reset(n) before Show(); Reset() would have caused the entire
1102 // animation curve (and time) to run between this value and the final
1103 // value, whereas Show() + SetCurrentValue() skips the animation forward
1104 // to the supplied value.
1105 show_url_animation_->SetCurrentValue(show_value);
1106 } else {
1107 show_url_animation_->Show();
1108 }
1109 }
1110 omnibox_view_->ShowURL();
1111 }
1112
EndOriginChipAnimations(bool cancel_fade)1113 void LocationBarView::EndOriginChipAnimations(bool cancel_fade) {
1114 show_url_animation_->End();
1115 hide_url_animation_->End();
1116 if (cancel_fade)
1117 origin_chip_view_->CancelFade();
1118 }
1119
GetToolbarModel()1120 ToolbarModel* LocationBarView::GetToolbarModel() {
1121 return delegate_->GetToolbarModel();
1122 }
1123
GetWebContents()1124 WebContents* LocationBarView::GetWebContents() {
1125 return delegate_->GetWebContents();
1126 }
1127
1128 ////////////////////////////////////////////////////////////////////////////////
1129 // LocationBarView, private:
1130
1131 // static
IncrementalMinimumWidth(views::View * view)1132 int LocationBarView::IncrementalMinimumWidth(views::View* view) {
1133 return view->visible() ? (kItemPadding + view->GetMinimumSize().width()) : 0;
1134 }
1135
GetHorizontalEdgeThickness() const1136 int LocationBarView::GetHorizontalEdgeThickness() const {
1137 // In maximized popup mode, there isn't any edge.
1138 return (is_popup_mode_ && browser_ && browser_->window() &&
1139 browser_->window()->IsMaximized()) ? 0 : vertical_edge_thickness();
1140 }
1141
RefreshContentSettingViews()1142 bool LocationBarView::RefreshContentSettingViews() {
1143 bool visibility_changed = false;
1144 for (ContentSettingViews::const_iterator i(content_setting_views_.begin());
1145 i != content_setting_views_.end(); ++i) {
1146 const bool was_visible = (*i)->visible();
1147 (*i)->Update(GetToolbarModel()->input_in_progress() ?
1148 NULL : GetWebContents());
1149 if (was_visible != (*i)->visible())
1150 visibility_changed = true;
1151 }
1152 return visibility_changed;
1153 }
1154
DeletePageActionViews()1155 void LocationBarView::DeletePageActionViews() {
1156 for (PageActionViews::const_iterator i(page_action_views_.begin());
1157 i != page_action_views_.end(); ++i)
1158 RemoveChildView(*i);
1159 STLDeleteElements(&page_action_views_);
1160 }
1161
RefreshPageActionViews()1162 bool LocationBarView::RefreshPageActionViews() {
1163 if (is_popup_mode_)
1164 return false;
1165
1166 bool changed = false;
1167
1168 // Remember the previous visibility of the page actions so that we can
1169 // notify when this changes.
1170 std::map<ExtensionAction*, bool> old_visibility;
1171 for (PageActionViews::const_iterator i(page_action_views_.begin());
1172 i != page_action_views_.end(); ++i) {
1173 old_visibility[(*i)->image_view()->page_action()] = (*i)->visible();
1174 }
1175
1176 PageActions new_page_actions;
1177
1178 WebContents* web_contents = GetWebContents();
1179 if (web_contents) {
1180 extensions::TabHelper* extensions_tab_helper =
1181 extensions::TabHelper::FromWebContents(web_contents);
1182 extensions::LocationBarController* controller =
1183 extensions_tab_helper->location_bar_controller();
1184 new_page_actions = controller->GetCurrentActions();
1185 }
1186
1187 // On startup we sometimes haven't loaded any extensions. This makes sure
1188 // we catch up when the extensions (and any page actions) load.
1189 if (page_actions_ != new_page_actions) {
1190 changed = true;
1191
1192 page_actions_.swap(new_page_actions);
1193 DeletePageActionViews(); // Delete the old views (if any).
1194
1195 // Create the page action views.
1196 for (PageActions::const_iterator i = page_actions_.begin();
1197 i != page_actions_.end(); ++i) {
1198 PageActionWithBadgeView* page_action_view = new PageActionWithBadgeView(
1199 delegate_->CreatePageActionImageView(this, *i));
1200 page_action_view->SetVisible(false);
1201 page_action_views_.push_back(page_action_view);
1202 }
1203
1204 // Move rightmost extensions to the start.
1205 std::stable_partition(
1206 page_action_views_.begin(),
1207 page_action_views_.end(),
1208 IsPageActionViewRightAligned(
1209 extensions::ExtensionSystem::Get(profile())->extension_service()));
1210
1211 View* right_anchor = open_pdf_in_reader_view_;
1212 if (!right_anchor)
1213 right_anchor = star_view_;
1214 DCHECK(right_anchor);
1215
1216 // |page_action_views_| are ordered right-to-left. Add them as children in
1217 // reverse order so the logical order and visual order match for
1218 // accessibility purposes.
1219 for (PageActionViews::reverse_iterator i = page_action_views_.rbegin();
1220 i != page_action_views_.rend(); ++i)
1221 AddChildViewAt(*i, GetIndexOf(right_anchor));
1222 }
1223
1224 if (!page_action_views_.empty() && web_contents) {
1225 Browser* browser = chrome::FindBrowserWithWebContents(web_contents);
1226 GURL url = browser->tab_strip_model()->GetActiveWebContents()->GetURL();
1227
1228 for (PageActionViews::const_iterator i(page_action_views_.begin());
1229 i != page_action_views_.end(); ++i) {
1230 (*i)->UpdateVisibility(
1231 GetToolbarModel()->input_in_progress() ? NULL : web_contents, url);
1232
1233 // Check if the visibility of the action changed and notify if it did.
1234 ExtensionAction* action = (*i)->image_view()->page_action();
1235 if (old_visibility.find(action) == old_visibility.end() ||
1236 old_visibility[action] != (*i)->visible()) {
1237 changed = true;
1238 content::NotificationService::current()->Notify(
1239 chrome::NOTIFICATION_EXTENSION_PAGE_ACTION_VISIBILITY_CHANGED,
1240 content::Source<ExtensionAction>(action),
1241 content::Details<WebContents>(web_contents));
1242 }
1243 }
1244 }
1245 return changed;
1246 }
1247
RefreshZoomView()1248 bool LocationBarView::RefreshZoomView() {
1249 DCHECK(zoom_view_);
1250 WebContents* web_contents = GetWebContents();
1251 if (!web_contents)
1252 return false;
1253 const bool was_visible = zoom_view_->visible();
1254 zoom_view_->Update(ZoomController::FromWebContents(web_contents));
1255 return was_visible != zoom_view_->visible();
1256 }
1257
RefreshTranslateIcon()1258 void LocationBarView::RefreshTranslateIcon() {
1259 if (!TranslateService::IsTranslateBubbleEnabled())
1260 return;
1261
1262 WebContents* web_contents = GetWebContents();
1263 if (!web_contents)
1264 return;
1265 LanguageState& language_state =
1266 ChromeTranslateClient::FromWebContents(web_contents)->GetLanguageState();
1267 bool enabled = language_state.translate_enabled();
1268 command_updater()->UpdateCommandEnabled(IDC_TRANSLATE_PAGE, enabled);
1269 translate_icon_view_->SetVisible(enabled);
1270 translate_icon_view_->SetToggled(language_state.IsPageTranslated());
1271 }
1272
RefreshManagePasswordsIconView()1273 bool LocationBarView::RefreshManagePasswordsIconView() {
1274 DCHECK(manage_passwords_icon_view_);
1275 WebContents* web_contents = GetWebContents();
1276 if (!web_contents)
1277 return false;
1278 const bool was_visible = manage_passwords_icon_view_->visible();
1279 ManagePasswordsUIController::FromWebContents(
1280 web_contents)->UpdateIconAndBubbleState(manage_passwords_icon_view_);
1281 return was_visible != manage_passwords_icon_view_->visible();
1282 }
1283
ShowFirstRunBubbleInternal()1284 void LocationBarView::ShowFirstRunBubbleInternal() {
1285 // First run bubble doesn't make sense for Chrome OS.
1286 #if !defined(OS_CHROMEOS)
1287 WebContents* web_contents = delegate_->GetWebContents();
1288 if (!web_contents)
1289 return;
1290 Browser* browser = chrome::FindBrowserWithWebContents(web_contents);
1291 if (browser)
1292 FirstRunBubble::ShowBubble(browser, location_icon_view_);
1293 #endif
1294 }
1295
AccessibilitySetValue(const base::string16 & new_value)1296 void LocationBarView::AccessibilitySetValue(const base::string16& new_value) {
1297 omnibox_view_->SetUserText(new_value, new_value, true);
1298 }
1299
HasValidSuggestText() const1300 bool LocationBarView::HasValidSuggestText() const {
1301 return suggested_text_view_->visible() &&
1302 !suggested_text_view_->size().IsEmpty();
1303 }
1304
ShouldShowKeywordBubble() const1305 bool LocationBarView::ShouldShowKeywordBubble() const {
1306 return !omnibox_view_->model()->keyword().empty() &&
1307 !omnibox_view_->model()->is_keyword_hint();
1308 }
1309
ShouldShowEVBubble() const1310 bool LocationBarView::ShouldShowEVBubble() const {
1311 return !chrome::ShouldDisplayOriginChip() &&
1312 (GetToolbarModel()->GetSecurityLevel(false) == ToolbarModel::EV_SECURE);
1313 }
1314
GetValueForAnimation(bool hide) const1315 double LocationBarView::GetValueForAnimation(bool hide) const {
1316 int calculated_offset;
1317 const gfx::Tween::Type tween_type = hide ? kHideTweenType : kShowTweenType;
1318 int start_offset = starting_omnibox_offset_, end_offset = 0;
1319 if (hide)
1320 std::swap(start_offset, end_offset);
1321 const int desired_offset = abs(current_omnibox_offset_);
1322 // Binary-search the value space (0 <= value <= 1) to find the appropriate
1323 // position. We only bother to iterate to within 1/64 of the desired value,
1324 // because the longer of the two animations will only run for twelve frames
1325 // anyway (200 ms * 60 Hz), so at this point we'll have a maximum error of
1326 // less than a fifth of an animation frame, which the user isn't going to
1327 // notice.
1328 //
1329 // We have to use this method because Tween::CalculateValue() is not
1330 // necessarily easily invertible. Luckily, this only runs when the user
1331 // reverses the animation (rare), and the limit on how many iterations we'll
1332 // do ensures the cost is unnoticeable.
1333 double value = 0.5;
1334 double step = value / 2;
1335 do {
1336 calculated_offset = abs(gfx::Tween::IntValueBetween(
1337 gfx::Tween::CalculateValue(tween_type, value), start_offset,
1338 end_offset));
1339 if (calculated_offset < desired_offset)
1340 value += step;
1341 else if (calculated_offset > desired_offset)
1342 value -= step;
1343 step /= 2;
1344 } while ((calculated_offset != desired_offset) && (step >= (1.0 / 64)));
1345 return value;
1346 }
1347
ResetShowAnimationAndColors()1348 void LocationBarView::ResetShowAnimationAndColors() {
1349 show_url_animation_->Reset();
1350 omnibox_view_->UseDefaultSelectionTextColor();
1351 omnibox_view_->UseDefaultSelectionBackgroundColor();
1352 }
1353
1354 ////////////////////////////////////////////////////////////////////////////////
1355 // LocationBarView, private LocationBar implementation:
1356
ShowFirstRunBubble()1357 void LocationBarView::ShowFirstRunBubble() {
1358 // Wait until search engines have loaded to show the first run bubble.
1359 TemplateURLService* url_service =
1360 TemplateURLServiceFactory::GetForProfile(profile());
1361 if (!url_service->loaded()) {
1362 template_url_service_ = url_service;
1363 template_url_service_->AddObserver(this);
1364 template_url_service_->Load();
1365 return;
1366 }
1367 ShowFirstRunBubbleInternal();
1368 }
1369
GetDestinationURL() const1370 GURL LocationBarView::GetDestinationURL() const {
1371 return destination_url();
1372 }
1373
GetWindowOpenDisposition() const1374 WindowOpenDisposition LocationBarView::GetWindowOpenDisposition() const {
1375 return disposition();
1376 }
1377
GetPageTransition() const1378 content::PageTransition LocationBarView::GetPageTransition() const {
1379 return transition();
1380 }
1381
AcceptInput()1382 void LocationBarView::AcceptInput() {
1383 omnibox_view_->model()->AcceptInput(CURRENT_TAB, false);
1384 }
1385
FocusSearch()1386 void LocationBarView::FocusSearch() {
1387 omnibox_view_->SetFocus();
1388 omnibox_view_->SetForcedQuery();
1389 }
1390
UpdateContentSettingsIcons()1391 void LocationBarView::UpdateContentSettingsIcons() {
1392 if (RefreshContentSettingViews()) {
1393 Layout();
1394 SchedulePaint();
1395 }
1396 }
1397
UpdateManagePasswordsIconAndBubble()1398 void LocationBarView::UpdateManagePasswordsIconAndBubble() {
1399 if (RefreshManagePasswordsIconView()) {
1400 Layout();
1401 SchedulePaint();
1402 }
1403 }
1404
UpdatePageActions()1405 void LocationBarView::UpdatePageActions() {
1406 size_t count_before = page_action_views_.size();
1407 bool changed = RefreshPageActionViews();
1408 if (page_action_views_.size() != count_before) {
1409 content::NotificationService::current()->Notify(
1410 chrome::NOTIFICATION_EXTENSION_PAGE_ACTION_COUNT_CHANGED,
1411 content::Source<LocationBar>(this),
1412 content::NotificationService::NoDetails());
1413 }
1414
1415 if (changed) {
1416 Layout();
1417 SchedulePaint();
1418 }
1419 }
1420
InvalidatePageActions()1421 void LocationBarView::InvalidatePageActions() {
1422 size_t count_before = page_action_views_.size();
1423 DeletePageActionViews();
1424 if (page_action_views_.size() != count_before) {
1425 content::NotificationService::current()->Notify(
1426 chrome::NOTIFICATION_EXTENSION_PAGE_ACTION_COUNT_CHANGED,
1427 content::Source<LocationBar>(this),
1428 content::NotificationService::NoDetails());
1429 }
1430 }
1431
UpdateOpenPDFInReaderPrompt()1432 void LocationBarView::UpdateOpenPDFInReaderPrompt() {
1433 open_pdf_in_reader_view_->Update(
1434 GetToolbarModel()->input_in_progress() ? NULL : GetWebContents());
1435 Layout();
1436 SchedulePaint();
1437 }
1438
UpdateGeneratedCreditCardView()1439 void LocationBarView::UpdateGeneratedCreditCardView() {
1440 generated_credit_card_view_->Update();
1441 Layout();
1442 SchedulePaint();
1443 }
1444
SaveStateToContents(WebContents * contents)1445 void LocationBarView::SaveStateToContents(WebContents* contents) {
1446 // If we're about to switch tabs, complete any current animations, so that if
1447 // the user is in the midst of hiding the URL, when he returns to this tab,
1448 // the URL will be hidden rather than shown.
1449 // NOTE: This must be called before SaveStateToTab().
1450 EndOriginChipAnimations(true);
1451 omnibox_view_->SaveStateToTab(contents);
1452 }
1453
GetOmniboxView() const1454 const OmniboxView* LocationBarView::GetOmniboxView() const {
1455 return omnibox_view_;
1456 }
1457
GetLocationBarForTesting()1458 LocationBarTesting* LocationBarView::GetLocationBarForTesting() {
1459 return this;
1460 }
1461
1462 ////////////////////////////////////////////////////////////////////////////////
1463 // LocationBarView, private LocationBarTesting implementation:
1464
PageActionCount()1465 int LocationBarView::PageActionCount() {
1466 return page_action_views_.size();
1467 }
1468
PageActionVisibleCount()1469 int LocationBarView::PageActionVisibleCount() {
1470 int result = 0;
1471 for (size_t i = 0; i < page_action_views_.size(); i++) {
1472 if (page_action_views_[i]->visible())
1473 ++result;
1474 }
1475 return result;
1476 }
1477
GetPageAction(size_t index)1478 ExtensionAction* LocationBarView::GetPageAction(size_t index) {
1479 if (index < page_action_views_.size())
1480 return page_action_views_[index]->image_view()->page_action();
1481
1482 NOTREACHED();
1483 return NULL;
1484 }
1485
GetVisiblePageAction(size_t index)1486 ExtensionAction* LocationBarView::GetVisiblePageAction(size_t index) {
1487 size_t current = 0;
1488 for (size_t i = 0; i < page_action_views_.size(); ++i) {
1489 if (page_action_views_[i]->visible()) {
1490 if (current == index)
1491 return page_action_views_[i]->image_view()->page_action();
1492
1493 ++current;
1494 }
1495 }
1496
1497 NOTREACHED();
1498 return NULL;
1499 }
1500
TestPageActionPressed(size_t index)1501 void LocationBarView::TestPageActionPressed(size_t index) {
1502 size_t current = 0;
1503 for (size_t i = 0; i < page_action_views_.size(); ++i) {
1504 if (page_action_views_[i]->visible()) {
1505 if (current == index) {
1506 page_action_views_[i]->image_view()->ExecuteAction(
1507 ExtensionPopup::SHOW);
1508 return;
1509 }
1510 ++current;
1511 }
1512 }
1513
1514 NOTREACHED();
1515 }
1516
GetBookmarkStarVisibility()1517 bool LocationBarView::GetBookmarkStarVisibility() {
1518 DCHECK(star_view_);
1519 return star_view_->visible();
1520 }
1521
1522 ////////////////////////////////////////////////////////////////////////////////
1523 // LocationBarView, private views::View implementation:
1524
GetClassName() const1525 const char* LocationBarView::GetClassName() const {
1526 return kViewClassName;
1527 }
1528
OnBoundsChanged(const gfx::Rect & previous_bounds)1529 void LocationBarView::OnBoundsChanged(const gfx::Rect& previous_bounds) {
1530 InstantServiceFactory::GetForProfile(profile())->OnOmniboxStartMarginChanged(
1531 bounds().x());
1532
1533 OmniboxPopupView* popup = omnibox_view_->model()->popup_model()->view();
1534 if (popup->IsOpen())
1535 popup->UpdatePopupAppearance();
1536 }
1537
OnFocus()1538 void LocationBarView::OnFocus() {
1539 // Explicitly focus the omnibox so a focus ring will be displayed around it on
1540 // Windows.
1541 omnibox_view_->SetFocus();
1542 }
1543
OnPaint(gfx::Canvas * canvas)1544 void LocationBarView::OnPaint(gfx::Canvas* canvas) {
1545 View::OnPaint(canvas);
1546
1547 // Fill the location bar background color behind the border. Parts of the
1548 // border images are meant to rest atop the toolbar background and parts atop
1549 // the omnibox background, so we can't just blindly fill our entire bounds.
1550 gfx::Rect bounds(GetContentsBounds());
1551 bounds.Inset(GetHorizontalEdgeThickness(), vertical_edge_thickness());
1552 SkColor color(GetColor(ToolbarModel::NONE, BACKGROUND));
1553 if (is_popup_mode_) {
1554 canvas->FillRect(bounds, color);
1555 } else {
1556 SkPaint paint;
1557 paint.setStyle(SkPaint::kFill_Style);
1558 paint.setColor(color);
1559 const int kBorderCornerRadius = 2;
1560 canvas->DrawRoundRect(bounds, kBorderCornerRadius, paint);
1561 }
1562
1563 // The border itself will be drawn in PaintChildren() since it includes an
1564 // inner shadow which should be drawn over the contents.
1565 }
1566
PaintChildren(gfx::Canvas * canvas,const views::CullSet & cull_set)1567 void LocationBarView::PaintChildren(gfx::Canvas* canvas,
1568 const views::CullSet& cull_set) {
1569 // Paint all the children except for the omnibox itself, which may need to be
1570 // clipped if it's animating in, and the origin chip and the search button,
1571 // which will be painted after the border.
1572 for (int i = 0, count = child_count(); i < count; ++i) {
1573 views::View* child = child_at(i);
1574 if (!child->layer() && (child != omnibox_view_) &&
1575 (child != origin_chip_view_) && (child != search_button_))
1576 child->Paint(canvas, cull_set);
1577 }
1578
1579 {
1580 gfx::ScopedCanvas scoped_canvas(canvas);
1581 if (show_url_animation_->is_animating() ||
1582 hide_url_animation_->is_animating()) {
1583 gfx::Rect clip_rect(omnibox_view_->bounds());
1584 clip_rect.Inset(current_omnibox_leading_inset_, 0, 0, 0);
1585 clip_rect.set_width(current_omnibox_width_);
1586 clip_rect.set_x(GetMirroredXForRect(clip_rect));
1587 canvas->ClipRect(clip_rect);
1588 }
1589 omnibox_view_->Paint(canvas, cull_set);
1590 }
1591
1592 // For non-InstantExtendedAPI cases, if necessary, show focus rect. As we need
1593 // the focus rect to appear on top of children we paint here rather than
1594 // OnPaint().
1595 // Note: |Canvas::DrawFocusRect| paints a dashed rect with gray color.
1596 if (show_focus_rect_ && HasFocus())
1597 canvas->DrawFocusRect(omnibox_view_->bounds());
1598
1599 // Maximized popup windows don't draw the horizontal edges. We implement this
1600 // by simply expanding the paint area outside the view by the edge thickness.
1601 gfx::Rect border_rect(GetContentsBounds());
1602 if (is_popup_mode_ && (GetHorizontalEdgeThickness() == 0))
1603 border_rect.Inset(-kPopupEdgeThickness, 0);
1604 views::Painter::PaintPainterAt(canvas, border_painter_.get(), border_rect);
1605
1606 // The origin chip and the search button must be painted after the border so
1607 // that the border shadow is not drawn over them.
1608 origin_chip_view_->Paint(canvas, cull_set);
1609 search_button_->Paint(canvas, cull_set);
1610 }
1611
1612 ////////////////////////////////////////////////////////////////////////////////
1613 // LocationBarView, private views::ButtonListener implementation:
1614
ButtonPressed(views::Button * sender,const ui::Event & event)1615 void LocationBarView::ButtonPressed(views::Button* sender,
1616 const ui::Event& event) {
1617 if (sender == mic_search_view_) {
1618 command_updater()->ExecuteCommand(IDC_TOGGLE_SPEECH_INPUT);
1619 return;
1620 }
1621
1622 DCHECK_EQ(search_button_, sender);
1623 // TODO(pkasting): When macourteau adds UMA stats for this, wire them up here.
1624 omnibox_view_->model()->AcceptInput(
1625 ui::DispositionFromEventFlags(event.flags()), false);
1626 }
1627
1628 ////////////////////////////////////////////////////////////////////////////////
1629 // LocationBarView, private views::DragController implementation:
1630
WriteDragDataForView(views::View * sender,const gfx::Point & press_pt,OSExchangeData * data)1631 void LocationBarView::WriteDragDataForView(views::View* sender,
1632 const gfx::Point& press_pt,
1633 OSExchangeData* data) {
1634 DCHECK_NE(GetDragOperationsForView(sender, press_pt),
1635 ui::DragDropTypes::DRAG_NONE);
1636
1637 WebContents* web_contents = GetWebContents();
1638 FaviconTabHelper* favicon_tab_helper =
1639 FaviconTabHelper::FromWebContents(web_contents);
1640 gfx::ImageSkia favicon = favicon_tab_helper->GetFavicon().AsImageSkia();
1641 button_drag_utils::SetURLAndDragImage(web_contents->GetURL(),
1642 web_contents->GetTitle(),
1643 favicon,
1644 NULL,
1645 data,
1646 sender->GetWidget());
1647 }
1648
GetDragOperationsForView(views::View * sender,const gfx::Point & p)1649 int LocationBarView::GetDragOperationsForView(views::View* sender,
1650 const gfx::Point& p) {
1651 DCHECK((sender == location_icon_view_) || (sender == ev_bubble_view_) ||
1652 (sender == origin_chip_view_));
1653 WebContents* web_contents = delegate_->GetWebContents();
1654 return (web_contents && web_contents->GetURL().is_valid() &&
1655 (!GetOmniboxView()->IsEditingOrEmpty() ||
1656 sender == origin_chip_view_)) ?
1657 (ui::DragDropTypes::DRAG_COPY | ui::DragDropTypes::DRAG_LINK) :
1658 ui::DragDropTypes::DRAG_NONE;
1659 }
1660
CanStartDragForView(View * sender,const gfx::Point & press_pt,const gfx::Point & p)1661 bool LocationBarView::CanStartDragForView(View* sender,
1662 const gfx::Point& press_pt,
1663 const gfx::Point& p) {
1664 return true;
1665 }
1666
1667 ////////////////////////////////////////////////////////////////////////////////
1668 // LocationBarView, private OmniboxEditController implementation:
1669
OnChanged()1670 void LocationBarView::OnChanged() {
1671 int icon_id = omnibox_view_->GetIcon();
1672 location_icon_view_->SetImage(GetThemeProvider()->GetImageSkiaNamed(icon_id));
1673 location_icon_view_->ShowTooltip(!GetOmniboxView()->IsEditingOrEmpty());
1674
1675 ToolbarModel* toolbar_model = GetToolbarModel();
1676 chrome::DisplaySearchButtonConditions conditions =
1677 chrome::GetDisplaySearchButtonConditions();
1678 bool meets_conditions =
1679 (conditions == chrome::DISPLAY_SEARCH_BUTTON_ALWAYS) ||
1680 ((conditions != chrome::DISPLAY_SEARCH_BUTTON_NEVER) &&
1681 (toolbar_model->WouldPerformSearchTermReplacement(true) ||
1682 ((conditions == chrome::DISPLAY_SEARCH_BUTTON_FOR_STR_OR_IIP) &&
1683 toolbar_model->input_in_progress())));
1684 search_button_->SetVisible(!is_popup_mode_ && meets_conditions);
1685 search_button_->UpdateIcon(icon_id == IDR_OMNIBOX_SEARCH);
1686
1687 origin_chip_view_->OnChanged();
1688
1689 Layout();
1690 SchedulePaint();
1691 }
1692
OnSetFocus()1693 void LocationBarView::OnSetFocus() {
1694 GetFocusManager()->SetFocusedView(this);
1695 }
1696
GetInstant()1697 InstantController* LocationBarView::GetInstant() {
1698 return delegate_->GetInstant();
1699 }
1700
GetToolbarModel() const1701 const ToolbarModel* LocationBarView::GetToolbarModel() const {
1702 return delegate_->GetToolbarModel();
1703 }
1704
HideURL()1705 void LocationBarView::HideURL() {
1706 DCHECK(chrome::ShouldDisplayOriginChip());
1707
1708 // If we're currently showing, reverse the hide by swapping to the hide
1709 // animation, offset so that the text is in the same position.
1710 if (show_url_animation_->is_animating()) {
1711 const double hide_value = GetValueForAnimation(true);
1712 ResetShowAnimationAndColors();
1713 hide_url_animation_->Show();
1714 // This must be done after calling Show() and is not equivalent to Reset(n);
1715 // see comments in ShowURL().
1716 hide_url_animation_->SetCurrentValue(hide_value);
1717 } else {
1718 hide_url_animation_->Show();
1719 }
1720 }
1721
1722 ////////////////////////////////////////////////////////////////////////////////
1723 // LocationBarView, private DropdownBarHostDelegate implementation:
1724
SetFocusAndSelection(bool select_all)1725 void LocationBarView::SetFocusAndSelection(bool select_all) {
1726 FocusLocation(select_all);
1727 }
1728
SetAnimationOffset(int offset)1729 void LocationBarView::SetAnimationOffset(int offset) {
1730 dropdown_animation_offset_ = offset;
1731 }
1732
1733 ////////////////////////////////////////////////////////////////////////////////
1734 // LocationBarView, private gfx::AnimationDelegate implementation:
1735
AnimationProgressed(const gfx::Animation * animation)1736 void LocationBarView::AnimationProgressed(const gfx::Animation* animation) {
1737 DCHECK((animation == show_url_animation_.get()) ||
1738 (animation == hide_url_animation_.get()));
1739 Layout();
1740 SchedulePaint();
1741 }
1742
AnimationEnded(const gfx::Animation * animation)1743 void LocationBarView::AnimationEnded(const gfx::Animation* animation) {
1744 if (animation == show_url_animation_.get()) {
1745 ResetShowAnimationAndColors();
1746 Layout();
1747 SchedulePaint();
1748 } else {
1749 DCHECK(animation == hide_url_animation_.get());
1750 hide_url_animation_->Reset();
1751 origin_chip_view_->FadeIn();
1752 omnibox_view_->HideURL(); // Calls OnChanged(), triggering layout.
1753 }
1754 }
1755
1756 ////////////////////////////////////////////////////////////////////////////////
1757 // LocationBarView, private TemplateURLServiceObserver implementation:
1758
OnTemplateURLServiceChanged()1759 void LocationBarView::OnTemplateURLServiceChanged() {
1760 template_url_service_->RemoveObserver(this);
1761 template_url_service_ = NULL;
1762 // If the browser is no longer active, let's not show the info bubble, as this
1763 // would make the browser the active window again.
1764 if (omnibox_view_ && omnibox_view_->GetWidget()->IsActive())
1765 ShowFirstRunBubble();
1766 }
1767
1768 ////////////////////////////////////////////////////////////////////////////////
1769 // LocationBarView, private content::NotificationObserver implementation:
1770
Observe(int type,const content::NotificationSource & source,const content::NotificationDetails & details)1771 void LocationBarView::Observe(int type,
1772 const content::NotificationSource& source,
1773 const content::NotificationDetails& details) {
1774 switch (type) {
1775 case chrome::NOTIFICATION_EXTENSION_LOADED_DEPRECATED:
1776 case chrome::NOTIFICATION_EXTENSION_UNLOADED_DEPRECATED:
1777 Update(NULL);
1778 break;
1779
1780 default:
1781 NOTREACHED() << "Unexpected notification.";
1782 }
1783 }
1784
1785 ////////////////////////////////////////////////////////////////////////////////
1786 // LocationBarView, private SearchModelObserver implementation:
1787
ModelChanged(const SearchModel::State & old_state,const SearchModel::State & new_state)1788 void LocationBarView::ModelChanged(const SearchModel::State& old_state,
1789 const SearchModel::State& new_state) {
1790 const bool visible = !GetToolbarModel()->input_in_progress() &&
1791 new_state.voice_search_supported;
1792 if (mic_search_view_->visible() != visible) {
1793 mic_search_view_->SetVisible(visible);
1794 Layout();
1795 }
1796 }
1797
1798