[Metrics] Make MetricsStateManager take a callback param to check if UMA is enabled.
[chromium-blink-merge.git] / chrome / browser / autocomplete / search_provider.h
blobe2be361d92b8ab0893cb0641e14223eb98a24fb9
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 Search autocomplete provider. This provider is
6 // responsible for all autocomplete entries that start with "Search <engine>
7 // for ...", including searching for the current input string, search
8 // history, and search suggestions. An instance of it gets created and
9 // managed by the autocomplete controller.
11 #ifndef CHROME_BROWSER_AUTOCOMPLETE_SEARCH_PROVIDER_H_
12 #define CHROME_BROWSER_AUTOCOMPLETE_SEARCH_PROVIDER_H_
14 #include "base/basictypes.h"
15 #include "base/compiler_specific.h"
16 #include "base/memory/scoped_ptr.h"
17 #include "base/time/time.h"
18 #include "base/timer/timer.h"
19 #include "chrome/browser/autocomplete/base_search_provider.h"
20 #include "chrome/browser/history/history_types.h"
21 #include "chrome/browser/search_engines/template_url.h"
23 class Profile;
24 class SearchProviderTest;
25 class TemplateURLService;
27 namespace net {
28 class URLFetcher;
31 // Autocomplete provider for searches and suggestions from a search engine.
33 // After construction, the autocomplete controller repeatedly calls Start()
34 // with some user input, each time expecting to receive a small set of the best
35 // matches (either synchronously or asynchronously).
37 // Initially the provider creates a match that searches for the current input
38 // text. It also starts a task to query the Suggest servers. When that data
39 // comes back, the provider creates and returns matches for the best
40 // suggestions.
41 class SearchProvider : public BaseSearchProvider {
42 public:
43 SearchProvider(AutocompleteProviderListener* listener, Profile* profile);
45 // Extracts the suggest response metadata which SearchProvider previously
46 // stored for |match|.
47 static std::string GetSuggestMetadata(const AutocompleteMatch& match);
49 // AutocompleteProvider:
50 virtual void ResetSession() OVERRIDE;
52 // This URL may be sent with suggest requests; see comments on CanSendURL().
53 void set_current_page_url(const GURL& current_page_url) {
54 current_page_url_ = current_page_url;
57 protected:
58 virtual ~SearchProvider();
60 private:
61 friend class SearchProviderTest;
62 FRIEND_TEST_ALL_PREFIXES(SearchProviderTest, CanSendURL);
63 FRIEND_TEST_ALL_PREFIXES(SearchProviderTest, NavigationInline);
64 FRIEND_TEST_ALL_PREFIXES(SearchProviderTest, NavigationInlineDomainClassify);
65 FRIEND_TEST_ALL_PREFIXES(SearchProviderTest, NavigationInlineSchemeSubstring);
66 FRIEND_TEST_ALL_PREFIXES(SearchProviderTest, RemoveStaleResultsTest);
67 FRIEND_TEST_ALL_PREFIXES(SearchProviderTest, SuggestRelevanceExperiment);
68 FRIEND_TEST_ALL_PREFIXES(SearchProviderTest, TestDeleteMatch);
69 FRIEND_TEST_ALL_PREFIXES(SearchProviderTest, SuggestQueryUsesToken);
70 FRIEND_TEST_ALL_PREFIXES(SearchProviderTest, SessionToken);
71 FRIEND_TEST_ALL_PREFIXES(AutocompleteProviderTest, GetDestinationURL);
72 FRIEND_TEST_ALL_PREFIXES(InstantExtendedPrefetchTest, ClearPrefetchedResults);
73 FRIEND_TEST_ALL_PREFIXES(InstantExtendedPrefetchTest, SetPrefetchQuery);
75 // Manages the providers (TemplateURLs) used by SearchProvider. Two providers
76 // may be used:
77 // . The default provider. This corresponds to the user's default search
78 // engine. This is always used, except for the rare case of no default
79 // engine.
80 // . The keyword provider. This is used if the user has typed in a keyword.
81 class Providers {
82 public:
83 explicit Providers(TemplateURLService* template_url_service);
85 // Returns true if the specified providers match the two providers cached
86 // by this class.
87 bool equal(const base::string16& default_provider,
88 const base::string16& keyword_provider) const {
89 return (default_provider == default_provider_) &&
90 (keyword_provider == keyword_provider_);
93 // Resets the cached providers.
94 void set(const base::string16& default_provider,
95 const base::string16& keyword_provider) {
96 default_provider_ = default_provider;
97 keyword_provider_ = keyword_provider;
100 TemplateURLService* template_url_service() { return template_url_service_; }
101 const base::string16& default_provider() const { return default_provider_; }
102 const base::string16& keyword_provider() const { return keyword_provider_; }
104 // NOTE: These may return NULL even if the provider members are nonempty!
105 const TemplateURL* GetDefaultProviderURL() const;
106 const TemplateURL* GetKeywordProviderURL() const;
108 // Returns true if there is a valid keyword provider.
109 bool has_keyword_provider() const { return !keyword_provider_.empty(); }
111 private:
112 TemplateURLService* template_url_service_;
114 // Cached across the life of a query so we behave consistently even if the
115 // user changes their default while the query is running.
116 base::string16 default_provider_;
117 base::string16 keyword_provider_;
119 DISALLOW_COPY_AND_ASSIGN(Providers);
122 class CompareScoredResults;
124 typedef std::vector<history::KeywordSearchTermVisit> HistoryResults;
126 // Removes non-inlineable results until either the top result can inline
127 // autocomplete the current input or verbatim outscores the top result.
128 static void RemoveStaleResults(const base::string16& input,
129 int verbatim_relevance,
130 SuggestResults* suggest_results,
131 NavigationResults* navigation_results);
133 // Recalculates the match contents class of |results| to better display
134 // against the current input and user's language.
135 void UpdateMatchContentsClass(const base::string16& input_text,
136 Results* results);
138 // Calculates the relevance score for the keyword verbatim result (if the
139 // input matches one of the profile's keyword).
140 static int CalculateRelevanceForKeywordVerbatim(AutocompleteInput::Type type,
141 bool prefer_keyword);
143 // AutocompleteProvider:
144 virtual void Start(const AutocompleteInput& input,
145 bool minimal_changes) OVERRIDE;
147 // BaseSearchProvider:
148 virtual void SortResults(bool is_keyword,
149 const base::ListValue* relevances,
150 Results* results) OVERRIDE;
151 virtual const TemplateURL* GetTemplateURL(bool is_keyword) const OVERRIDE;
152 virtual const AutocompleteInput GetInput(bool is_keyword) const OVERRIDE;
153 virtual Results* GetResultsToFill(bool is_keyword) OVERRIDE;
154 virtual bool ShouldAppendExtraParams(
155 const SuggestResult& result) const OVERRIDE;
156 virtual void StopSuggest() OVERRIDE;
157 virtual void ClearAllResults() OVERRIDE;
158 virtual int GetDefaultResultRelevance() const OVERRIDE;
159 virtual void RecordDeletionResult(bool success) OVERRIDE;
160 virtual void LogFetchComplete(bool success, bool is_keyword) OVERRIDE;
161 virtual bool IsKeywordFetcher(const net::URLFetcher* fetcher) const OVERRIDE;
162 virtual void UpdateMatches() OVERRIDE;
164 // Called when timer_ expires.
165 void Run();
167 // Runs the history query, if necessary. The history query is synchronous.
168 // This does not update |done_|.
169 void DoHistoryQuery(bool minimal_changes);
171 // Determines whether an asynchronous subcomponent query should run for the
172 // current input. If so, starts it if necessary; otherwise stops it.
173 // NOTE: This function does not update |done_|. Callers must do so.
174 void StartOrStopSuggestQuery(bool minimal_changes);
176 // Returns true when the current query can be sent to the Suggest service.
177 // This will be false e.g. when Suggest is disabled, the query contains
178 // potentially private data, etc.
179 bool IsQuerySuitableForSuggest() const;
181 // Removes stale results for both default and keyword providers. See comments
182 // on RemoveStaleResults().
183 void RemoveAllStaleResults();
185 // Apply calculated relevance scores to the current results.
186 void ApplyCalculatedRelevance();
187 void ApplyCalculatedSuggestRelevance(SuggestResults* list);
188 void ApplyCalculatedNavigationRelevance(NavigationResults* list);
190 // Starts a new URLFetcher requesting suggest results from |template_url|;
191 // callers own the returned URLFetcher, which is NULL for invalid providers.
192 net::URLFetcher* CreateSuggestFetcher(int id,
193 const TemplateURL* template_url,
194 const AutocompleteInput& input);
196 // Converts the parsed results to a set of AutocompleteMatches, |matches_|.
197 void ConvertResultsToAutocompleteMatches();
199 // Returns an iterator to the first match in |matches_| which might
200 // be chosen as default.
201 ACMatches::const_iterator FindTopMatch() const;
203 // Checks if suggested relevances violate certain expected constraints.
204 // See UpdateMatches() for the use and explanation of these constraints.
205 bool HasKeywordDefaultMatchInKeywordMode() const;
206 bool IsTopMatchSearchWithURLInput() const;
208 // Converts an appropriate number of navigation results in
209 // |navigation_results| to matches and adds them to |matches|.
210 void AddNavigationResultsToMatches(
211 const NavigationResults& navigation_results,
212 ACMatches* matches);
214 // Adds a match for each result in |results| to |map|. |is_keyword| indicates
215 // whether the results correspond to the keyword provider or default provider.
216 void AddHistoryResultsToMap(const HistoryResults& results,
217 bool is_keyword,
218 int did_not_accept_suggestion,
219 MatchMap* map);
221 // Calculates relevance scores for all |results|.
222 SuggestResults ScoreHistoryResults(const HistoryResults& results,
223 bool base_prevent_inline_autocomplete,
224 bool input_multiple_words,
225 const base::string16& input_text,
226 bool is_keyword);
228 // Adds matches for |results| to |map|.
229 void AddSuggestResultsToMap(const SuggestResults& results,
230 const std::string& metadata,
231 MatchMap* map);
233 // Gets the relevance score for the verbatim result. This value may be
234 // provided by the suggest server or calculated locally; if
235 // |relevance_from_server| is non-NULL, it will be set to indicate which of
236 // those is true.
237 int GetVerbatimRelevance(bool* relevance_from_server) const;
239 // Calculates the relevance score for the verbatim result from the
240 // default search engine. This version takes into account context:
241 // i.e., whether the user has entered a keyword-based search or not.
242 int CalculateRelevanceForVerbatim() const;
244 // Calculates the relevance score for the verbatim result from the default
245 // search engine *ignoring* whether the input is a keyword-based search
246 // or not. This function should only be used to determine the minimum
247 // relevance score that the best result from this provider should have.
248 // For normal use, prefer the above function.
249 int CalculateRelevanceForVerbatimIgnoringKeywordModeState() const;
251 // Gets the relevance score for the keyword verbatim result.
252 // |relevance_from_server| is handled as in GetVerbatimRelevance().
253 // TODO(mpearson): Refactor so this duplication isn't necessary or
254 // restructure so one static function takes all the parameters it needs
255 // (rather than looking at internal state).
256 int GetKeywordVerbatimRelevance(bool* relevance_from_server) const;
258 // |time| is the time at which this query was last seen. |is_keyword|
259 // indicates whether the results correspond to the keyword provider or default
260 // provider. |use_aggressive_method| says whether this function can use a
261 // method that gives high scores (1200+) rather than one that gives lower
262 // scores. When using the aggressive method, scores may exceed 1300
263 // unless |prevent_search_history_inlining| is set.
264 int CalculateRelevanceForHistory(const base::Time& time,
265 bool is_keyword,
266 bool use_aggressive_method,
267 bool prevent_search_history_inlining) const;
269 // Returns an AutocompleteMatch for a navigational suggestion.
270 AutocompleteMatch NavigationToMatch(const NavigationResult& navigation);
272 // Updates the value of |done_| from the internal state.
273 void UpdateDone();
275 // Obtains a session token, regenerating if necessary.
276 std::string GetSessionToken();
278 // The amount of time to wait before sending a new suggest request after the
279 // previous one. Non-const because some unittests modify this value.
280 static int kMinimumTimeBetweenSuggestQueriesMs;
282 // Maintains the TemplateURLs used.
283 Providers providers_;
285 // The user's input.
286 AutocompleteInput input_;
288 // Input when searching against the keyword provider.
289 AutocompleteInput keyword_input_;
291 // Searches in the user's history that begin with the input text.
292 HistoryResults keyword_history_results_;
293 HistoryResults default_history_results_;
295 // A timer to start a query to the suggest server after the user has stopped
296 // typing for long enough.
297 base::OneShotTimer<SearchProvider> timer_;
299 // The time at which we sent a query to the suggest server.
300 base::TimeTicks time_suggest_request_sent_;
302 // Fetchers used to retrieve results for the keyword and default providers.
303 scoped_ptr<net::URLFetcher> keyword_fetcher_;
304 scoped_ptr<net::URLFetcher> default_fetcher_;
306 // Results from the default and keyword search providers.
307 Results default_results_;
308 Results keyword_results_;
310 GURL current_page_url_;
312 // Session token management.
313 std::string current_token_;
314 base::TimeTicks token_expiration_time_;
316 DISALLOW_COPY_AND_ASSIGN(SearchProvider);
319 #endif // CHROME_BROWSER_AUTOCOMPLETE_SEARCH_PROVIDER_H_