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