Home | History | Annotate | Download | only in omnibox
      1 // Copyright 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_OMNIBOX_OMNIBOX_EDIT_MODEL_H_
      6 #define CHROME_BROWSER_UI_OMNIBOX_OMNIBOX_EDIT_MODEL_H_
      7 
      8 #include "base/basictypes.h"
      9 #include "base/compiler_specific.h"
     10 #include "base/memory/scoped_ptr.h"
     11 #include "base/strings/string16.h"
     12 #include "base/time/time.h"
     13 #include "chrome/browser/autocomplete/autocomplete_controller_delegate.h"
     14 #include "chrome/browser/autocomplete/autocomplete_match.h"
     15 #include "chrome/browser/ui/omnibox/omnibox_controller.h"
     16 #include "chrome/common/omnibox_focus_state.h"
     17 #include "content/public/common/page_transition_types.h"
     18 #include "ui/base/window_open_disposition.h"
     19 #include "ui/gfx/native_widget_types.h"
     20 #include "url/gurl.h"
     21 
     22 class AutocompleteController;
     23 class AutocompleteResult;
     24 class OmniboxCurrentPageDelegate;
     25 class OmniboxEditController;
     26 class OmniboxPopupModel;
     27 class OmniboxView;
     28 class Profile;
     29 
     30 namespace gfx {
     31 class Image;
     32 class Rect;
     33 }
     34 
     35 // Reasons why the Omnibox could change into keyword mode.
     36 // These numeric values are used in UMA logs; do not change them.
     37 enum EnteredKeywordModeMethod {
     38   ENTERED_KEYWORD_MODE_VIA_TAB = 0,
     39   ENTERED_KEYWORD_MODE_VIA_SPACE_AT_END = 1,
     40   ENTERED_KEYWORD_MODE_VIA_SPACE_IN_MIDDLE = 2,
     41   ENTERED_KEYWORD_MODE_NUM_ITEMS
     42 };
     43 
     44 class OmniboxEditModel {
     45  public:
     46   // Did the Omnibox focus originate via the user clicking on the Omnibox or on
     47   // the Fakebox?
     48   enum FocusSource {
     49     INVALID = 0,
     50     OMNIBOX = 1,
     51     FAKEBOX = 2
     52   };
     53 
     54   struct State {
     55     State(bool user_input_in_progress,
     56           const base::string16& user_text,
     57           const base::string16& gray_text,
     58           const base::string16& keyword,
     59           bool is_keyword_hint,
     60           bool url_replacement_enabled,
     61           OmniboxFocusState focus_state,
     62           FocusSource focus_source);
     63     ~State();
     64 
     65     bool user_input_in_progress;
     66     const base::string16 user_text;
     67     const base::string16 gray_text;
     68     const base::string16 keyword;
     69     const bool is_keyword_hint;
     70     bool url_replacement_enabled;
     71     OmniboxFocusState focus_state;
     72     FocusSource focus_source;
     73   };
     74 
     75   OmniboxEditModel(OmniboxView* view,
     76                    OmniboxEditController* controller,
     77                    Profile* profile);
     78   virtual ~OmniboxEditModel();
     79 
     80   // TODO(beaudoin): Remove this accessor when the AutocompleteController has
     81   //     completely moved to OmniboxController.
     82   AutocompleteController* autocomplete_controller() const {
     83     return omnibox_controller_->autocomplete_controller();
     84   }
     85 
     86   void set_popup_model(OmniboxPopupModel* popup_model) {
     87     omnibox_controller_->set_popup_model(popup_model);
     88   }
     89 
     90   // TODO: The edit and popup should be siblings owned by the LocationBarView,
     91   // making this accessor unnecessary.
     92   // NOTE: popup_model() can be NULL for testing.
     93   OmniboxPopupModel* popup_model() const {
     94     return omnibox_controller_->popup_model();
     95   }
     96 
     97   OmniboxEditController* controller() const { return controller_; }
     98 
     99   Profile* profile() const { return profile_; }
    100 
    101   // Returns the current state.  This assumes we are switching tabs, and changes
    102   // the internal state appropriately.
    103   const State GetStateForTabSwitch();
    104 
    105   // Resets the tab state, then restores local state from the saved |state|.
    106   // |state| may be NULL if there is no saved state.
    107   void RestoreState(const State* state);
    108 
    109   // Returns the match for the current text. If the user has not edited the text
    110   // this is the match corresponding to the permanent text. Returns the
    111   // alternate nav URL, if |alternate_nav_url| is non-NULL and there is such a
    112   // URL.
    113   AutocompleteMatch CurrentMatch(GURL* alternate_nav_url) const;
    114 
    115   // Called when the user wants to export the entire current text as a URL.
    116   // Sets the url, and if known, the title and favicon.
    117   void GetDataForURLExport(GURL* url,
    118                            base::string16* title,
    119                            gfx::Image* favicon);
    120 
    121   // Returns true if the current edit contents will be treated as a
    122   // URL/navigation, as opposed to a search.
    123   bool CurrentTextIsURL() const;
    124 
    125   // Returns the match type for the current edit contents.
    126   AutocompleteMatch::Type CurrentTextType() const;
    127 
    128   // Invoked to adjust the text before writting to the clipboard for a copy
    129   // (e.g. by adding 'http' to the front). |sel_min| gives the minimum position
    130   // of the selection e.g. min(selection_start, selection_end). |text| is the
    131   // currently selected text. If |is_all_selected| is true all the text in the
    132   // edit is selected. If the url should be copied to the clipboard |write_url|
    133   // is set to true and |url| set to the url to write.
    134   void AdjustTextForCopy(int sel_min,
    135                          bool is_all_selected,
    136                          base::string16* text,
    137                          GURL* url,
    138                          bool* write_url);
    139 
    140   bool user_input_in_progress() const { return user_input_in_progress_; }
    141 
    142   // Sets the state of user_input_in_progress_, and notifies the observer if
    143   // that state has changed.
    144   void SetInputInProgress(bool in_progress);
    145 
    146   // Updates permanent_text_ to the current permanent text from the toolbar
    147   // model.  Returns true if the permanent text changed and the change should be
    148   // immediately user-visible, because either the user is not editing or the
    149   // edit does not have focus.
    150   bool UpdatePermanentText();
    151 
    152   // Returns the URL corresponding to the permanent text.
    153   GURL PermanentURL();
    154 
    155   // Sets the user_text_ to |text|.  Only the View should call this.
    156   void SetUserText(const base::string16& text);
    157 
    158   // Commits the gray suggested text as if it's been input by the user.
    159   // Returns true if the text was committed.
    160   // TODO: can the return type be void?
    161   bool CommitSuggestedText();
    162 
    163   // Invoked any time the text may have changed in the edit. Notifies the
    164   // controller.
    165   void OnChanged();
    166 
    167   // Reverts the edit model back to its unedited state (permanent text showing,
    168   // no user input in progress).
    169   void Revert();
    170 
    171   // Directs the popup to start autocomplete.
    172   void StartAutocomplete(bool has_selected_text,
    173                          bool prevent_inline_autocomplete) const;
    174 
    175   // Closes the popup and cancels any pending asynchronous queries.
    176   void StopAutocomplete();
    177 
    178   // Determines whether the user can "paste and go", given the specified text.
    179   bool CanPasteAndGo(const base::string16& text) const;
    180 
    181   // Navigates to the destination last supplied to CanPasteAndGo.
    182   void PasteAndGo(const base::string16& text);
    183 
    184   // Returns true if this is a paste-and-search rather than paste-and-go (or
    185   // nothing).
    186   bool IsPasteAndSearch(const base::string16& text) const;
    187 
    188   // Asks the browser to load the popup's currently selected item, using the
    189   // supplied disposition.  This may close the popup. If |for_drop| is true,
    190   // it indicates the input is being accepted as part of a drop operation and
    191   // the transition should be treated as LINK (so that it won't trigger the
    192   // URL to be autocompleted).
    193   void AcceptInput(WindowOpenDisposition disposition,
    194                    bool for_drop);
    195 
    196   // Asks the browser to load the item at |index|, with the given properties.
    197   //
    198   // |match| is passed by value for two reasons:
    199   // (1) This function needs to modify |match|, so a const ref isn't
    200   //     appropriate.  Callers don't actually care about the modifications, so a
    201   //     pointer isn't required.
    202   // (2) The passed-in match is, on the caller side, typically coming from data
    203   //     associated with the popup.  Since this call can close the popup, that
    204   //     could clear that data, leaving us with a pointer-to-garbage.  So at
    205   //     some point someone needs to make a copy of the match anyway, to
    206   //     preserve it past the popup closure.
    207   void OpenMatch(AutocompleteMatch match,
    208                  WindowOpenDisposition disposition,
    209                  const GURL& alternate_nav_url,
    210                  size_t index);
    211 
    212   OmniboxFocusState focus_state() const { return focus_state_; }
    213   bool has_focus() const { return focus_state_ != OMNIBOX_FOCUS_NONE; }
    214   bool is_caret_visible() const {
    215     return focus_state_ == OMNIBOX_FOCUS_VISIBLE;
    216   }
    217 
    218   // Accessors for keyword-related state (see comments on keyword_ and
    219   // is_keyword_hint_).
    220   const base::string16& keyword() const { return keyword_; }
    221   bool is_keyword_hint() const { return is_keyword_hint_; }
    222 
    223   // Accepts the current keyword hint as a keyword. It always returns true for
    224   // caller convenience. |entered_method| indicates how the use entered
    225   // keyword mode. This parameter is only used for metrics/logging; it's not
    226   // used to change user-visible behavior.
    227   bool AcceptKeyword(EnteredKeywordModeMethod entered_method);
    228 
    229   // Accepts the current temporary text as the user text.
    230   void AcceptTemporaryTextAsUserText();
    231 
    232   // Clears the current keyword.  |visible_text| is the (non-keyword) text
    233   // currently visible in the edit.
    234   void ClearKeyword(const base::string16& visible_text);
    235 
    236   // Returns the current autocomplete result.  This logic should in the future
    237   // live in AutocompleteController but resides here for now.  This method is
    238   // used by AutomationProvider::AutocompleteEditGetMatches.
    239   const AutocompleteResult& result() const {
    240     return omnibox_controller_->result();
    241   }
    242 
    243   // Called when the view is gaining focus.  |control_down| is whether the
    244   // control key is down (at the time we're gaining focus).
    245   void OnSetFocus(bool control_down);
    246 
    247   // Sets the visibility of the caret in the omnibox, if it has focus. The
    248   // visibility of the caret is reset to visible if either
    249   //   - The user starts typing, or
    250   //   - We explicitly focus the omnibox again.
    251   // The latter case must be handled in three separate places--OnSetFocus(),
    252   // OmniboxView::SetFocus(), and the mouse handlers in OmniboxView. See
    253   // accompanying comments for why each of these is necessary.
    254   //
    255   // Caret visibility is tracked per-tab and updates automatically upon
    256   // switching tabs.
    257   void SetCaretVisibility(bool visible);
    258 
    259   // Sent before |OnKillFocus| and before the popup is closed.
    260   void OnWillKillFocus(gfx::NativeView view_gaining_focus);
    261 
    262   // Called when the view is losing focus.  Resets some state.
    263   void OnKillFocus();
    264 
    265   // Called when the user presses the escape key.  Decides what, if anything, to
    266   // revert about any current edits.  Returns whether the key was handled.
    267   bool OnEscapeKeyPressed();
    268 
    269   // Called when the user presses or releases the control key.  Changes state as
    270   // necessary.
    271   void OnControlKeyChanged(bool pressed);
    272 
    273   // Called when the user pastes in text.
    274   void OnPaste();
    275 
    276   // Returns true if pasting is in progress.
    277   bool is_pasting() const { return paste_state_ == PASTING; }
    278 
    279   // TODO(beaudoin): Try not to expose this.
    280   bool in_revert() const { return in_revert_; }
    281 
    282   // Called when the user presses up or down.  |count| is a repeat count,
    283   // negative for moving up, positive for moving down.
    284   virtual void OnUpOrDownKeyPressed(int count);
    285 
    286   // Called when any relevant data changes.  This rolls together several
    287   // separate pieces of data into one call so we can update all the UI
    288   // efficiently:
    289   //   |text| is either the new temporary text from the user manually selecting
    290   //     a different match, or the inline autocomplete text.  We distinguish by
    291   //     checking if |destination_for_temporary_text_change| is NULL.
    292   //   |destination_for_temporary_text_change| is NULL (if temporary text should
    293   //     not change) or the pre-change destination URL (if temporary text should
    294   //     change) so we can save it off to restore later.
    295   //   |keyword| is the keyword to show a hint for if |is_keyword_hint| is true,
    296   //     or the currently selected keyword if |is_keyword_hint| is false (see
    297   //     comments on keyword_ and is_keyword_hint_).
    298   void OnPopupDataChanged(
    299       const base::string16& text,
    300       GURL* destination_for_temporary_text_change,
    301       const base::string16& keyword,
    302       bool is_keyword_hint);
    303 
    304   // Called by the OmniboxView after something changes, with details about what
    305   // state changes occured.  Updates internal state, updates the popup if
    306   // necessary, and returns true if any significant changes occurred.  Note that
    307   // |text_differs| may be set even if |old_text| == |new_text|, e.g. if we've
    308   // just committed an IME composition.
    309   //
    310   // If |allow_keyword_ui_change| is false then the change should not affect
    311   // keyword ui state, even if the text matches a keyword exactly. This value
    312   // may be false when the user is composing a text with an IME.
    313   bool OnAfterPossibleChange(const base::string16& old_text,
    314                              const base::string16& new_text,
    315                              size_t selection_start,
    316                              size_t selection_end,
    317                              bool selection_differs,
    318                              bool text_differs,
    319                              bool just_deleted_text,
    320                              bool allow_keyword_ui_change);
    321 
    322   // Called when the current match has changed in the OmniboxController.
    323   void OnCurrentMatchChanged();
    324 
    325   // TODO(beaudoin): We need this to allow OmniboxController access the
    326   // InstantController via OmniboxEditController, because the only valid pointer
    327   // to InstantController is kept in Browser. We should try to get rid of this,
    328   // maybe by ensuring InstantController lives as long as Browser.
    329   InstantController* GetInstantController() const;
    330 
    331   // Name of the histogram tracking cut or copy omnibox commands.
    332   static const char kCutOrCopyAllTextHistogram[];
    333 
    334  private:
    335   friend class OmniboxControllerTest;
    336 
    337   enum PasteState {
    338     NONE,           // Most recent edit was not a paste.
    339     PASTING,        // In the middle of doing a paste. We need this intermediate
    340                     // state because OnPaste() does the actual detection of
    341                     // paste, but OnAfterPossibleChange() has to update the
    342                     // paste state for every edit. If OnPaste() set the state
    343                     // directly to PASTED, OnAfterPossibleChange() wouldn't know
    344                     // whether that represented the current edit or a past one.
    345     PASTED,         // Most recent edit was a paste.
    346   };
    347 
    348   enum ControlKeyState {
    349     UP,                   // The control key is not depressed.
    350     DOWN_WITHOUT_CHANGE,  // The control key is depressed, and the edit's
    351                           // contents/selection have not changed since it was
    352                           // depressed.  This is the only state in which we
    353                           // do the "ctrl-enter" behavior when the user hits
    354                           // enter.
    355     DOWN_WITH_CHANGE,     // The control key is depressed, and the edit's
    356                           // contents/selection have changed since it was
    357                           // depressed.  If the user now hits enter, we assume
    358                           // he simply hasn't released the key, rather than that
    359                           // he intended to hit "ctrl-enter".
    360   };
    361 
    362   // Returns true if a query to an autocomplete provider is currently
    363   // in progress.  This logic should in the future live in
    364   // AutocompleteController but resides here for now.  This method is used by
    365   // AutomationProvider::AutocompleteEditIsQueryInProgress.
    366   bool query_in_progress() const;
    367 
    368   // Called whenever user_text_ should change.
    369   void InternalSetUserText(const base::string16& text);
    370 
    371   // Returns true if a keyword is selected.
    372   bool KeywordIsSelected() const;
    373 
    374   // Turns off keyword mode for the current match.
    375   void ClearPopupKeywordMode() const;
    376 
    377   // Conversion between user text and display text. User text is the text the
    378   // user has input. Display text is the text being shown in the edit. The
    379   // two are different if a keyword is selected.
    380   base::string16 DisplayTextFromUserText(const base::string16& text) const;
    381   base::string16 UserTextFromDisplayText(const base::string16& text) const;
    382 
    383   // If there's a selected match, copies it into |match|. Else, returns the
    384   // default match for the current text, as well as the alternate nav URL, if
    385   // |alternate_nav_url| is non-NULL and there is such a URL.
    386   void GetInfoForCurrentText(AutocompleteMatch* match,
    387                              GURL* alternate_nav_url) const;
    388 
    389   // Reverts the edit box from a temporary text back to the original user text.
    390   // If |revert_popup| is true then the popup will be reverted as well.
    391   void RevertTemporaryText(bool revert_popup);
    392 
    393   // Accepts current keyword if the user just typed a space at the end of
    394   // |new_text|.  This handles both of the following cases:
    395   //   (assume "foo" is a keyword, | is the input caret, [] is selected text)
    396   //   foo| -> foo |      (a space was appended to a keyword)
    397   //   foo[bar] -> foo |  (a space replaced other text after a keyword)
    398   // Returns true if the current keyword is accepted.
    399   bool MaybeAcceptKeywordBySpace(const base::string16& new_text);
    400 
    401   // Checks whether the user inserted a space into |old_text| and by doing so
    402   // created a |new_text| that looks like "<keyword> <search phrase>".
    403   bool CreatedKeywordSearchByInsertingSpaceInMiddle(
    404       const base::string16& old_text,
    405       const base::string16& new_text,
    406       size_t caret_position) const;
    407 
    408   // Checks if a given character is a valid space character for accepting
    409   // keyword.
    410   static bool IsSpaceCharForAcceptingKeyword(wchar_t c);
    411 
    412   // Classify the current page being viewed as, for example, the new tab
    413   // page or a normal web page.  Used for logging omnibox events for
    414   // UMA opted-in users.  Examines the user's profile to determine if the
    415   // current page is the user's home page.
    416   AutocompleteInput::PageClassification ClassifyPage() const;
    417 
    418   // Sets |match| and |alternate_nav_url| based on classifying |text|.
    419   // |alternate_nav_url| may be NULL.
    420   void ClassifyStringForPasteAndGo(const base::string16& text,
    421                                    AutocompleteMatch* match,
    422                                    GURL* alternate_nav_url) const;
    423 
    424   // If focus_state_ does not match |state|, we update it and notify the
    425   // InstantController about the change (passing along the |reason| for the
    426   // change). If the caret visibility changes, we call ApplyCaretVisibility() on
    427   // the view.
    428   void SetFocusState(OmniboxFocusState state, OmniboxFocusChangeReason reason);
    429 
    430   scoped_ptr<OmniboxController> omnibox_controller_;
    431 
    432   OmniboxView* view_;
    433 
    434   OmniboxEditController* controller_;
    435 
    436   scoped_ptr<OmniboxCurrentPageDelegate> delegate_;
    437 
    438   OmniboxFocusState focus_state_;
    439 
    440   // Used to keep track whether the input currently in progress originated by
    441   // focusing in the Omnibox or in the Fakebox. This will be INVALID if no input
    442   // is in progress or the Omnibox is not focused.
    443   FocusSource focus_source_;
    444 
    445   // The URL of the currently displayed page.
    446   base::string16 permanent_text_;
    447 
    448   // This flag is true when the user has modified the contents of the edit, but
    449   // not yet accepted them.  We use this to determine when we need to save
    450   // state (on switching tabs) and whether changes to the page URL should be
    451   // immediately displayed.
    452   // This flag will be true in a superset of the cases where the popup is open.
    453   bool user_input_in_progress_;
    454 
    455   // The text that the user has entered.  This does not include inline
    456   // autocomplete text that has not yet been accepted.
    457   base::string16 user_text_;
    458 
    459   // We keep track of when the user last focused on the omnibox.
    460   base::TimeTicks last_omnibox_focus_;
    461 
    462   // Whether any user input has occurred since focusing on the omnibox. This is
    463   // used along with |last_omnibox_focus_| to calculate the time between a user
    464   // focusing on the omnibox and editing. It is initialized to true since
    465   // there was no focus event.
    466   bool user_input_since_focus_;
    467 
    468   // We keep track of when the user began modifying the omnibox text.
    469   // This should be valid whenever user_input_in_progress_ is true.
    470   base::TimeTicks time_user_first_modified_omnibox_;
    471 
    472   // When the user closes the popup, we need to remember the URL for their
    473   // desired choice, so that if they hit enter without reopening the popup we
    474   // know where to go.  We could simply rerun autocomplete in this case, but
    475   // we'd need to either wait for all results to come in (unacceptably slow) or
    476   // do the wrong thing when the user had chosen some provider whose results
    477   // were not returned instantaneously.
    478   //
    479   // This variable is only valid when user_input_in_progress_ is true, since
    480   // when it is false the user has either never input anything (so there won't
    481   // be a value here anyway) or has canceled their input, which should be
    482   // treated the same way.  Also, since this is for preserving a desired URL
    483   // after the popup has been closed, we ignore this if the popup is open, and
    484   // simply ask the popup for the desired URL directly.  As a result, the
    485   // contents of this variable only need to be updated when the popup is closed
    486   // but user_input_in_progress_ is not being cleared.
    487   base::string16 url_for_remembered_user_selection_;
    488 
    489   // Inline autocomplete is allowed if the user has not just deleted text, and
    490   // no temporary text is showing.  In this case, inline_autocomplete_text_ is
    491   // appended to the user_text_ and displayed selected (at least initially).
    492   //
    493   // NOTE: When the popup is closed there should never be inline autocomplete
    494   // text (actions that close the popup should either accept the text, convert
    495   // it to a normal selection, or change the edit entirely).
    496   bool just_deleted_text_;
    497   base::string16 inline_autocomplete_text_;
    498 
    499   // Used by OnPopupDataChanged to keep track of whether there is currently a
    500   // temporary text.
    501   //
    502   // Example of use: If the user types "goog", then arrows down in the
    503   // autocomplete popup until, say, "google.com" appears in the edit box, then
    504   // the user_text_ is still "goog", and "google.com" is "temporary text".
    505   // When the user hits <esc>, the edit box reverts to "goog".  Hit <esc> again
    506   // and the popup is closed and "goog" is replaced by the permanent_text_,
    507   // which is the URL of the current page.
    508   //
    509   // original_url_ is only valid when there is temporary text, and is used as
    510   // the unique identifier of the originally selected item.  Thus, if the user
    511   // arrows to a different item with the same text, we can still distinguish
    512   // them and not revert all the way to the permanent_text_.
    513   bool has_temporary_text_;
    514   GURL original_url_;
    515 
    516   // When the user's last action was to paste, we disallow inline autocomplete
    517   // (on the theory that the user is trying to paste in a new URL or part of
    518   // one, and in either case inline autocomplete would get in the way).
    519   PasteState paste_state_;
    520 
    521   // Whether the control key is depressed.  We track this to avoid calling
    522   // UpdatePopup() repeatedly if the user holds down the key, and to know
    523   // whether to trigger "ctrl-enter" behavior.
    524   ControlKeyState control_key_state_;
    525 
    526   // The keyword associated with the current match.  The user may have an actual
    527   // selected keyword, or just some input text that looks like a keyword (so we
    528   // can show a hint to press <tab>).  This is the keyword in either case;
    529   // is_keyword_hint_ (below) distinguishes the two cases.
    530   base::string16 keyword_;
    531 
    532   // True if the keyword associated with this match is merely a hint, i.e. the
    533   // user hasn't actually selected a keyword yet.  When this is true, we can use
    534   // keyword_ to show a "Press <tab> to search" sort of hint.
    535   bool is_keyword_hint_;
    536 
    537   Profile* profile_;
    538 
    539   // This is needed to properly update the SearchModel state when the user
    540   // presses escape.
    541   bool in_revert_;
    542 
    543   // Indicates if the upcoming autocomplete search is allowed to be treated as
    544   // an exact keyword match.  If this is true then keyword mode will be
    545   // triggered automatically if the input is "<keyword> <search string>".  We
    546   // allow this when CreatedKeywordSearchByInsertingSpaceInMiddle() is true.
    547   // This has no effect if we're already in keyword mode.
    548   bool allow_exact_keyword_match_;
    549 
    550   DISALLOW_COPY_AND_ASSIGN(OmniboxEditModel);
    551 };
    552 
    553 #endif  // CHROME_BROWSER_UI_OMNIBOX_OMNIBOX_EDIT_MODEL_H_
    554