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