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