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