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// This file contains the keyword autocomplete provider. The keyword provider
6// is responsible for remembering/suggesting user "search keyword queries"
7// (e.g.  "imdb Godzilla") and then fixing them up into valid URLs.  An
8// instance of it gets created and managed by the autocomplete controller.
9// KeywordProvider uses a TemplateURLService to find the set of keywords.
10
11#ifndef CHROME_BROWSER_AUTOCOMPLETE_KEYWORD_PROVIDER_H_
12#define CHROME_BROWSER_AUTOCOMPLETE_KEYWORD_PROVIDER_H_
13
14#include <string>
15
16#include "base/basictypes.h"
17#include "base/compiler_specific.h"
18#include "chrome/browser/autocomplete/autocomplete_input.h"
19#include "chrome/browser/autocomplete/autocomplete_provider.h"
20#include "content/public/browser/notification_observer.h"
21#include "content/public/browser/notification_registrar.h"
22
23class Profile;
24class TemplateURL;
25class TemplateURLService;
26
27// Autocomplete provider for keyword input.
28//
29// After construction, the autocomplete controller repeatedly calls Start()
30// with some user input, each time expecting to receive a small set of the best
31// matches (either synchronously or asynchronously).
32//
33// To construct these matches, the provider treats user input as a series of
34// whitespace-delimited tokens and tries to match the first token as the prefix
35// of a known "keyword".  A keyword is some string that maps to a search query
36// URL; the rest of the user's input is taken as the input to the query.  For
37// example, the keyword "bug" might map to the URL "http://b/issue?id=%s", so
38// input like "bug 123" would become "http://b/issue?id=123".
39//
40// Because we do prefix matching, user input could match more than one keyword
41// at once.  (Example: the input "f jazz" matches all keywords starting with
42// "f".)  We return the best matches, up to three.
43//
44// The resulting matches are shown with content specified by the keyword
45// (usually "Search [name] for %s"), description "(Keyword: [keyword])", and
46// action "[keyword] %s".  If the user has typed a (possibly partial) keyword
47// but no search terms, the suggested result is shown greyed out, with
48// "<enter term(s)>" as the substituted input, and does nothing when selected.
49class KeywordProvider : public AutocompleteProvider,
50                        public content::NotificationObserver {
51 public:
52  KeywordProvider(AutocompleteProviderListener* listener, Profile* profile);
53  // For testing.
54  KeywordProvider(AutocompleteProviderListener* listener,
55                  TemplateURLService* model);
56
57  // Extracts the next whitespace-delimited token from input and returns it.
58  // Sets |remaining_input| to everything after the first token (skipping over
59  // the first intervening whitespace).
60  // If |trim_leading_whitespace| is true then leading whitespace in
61  // |*remaining_input| will be trimmed.
62  static string16 SplitKeywordFromInput(const string16& input,
63                                        bool trim_leading_whitespace,
64                                        string16* remaining_input);
65
66  // Returns the replacement string from the user input. The replacement
67  // string is the portion of the input that does not contain the keyword.
68  // For example, the replacement string for "b blah" is blah.
69  // If |trim_leading_whitespace| is true then leading whitespace in
70  // replacement string will be trimmed.
71  static string16 SplitReplacementStringFromInput(const string16& input,
72                                                  bool trim_leading_whitespace);
73
74  // Returns the matching substituting keyword for |input|, or NULL if there
75  // is no keyword for the specified input.  If the matching keyword was found,
76  // updates |input|'s text and cursor position.
77  static const TemplateURL* GetSubstitutingTemplateURLForInput(
78      TemplateURLService* model,
79      AutocompleteInput* input);
80
81  // If |text| corresponds (in the sense of
82  // TemplateURLModel::CleanUserInputKeyword()) to an enabled, substituting
83  // keyword, returns that keyword; returns the empty string otherwise.
84  string16 GetKeywordForText(const string16& text) const;
85
86  // Creates a fully marked-up AutocompleteMatch for a specific keyword.
87  AutocompleteMatch CreateVerbatimMatch(const string16& text,
88                                        const string16& keyword,
89                                        const AutocompleteInput& input);
90
91  // AutocompleteProvider:
92  virtual void Start(const AutocompleteInput& input,
93                     bool minimal_changes) OVERRIDE;
94  virtual void Stop(bool clear_cached_results) OVERRIDE;
95
96 private:
97  class ScopedEndExtensionKeywordMode;
98  friend class ScopedEndExtensionKeywordMode;
99
100  virtual ~KeywordProvider();
101
102  // Extracts the keyword from |input| into |keyword|. Any remaining characters
103  // after the keyword are placed in |remaining_input|. Returns true if |input|
104  // is valid and has a keyword. This makes use of SplitKeywordFromInput to
105  // extract the keyword and remaining string, and uses
106  // TemplateURLService::CleanUserInputKeyword to remove unnecessary characters.
107  // In general use this instead of SplitKeywordFromInput.
108  // Leading whitespace in |*remaining_input| will be trimmed.
109  static bool ExtractKeywordFromInput(const AutocompleteInput& input,
110                                      string16* keyword,
111                                      string16* remaining_input);
112
113  // Determines the relevance for some input, given its type, whether the user
114  // typed the complete keyword, and whether the user is in "prefer keyword
115  // matches" mode, and whether the keyword supports replacement.
116  // If |allow_exact_keyword_match| is false, the relevance for complete
117  // keywords that support replacements is degraded.
118  static int CalculateRelevance(AutocompleteInput::Type type,
119                                bool complete,
120                                bool support_replacement,
121                                bool prefer_keyword,
122                                bool allow_exact_keyword_match);
123
124  // Creates a fully marked-up AutocompleteMatch from the user's input.
125  // If |relevance| is negative, calculate a relevance based on heuristics.
126  AutocompleteMatch CreateAutocompleteMatch(const TemplateURL* template_url,
127                                            const AutocompleteInput& input,
128                                            size_t prefix_length,
129                                            const string16& remaining_input,
130                                            bool allowed_to_be_default_match,
131                                            int relevance);
132
133  // Fills in the "destination_url" and "contents" fields of |match| with the
134  // provided user input and keyword data.
135  void FillInURLAndContents(const string16& remaining_input,
136                            const TemplateURL* element,
137                            AutocompleteMatch* match) const;
138
139  void EnterExtensionKeywordMode(const std::string& extension_id);
140  void MaybeEndExtensionKeywordMode();
141
142  // content::NotificationObserver interface.
143  virtual void Observe(int type,
144                       const content::NotificationSource& source,
145                       const content::NotificationDetails& details) OVERRIDE;
146
147  TemplateURLService* GetTemplateURLService() const;
148
149  // Model for the keywords.  This is only non-null when testing, otherwise the
150  // TemplateURLService from the Profile is used.
151  TemplateURLService* model_;
152
153  // Identifies the current input state. This is incremented each time the
154  // autocomplete edit's input changes in any way. It is used to tell whether
155  // suggest results from the extension are current.
156  int current_input_id_;
157
158  // The input state at the time we last asked the extension for suggest
159  // results.
160  AutocompleteInput extension_suggest_last_input_;
161
162  // We remember the last suggestions we've received from the extension in case
163  // we need to reset our matches without asking the extension again.
164  std::vector<AutocompleteMatch> extension_suggest_matches_;
165
166  // If non-empty, holds the ID of the extension whose keyword is currently in
167  // the URL bar while the autocomplete popup is open.
168  std::string current_keyword_extension_id_;
169
170  content::NotificationRegistrar registrar_;
171
172  DISALLOW_COPY_AND_ASSIGN(KeywordProvider);
173};
174
175#endif  // CHROME_BROWSER_AUTOCOMPLETE_KEYWORD_PROVIDER_H_
176