location_bar_view.h revision 4e180b6a0b4720a9b8e9e959a882386f690f08ff
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#ifndef CHROME_BROWSER_UI_VIEWS_LOCATION_BAR_LOCATION_BAR_VIEW_H_
6#define CHROME_BROWSER_UI_VIEWS_LOCATION_BAR_LOCATION_BAR_VIEW_H_
7
8#include <string>
9#include <vector>
10
11#include "base/compiler_specific.h"
12#include "base/memory/weak_ptr.h"
13#include "base/prefs/pref_member.h"
14#include "chrome/browser/extensions/extension_context_menu_model.h"
15#include "chrome/browser/search_engines/template_url_service_observer.h"
16#include "chrome/browser/ui/omnibox/location_bar.h"
17#include "chrome/browser/ui/omnibox/omnibox_edit_controller.h"
18#include "chrome/browser/ui/search/search_model_observer.h"
19#include "chrome/browser/ui/toolbar/toolbar_model.h"
20#include "chrome/browser/ui/views/dropdown_bar_host.h"
21#include "chrome/browser/ui/views/dropdown_bar_host_delegate.h"
22#include "chrome/browser/ui/views/extensions/extension_popup.h"
23#include "content/public/browser/notification_observer.h"
24#include "content/public/browser/notification_registrar.h"
25#include "ui/gfx/font.h"
26#include "ui/gfx/rect.h"
27#include "ui/views/controls/button/button.h"
28#include "ui/views/controls/native/native_view_host.h"
29#include "ui/views/drag_controller.h"
30
31#if defined(USE_AURA)
32#include "ui/compositor/layer_animation_observer.h"
33#endif
34
35class ActionBoxButtonView;
36class CommandUpdater;
37class ContentSettingBubbleModelDelegate;
38class ContentSettingImageView;
39class EVBubbleView;
40class ExtensionAction;
41class GURL;
42class GeneratedCreditCardView;
43class InstantController;
44class KeywordHintView;
45class LocationIconView;
46class OpenPDFInReaderView;
47class PageActionWithBadgeView;
48class PageActionImageView;
49class Profile;
50class ScriptBubbleIconView;
51class SelectedKeywordView;
52class StarView;
53class TemplateURLService;
54class ZoomView;
55
56namespace views {
57class BubbleDelegateView;
58class ImageButton;
59class Label;
60class Widget;
61}
62
63/////////////////////////////////////////////////////////////////////////////
64//
65// LocationBarView class
66//
67//   The LocationBarView class is a View subclass that paints the background
68//   of the URL bar strip and contains its content.
69//
70/////////////////////////////////////////////////////////////////////////////
71class LocationBarView : public LocationBar,
72                        public LocationBarTesting,
73                        public views::View,
74                        public views::ButtonListener,
75                        public views::DragController,
76                        public OmniboxEditController,
77                        public DropdownBarHostDelegate,
78                        public TemplateURLServiceObserver,
79                        public content::NotificationObserver,
80                        public SearchModelObserver {
81 public:
82  // The location bar view's class name.
83  static const char kViewClassName[];
84
85  // DropdownBarHostDelegate:
86  virtual void SetFocusAndSelection(bool select_all) OVERRIDE;
87  virtual void SetAnimationOffset(int offset) OVERRIDE;
88
89  // Returns the offset used while animating.
90  int animation_offset() const { return animation_offset_; }
91
92  class Delegate {
93   public:
94    // Should return the current web contents.
95    virtual content::WebContents* GetWebContents() = 0;
96
97    // Returns the InstantController, or NULL if there isn't one.
98    virtual InstantController* GetInstant() = 0;
99
100    virtual ToolbarModel* GetToolbarModel() = 0;
101    virtual const ToolbarModel* GetToolbarModel() const = 0;
102
103    // Creates Widget for the given delegate.
104    virtual views::Widget* CreateViewsBubble(
105        views::BubbleDelegateView* bubble_delegate) = 0;
106
107    // Creates PageActionImageView. Caller gets an ownership.
108    virtual PageActionImageView* CreatePageActionImageView(
109        LocationBarView* owner,
110        ExtensionAction* action) = 0;
111
112    // Returns ContentSettingBubbleModelDelegate.
113    virtual ContentSettingBubbleModelDelegate*
114        GetContentSettingBubbleModelDelegate() = 0;
115
116    // Shows permissions and settings for the given web contents.
117    virtual void ShowWebsiteSettings(content::WebContents* web_contents,
118                                     const GURL& url,
119                                     const content::SSLStatus& ssl) = 0;
120
121   protected:
122    virtual ~Delegate() {}
123  };
124
125  enum ColorKind {
126    BACKGROUND = 0,
127    TEXT,
128    SELECTED_TEXT,
129    DEEMPHASIZED_TEXT,
130    SECURITY_TEXT,
131  };
132
133  LocationBarView(Browser* browser,
134                  Profile* profile,
135                  CommandUpdater* command_updater,
136                  Delegate* delegate,
137                  bool is_popup_mode);
138
139  virtual ~LocationBarView();
140
141  // Uses GetBuiltInHorizontalPaddingForChildViews() to optionally add
142  // additional padding (via an empty border) to |view|. This should be called
143  // during creation on all child views which are potentially touchable so that
144  // when touch is enabled they will have sufficient padding.
145  static void InitTouchableLocationBarChildView(views::View* view);
146
147  // Initializes the LocationBarView.
148  void Init();
149
150  // True if this instance has been initialized by calling Init, which can only
151  // be called when the receiving instance is attached to a view container.
152  bool IsInitialized() const;
153
154  // Returns the appropriate color for the desired kind, based on the user's
155  // system theme.
156  SkColor GetColor(ToolbarModel::SecurityLevel security_level,
157                   ColorKind kind) const;
158
159  // Returns corresponding profile.
160  Profile* profile() const { return profile_; }
161
162  // Returns the delegate.
163  Delegate* delegate() const { return delegate_; }
164
165  // See comment in browser_window.h for more info.
166  void ZoomChangedForActiveTab(bool can_show_bubble);
167
168  // The zoom icon view. It may not be visible.
169  ZoomView* zoom_view() { return zoom_view_; }
170
171  // Sets |preview_enabled| for the PageAction View associated with this
172  // |page_action|. If |preview_enabled| is true, the view will display the
173  // PageActions icon even though it has not been activated by the extension.
174  // This is used by the ExtensionInstalledBubble to preview what the icon
175  // will look like for the user upon installation of the extension.
176  void SetPreviewEnabledPageAction(ExtensionAction* page_action,
177                                   bool preview_enabled);
178
179  // Retrieves the PageAction View which is associated with |page_action|.
180  views::View* GetPageActionView(ExtensionAction* page_action);
181
182  // Toggles the star on or off.
183  void SetStarToggled(bool on);
184
185  // Returns the star view. It may not be visible.
186  StarView* star_view() { return star_view_; }
187
188  // Shows the bookmark prompt.
189  void ShowBookmarkPrompt();
190
191  // Returns the screen coordinates of the location entry (where the URL text
192  // appears, not where the icons are shown).
193  gfx::Point GetLocationEntryOrigin() const;
194
195  // Shows |text| as an inline autocompletion.  This is useful for IMEs, where
196  // we can't show the autocompletion inside the actual OmniboxView.  See
197  // comments on |ime_inline_autocomplete_view_|.
198  void SetImeInlineAutocompletion(const string16& text);
199
200  // Invoked from OmniboxViewWin to show gray text autocompletion.
201  void SetGrayTextAutocompletion(const string16& text);
202
203  // Returns the current gray text autocompletion.
204  string16 GetGrayTextAutocompletion() const;
205
206  // Sets whether the location entry can accept focus.
207  void SetLocationEntryFocusable(bool focusable);
208
209  // Returns true if the location entry is focusable and visible in
210  // the root view.
211  bool IsLocationEntryFocusableInRootView() const;
212
213  // Sizing functions
214  virtual gfx::Size GetPreferredSize() OVERRIDE;
215
216  // Layout and Painting functions
217  virtual void Layout() OVERRIDE;
218  virtual void OnPaint(gfx::Canvas* canvas) OVERRIDE;
219
220  // No focus border for the location bar, the caret is enough.
221  virtual void OnPaintFocusBorder(gfx::Canvas* canvas) OVERRIDE { }
222
223  // Set if we should show a focus rect while the location entry field is
224  // focused. Used when the toolbar is in full keyboard accessibility mode.
225  // Repaints if necessary.
226  virtual void SetShowFocusRect(bool show);
227
228  // Select all of the text. Needed when the user tabs through controls
229  // in the toolbar in full keyboard accessibility mode.
230  virtual void SelectAll();
231
232#if defined(OS_WIN) && !defined(USE_AURA)
233  // Event Handlers
234  virtual bool OnMousePressed(const ui::MouseEvent& event) OVERRIDE;
235  virtual bool OnMouseDragged(const ui::MouseEvent& event) OVERRIDE;
236  virtual void OnMouseReleased(const ui::MouseEvent& event) OVERRIDE;
237  virtual void OnMouseCaptureLost() OVERRIDE;
238#endif
239
240  LocationIconView* location_icon_view() { return location_icon_view_; }
241  const LocationIconView* location_icon_view() const {
242    return location_icon_view_;
243  }
244
245  views::View* location_entry_view() const { return location_entry_view_; }
246
247  views::View* generated_credit_card_view();
248
249  // OmniboxEditController:
250  virtual void Update(const content::WebContents* contents) OVERRIDE;
251  virtual void OnChanged() OVERRIDE;
252  virtual void OnSetFocus() OVERRIDE;
253  virtual InstantController* GetInstant() OVERRIDE;
254  virtual content::WebContents* GetWebContents() OVERRIDE;
255  virtual ToolbarModel* GetToolbarModel() OVERRIDE;
256  virtual const ToolbarModel* GetToolbarModel() const OVERRIDE;
257
258  // views::View:
259  virtual const char* GetClassName() const OVERRIDE;
260  virtual bool SkipDefaultKeyEventProcessing(
261      const ui::KeyEvent& event) OVERRIDE;
262  virtual void GetAccessibleState(ui::AccessibleViewState* state) OVERRIDE;
263  virtual bool HasFocus() const OVERRIDE;
264  virtual void OnBoundsChanged(const gfx::Rect& previous_bounds) OVERRIDE;
265
266  // views::ButtonListener:
267  virtual void ButtonPressed(views::Button* sender,
268                             const ui::Event& event) OVERRIDE;
269
270  // views::DragController:
271  virtual void WriteDragDataForView(View* sender,
272                                    const gfx::Point& press_pt,
273                                    OSExchangeData* data) OVERRIDE;
274  virtual int GetDragOperationsForView(View* sender,
275                                       const gfx::Point& p) OVERRIDE;
276  virtual bool CanStartDragForView(View* sender,
277                                   const gfx::Point& press_pt,
278                                   const gfx::Point& p) OVERRIDE;
279
280  // LocationBar:
281  virtual void ShowFirstRunBubble() OVERRIDE;
282  virtual GURL GetDestinationURL() const OVERRIDE;
283  virtual WindowOpenDisposition GetWindowOpenDisposition() const OVERRIDE;
284  virtual content::PageTransition GetPageTransition() const OVERRIDE;
285  virtual void AcceptInput() OVERRIDE;
286  virtual void FocusLocation(bool select_all) OVERRIDE;
287  virtual void FocusSearch() OVERRIDE;
288  virtual void UpdateContentSettingsIcons() OVERRIDE;
289  virtual void UpdatePageActions() OVERRIDE;
290  virtual void InvalidatePageActions() OVERRIDE;
291  virtual void UpdateOpenPDFInReaderPrompt() OVERRIDE;
292  virtual void UpdateGeneratedCreditCardView() OVERRIDE;
293  virtual void SaveStateToContents(content::WebContents* contents) OVERRIDE;
294  virtual void Revert() OVERRIDE;
295  virtual const OmniboxView* GetLocationEntry() const OVERRIDE;
296  virtual OmniboxView* GetLocationEntry() OVERRIDE;
297  virtual LocationBarTesting* GetLocationBarForTesting() OVERRIDE;
298
299  // LocationBarTesting:
300  virtual int PageActionCount() OVERRIDE;
301  virtual int PageActionVisibleCount() OVERRIDE;
302  virtual ExtensionAction* GetPageAction(size_t index) OVERRIDE;
303  virtual ExtensionAction* GetVisiblePageAction(size_t index) OVERRIDE;
304  virtual void TestPageActionPressed(size_t index) OVERRIDE;
305  virtual bool GetBookmarkStarVisibility() OVERRIDE;
306
307  // TemplateURLServiceObserver:
308  virtual void OnTemplateURLServiceChanged() OVERRIDE;
309
310  // content::NotificationObserver:
311  virtual void Observe(int type,
312                       const content::NotificationSource& source,
313                       const content::NotificationDetails& details) OVERRIDE;
314
315  // SearchModelObserver:
316  virtual void ModelChanged(const SearchModel::State& old_state,
317                            const SearchModel::State& new_state) OVERRIDE;
318
319  // Returns the height of the control without the top and bottom
320  // edges(i.e.  the height of the edit control inside).  If
321  // |use_preferred_size| is true this will be the preferred height,
322  // otherwise it will be the current height.
323  int GetInternalHeight(bool use_preferred_size);
324
325  // Returns the position and width that the popup should be, and also the left
326  // edge that the results should align themselves to (which will leave some
327  // border on the left of the popup).
328  void GetOmniboxPopupPositioningInfo(gfx::Point* top_left_screen_coord,
329                                      int* popup_width,
330                                      int* left_margin,
331                                      int* right_margin);
332
333  // Space between items in the location bar, as well as between items and the
334  // edges.
335  static int GetItemPadding();
336
337  // Thickness of the edges of the omnibox background images, in normal mode.
338  static const int kNormalEdgeThickness;
339  // The same, but for popup mode.
340  static const int kPopupEdgeThickness;
341  // Amount of padding built into the standard omnibox icons.
342  static const int kIconInternalPadding;
343  // Space between the edge and a bubble.
344  static const int kBubblePadding;
345
346 protected:
347  virtual void OnFocus() OVERRIDE;
348
349 private:
350  typedef std::vector<ContentSettingImageView*> ContentSettingViews;
351
352  friend class PageActionImageView;
353  friend class PageActionWithBadgeView;
354  typedef std::vector<PageActionWithBadgeView*> PageActionViews;
355
356  // Returns the number of pixels of built-in padding to the left and right for
357  // child views. This is nonzero when touch UI is enabled so as to space out
358  // child views for easier targeting. See InitTouchableLocationBarChildView().
359  static int GetBuiltInHorizontalPaddingForChildViews();
360
361  // Returns the thickness of any visible left and right edge, in pixels.
362  int GetHorizontalEdgeThickness() const;
363
364  // The same, but for the top and bottom edges.
365  int vertical_edge_thickness() const {
366    return is_popup_mode_ ? kPopupEdgeThickness : kNormalEdgeThickness;
367  }
368
369  // Updates the visibility state of the Content Blocked icons to reflect what
370  // is actually blocked on the current page. Calling this function should
371  // always eventually be followed by calling Layout() and then
372  // UpdateContentSettingViewsPostLayout(), to ensure the icons can completely
373  // update their states.
374  void UpdateContentSettingViewsPreLayout();
375
376  // Updates after the correct screen coordinates have been set for icons.
377  // Allows content setting icons to perform any updating which can't complete
378  // until after the icons have been correctly laid out.  This should be called
379  // after UpdateContentSettingViewsPreLayout() and a subsequent Layout().
380  void UpdateContentSettingViewsPostLayout();
381
382  // Delete all page action views that we have created.
383  void DeletePageActionViews();
384
385  // Update the views for the Page Actions, to reflect state changes for
386  // PageActions.
387  void RefreshPageActionViews();
388
389  // Returns the number of scripts currently running on the page.
390  size_t ScriptBubbleScriptsRunning();
391
392  // Update the Script Bubble Icon, to reflect the number of content scripts
393  // running on the page.
394  void RefreshScriptBubble();
395
396  // Update the view for the zoom icon based on the current tab's zoom.
397  void RefreshZoomView();
398
399#if !defined(USE_AURA)
400  // Helper for the Mouse event handlers that does all the real work.
401  void OnMouseEvent(const ui::MouseEvent& event, UINT msg);
402#endif
403
404  // Returns true if the suggest text is valid.
405  bool HasValidSuggestText() const;
406
407  // Helper to show the first run info bubble.
408  void ShowFirstRunBubbleInternal();
409
410  // Draw backgrounds and borders for page actions.  Must be called
411  // after layout, so the |page_action_views_| have their bounds.
412  void PaintPageActionBackgrounds(gfx::Canvas* canvas);
413
414  // Handles a request to change the value of this text field from software
415  // using an accessibility API (typically automation software, screen readers
416  // don't normally use this). Sets the value and clears the selection.
417  void AccessibilitySetValue(const string16& new_value);
418
419  // The Browser this LocationBarView is in.  Note that at least
420  // chromeos::SimpleWebViewDialog uses a LocationBarView outside any browser
421  // window, so this may be NULL.
422  Browser* browser_;
423
424  // The Autocomplete Edit field.
425  scoped_ptr<OmniboxView> location_entry_;
426
427  // The profile which corresponds to this View.
428  Profile* profile_;
429
430  // Our delegate.
431  Delegate* delegate_;
432
433  // An object used to paint the normal-mode background.
434  scoped_ptr<views::Painter> background_border_painter_;
435  scoped_ptr<views::Painter> background_filling_painter_;
436
437  // An icon to the left of the edit field.
438  LocationIconView* location_icon_view_;
439
440  // A bubble displayed for EV HTTPS sites.
441  EVBubbleView* ev_bubble_view_;
442
443  // Location_entry view
444  views::View* location_entry_view_;
445
446  // A view to show inline autocompletion when an IME is active.  In this case,
447  // we shouldn't change the text or selection inside the OmniboxView itself,
448  // since this will conflict with the IME's control over the text.  So instead
449  // we show any autocompletion in a separate field after the OmniboxView.
450  views::Label* ime_inline_autocomplete_view_;
451
452  // The following views are used to provide hints and remind the user as to
453  // what is going in the edit. They are all added a children of the
454  // LocationBarView. At most one is visible at a time. Preference is
455  // given to the keyword_view_, then hint_view_.
456  // These autocollapse when the edit needs the room.
457
458  // Shown if the user has selected a keyword.
459  SelectedKeywordView* selected_keyword_view_;
460
461  // View responsible for showing suggested text. This is NULL when there is no
462  // suggested text.
463  views::Label* suggested_text_view_;
464
465  // Shown if the selected url has a corresponding keyword.
466  KeywordHintView* keyword_hint_view_;
467
468  // The voice search icon.
469  views::ImageButton* mic_search_view_;
470
471  // The content setting views.
472  ContentSettingViews content_setting_views_;
473
474  // The zoom icon.
475  ZoomView* zoom_view_;
476
477  // A bubble that shows after successfully generating a new credit card number.
478  GeneratedCreditCardView* generated_credit_card_view_;
479
480  // The icon to open a PDF in Reader.
481  OpenPDFInReaderView* open_pdf_in_reader_view_;
482
483  // The current page actions.
484  std::vector<ExtensionAction*> page_actions_;
485
486  // The page action icon views.
487  PageActionViews page_action_views_;
488
489  // The script bubble.
490  ScriptBubbleIconView* script_bubble_icon_view_;
491
492  // The star.
493  StarView* star_view_;
494
495  // Whether we're in popup mode. This value also controls whether the location
496  // bar is read-only.
497  const bool is_popup_mode_;
498
499  // True if we should show a focus rect while the location entry field is
500  // focused. Used when the toolbar is in full keyboard accessibility mode.
501  bool show_focus_rect_;
502
503  // This is in case we're destroyed before the model loads. We need to make
504  // Add/RemoveObserver calls.
505  TemplateURLService* template_url_service_;
506
507  // Tracks this preference to determine whether bookmark editing is allowed.
508  BooleanPrefMember edit_bookmarks_enabled_;
509
510  // While animating, the host clips the widget and draws only the bottom
511  // part of it. The view needs to know the pixel offset at which we are drawing
512  // the widget so that we can draw the curved edges that attach to the toolbar
513  // in the right location.
514  int animation_offset_;
515
516  // Used to register for notifications received by NotificationObserver.
517  content::NotificationRegistrar registrar_;
518
519  // Used to bind callback functions to this object.
520  base::WeakPtrFactory<LocationBarView> weak_ptr_factory_;
521
522  DISALLOW_COPY_AND_ASSIGN(LocationBarView);
523};
524
525#endif  // CHROME_BROWSER_UI_VIEWS_LOCATION_BAR_LOCATION_BAR_VIEW_H_
526