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.
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 COMPONENTS_OMNIBOX_SEARCH_PROVIDER_H_
12 #define COMPONENTS_OMNIBOX_SEARCH_PROVIDER_H_
17 #include "base/basictypes.h"
18 #include "base/compiler_specific.h"
19 #include "base/memory/scoped_ptr.h"
20 #include "base/time/time.h"
21 #include "base/timer/timer.h"
22 #include "components/metrics/proto/omnibox_input_type.pb.h"
23 #include "components/omnibox/answers_cache.h"
24 #include "components/omnibox/base_search_provider.h"
25 #include "components/search_engines/template_url.h"
26 #include "net/url_request/url_fetcher_delegate.h"
28 class AutocompleteProviderClient
;
29 class AutocompleteProviderListener
;
30 class AutocompleteResult
;
31 class SearchProviderTest
;
32 class TemplateURLService
;
35 struct KeywordSearchTermVisit
;
42 // Autocomplete provider for searches and suggestions from a search engine.
44 // After construction, the autocomplete controller repeatedly calls Start()
45 // with some user input, each time expecting to receive a small set of the best
46 // matches (either synchronously or asynchronously).
48 // Initially the provider creates a match that searches for the current input
49 // text. It also starts a task to query the Suggest servers. When that data
50 // comes back, the provider creates and returns matches for the best
52 class SearchProvider
: public BaseSearchProvider
,
53 public net::URLFetcherDelegate
{
55 SearchProvider(AutocompleteProviderListener
* listener
,
56 TemplateURLService
* template_url_service
,
57 scoped_ptr
<AutocompleteProviderClient
> client
);
59 // Extracts the suggest response metadata which SearchProvider previously
60 // stored for |match|.
61 static std::string
GetSuggestMetadata(const AutocompleteMatch
& match
);
63 // Answers prefetch handling - register displayed answers. Takes the top
64 // match for Autocomplete and registers the contained answer data, if any.
65 void RegisterDisplayedAnswers(const AutocompleteResult
& result
);
67 // AutocompleteProvider:
68 void ResetSession() override
;
70 // This URL may be sent with suggest requests; see comments on CanSendURL().
71 void set_current_page_url(const GURL
& current_page_url
) {
72 current_page_url_
= current_page_url
;
76 ~SearchProvider() override
;
79 friend class SearchProviderTest
;
80 FRIEND_TEST_ALL_PREFIXES(SearchProviderTest
, CanSendURL
);
81 FRIEND_TEST_ALL_PREFIXES(SearchProviderTest
,
82 DontInlineAutocompleteAsynchronously
);
83 FRIEND_TEST_ALL_PREFIXES(SearchProviderTest
, NavigationInline
);
84 FRIEND_TEST_ALL_PREFIXES(SearchProviderTest
, NavigationInlineDomainClassify
);
85 FRIEND_TEST_ALL_PREFIXES(SearchProviderTest
, NavigationInlineSchemeSubstring
);
86 FRIEND_TEST_ALL_PREFIXES(SearchProviderTest
, SuggestRelevanceExperiment
);
87 FRIEND_TEST_ALL_PREFIXES(SearchProviderTest
, TestDeleteMatch
);
88 FRIEND_TEST_ALL_PREFIXES(SearchProviderTest
, SuggestQueryUsesToken
);
89 FRIEND_TEST_ALL_PREFIXES(SearchProviderTest
, SessionToken
);
90 FRIEND_TEST_ALL_PREFIXES(SearchProviderTest
, AnswersCache
);
91 FRIEND_TEST_ALL_PREFIXES(SearchProviderTest
, RemoveExtraAnswers
);
92 FRIEND_TEST_ALL_PREFIXES(SearchProviderTest
, DoesNotProvideOnFocus
);
93 FRIEND_TEST_ALL_PREFIXES(AutocompleteProviderTest
, GetDestinationURL
);
94 FRIEND_TEST_ALL_PREFIXES(InstantExtendedPrefetchTest
, ClearPrefetchedResults
);
95 FRIEND_TEST_ALL_PREFIXES(InstantExtendedPrefetchTest
, SetPrefetchQuery
);
97 // Manages the providers (TemplateURLs) used by SearchProvider. Two providers
99 // . The default provider. This corresponds to the user's default search
100 // engine. This is always used, except for the rare case of no default
102 // . The keyword provider. This is used if the user has typed in a keyword.
105 explicit Providers(TemplateURLService
* template_url_service
);
107 // Returns true if the specified providers match the two providers cached
109 bool equal(const base::string16
& default_provider
,
110 const base::string16
& keyword_provider
) const {
111 return (default_provider
== default_provider_
) &&
112 (keyword_provider
== keyword_provider_
);
115 // Resets the cached providers.
116 void set(const base::string16
& default_provider
,
117 const base::string16
& keyword_provider
) {
118 default_provider_
= default_provider
;
119 keyword_provider_
= keyword_provider
;
122 TemplateURLService
* template_url_service() { return template_url_service_
; }
123 const base::string16
& default_provider() const { return default_provider_
; }
124 const base::string16
& keyword_provider() const { return keyword_provider_
; }
126 // NOTE: These may return NULL even if the provider members are nonempty!
127 const TemplateURL
* GetDefaultProviderURL() const;
128 const TemplateURL
* GetKeywordProviderURL() const;
130 // Returns true if there is a valid keyword provider.
131 bool has_keyword_provider() const { return !keyword_provider_
.empty(); }
134 TemplateURLService
* template_url_service_
;
136 // Cached across the life of a query so we behave consistently even if the
137 // user changes their default while the query is running.
138 base::string16 default_provider_
;
139 base::string16 keyword_provider_
;
141 DISALLOW_COPY_AND_ASSIGN(Providers
);
144 class CompareScoredResults
;
146 typedef std::vector
<history::KeywordSearchTermVisit
> HistoryResults
;
148 // Calculates the relevance score for the keyword verbatim result (if the
149 // input matches one of the profile's keyword).
150 static int CalculateRelevanceForKeywordVerbatim(
151 metrics::OmniboxInputType::Type type
,
152 bool prefer_keyword
);
154 // A helper function for UpdateAllOldResults().
155 static void UpdateOldResults(bool minimal_changes
,
156 SearchSuggestionParser::Results
* results
);
158 // Returns the first match in |matches| which might be chosen as default.
159 static ACMatches::iterator
FindTopMatch(ACMatches
* matches
);
161 // AutocompleteProvider:
162 void Start(const AutocompleteInput
& input
,
163 bool minimal_changes
,
164 bool called_due_to_focus
) override
;
165 void Stop(bool clear_cached_results
) override
;
167 // BaseSearchProvider:
168 const TemplateURL
* GetTemplateURL(bool is_keyword
) const override
;
169 const AutocompleteInput
GetInput(bool is_keyword
) const override
;
170 bool ShouldAppendExtraParams(
171 const SearchSuggestionParser::SuggestResult
& result
) const override
;
172 void RecordDeletionResult(bool success
) override
;
174 // net::URLFetcherDelegate:
175 void OnURLFetchComplete(const net::URLFetcher
* source
) override
;
177 // Stops the suggest query.
178 // NOTE: This does not update |done_|. Callers must do so.
181 // Clears the current results.
182 void ClearAllResults();
184 // Recalculates the match contents class of |results| to better display
185 // against the current input and user's language.
186 void UpdateMatchContentsClass(const base::string16
& input_text
,
187 SearchSuggestionParser::Results
* results
);
189 // Called after ParseSuggestResults to rank the |results|.
190 void SortResults(bool is_keyword
, SearchSuggestionParser::Results
* results
);
192 // Records UMA statistics about a suggest server response.
193 void LogFetchComplete(bool success
, bool is_keyword
);
195 // Updates |matches_| from the latest results; applies calculated relevances
196 // if suggested relevances cause undesirable behavior. Updates |done_|.
197 void UpdateMatches();
199 // Called when timer_ expires.
202 // Runs the history query, if necessary. The history query is synchronous.
203 // This does not update |done_|.
204 void DoHistoryQuery(bool minimal_changes
);
206 // Returns the time to delay before sending the Suggest request.
207 base::TimeDelta
GetSuggestQueryDelay() const;
209 // Determines whether an asynchronous subcomponent query should run for the
210 // current input. If so, starts it if necessary; otherwise stops it.
211 // NOTE: This function does not update |done_|. Callers must do so.
212 void StartOrStopSuggestQuery(bool minimal_changes
);
214 // Returns true when the current query can be sent to the Suggest service.
215 // This will be false e.g. when Suggest is disabled, the query contains
216 // potentially private data, etc.
217 bool IsQuerySuitableForSuggest() const;
219 // Remove existing keyword results if the user is no longer in keyword mode,
220 // and, if |minimal_changes| is false, revise the existing results to
221 // indicate they were received before the last keystroke.
222 void UpdateAllOldResults(bool minimal_changes
);
224 // Given new asynchronous results, ensure that we don't clobber the current
225 // top results, which were determined synchronously on the last keystroke.
226 void PersistTopSuggestions(SearchSuggestionParser::Results
* results
);
228 // Apply calculated relevance scores to the current results.
229 void ApplyCalculatedSuggestRelevance(
230 SearchSuggestionParser::SuggestResults
* list
);
231 void ApplyCalculatedNavigationRelevance(
232 SearchSuggestionParser::NavigationResults
* list
);
234 // Starts a new URLFetcher requesting suggest results from |template_url|;
235 // callers own the returned URLFetcher, which is NULL for invalid providers.
236 net::URLFetcher
* CreateSuggestFetcher(int id
,
237 const TemplateURL
* template_url
,
238 const AutocompleteInput
& input
);
240 // Converts the parsed results to a set of AutocompleteMatches, |matches_|.
241 void ConvertResultsToAutocompleteMatches();
243 // Remove answer contents from each match in |matches| other than the first
245 static void RemoveExtraAnswers(ACMatches
* matches
);
247 // Returns an iterator to the first match in |matches_| which might
248 // be chosen as default.
249 ACMatches::const_iterator
FindTopMatch() const;
251 // Checks if suggested relevances violate an expected constraint.
252 // See UpdateMatches() for the use and explanation of this constraint
253 // and other constraints enforced without the use of helper functions.
254 bool IsTopMatchSearchWithURLInput() const;
256 // Converts an appropriate number of navigation results in
257 // |navigation_results| to matches and adds them to |matches|.
258 void AddNavigationResultsToMatches(
259 const SearchSuggestionParser::NavigationResults
& navigation_results
,
262 // Adds a match for each result in |raw_default_history_results_| or
263 // |raw_keyword_history_results_| to |map|. |is_keyword| indicates
264 // which one of the two.
265 void AddRawHistoryResultsToMap(bool is_keyword
,
266 int did_not_accept_suggestion
,
269 // Adds a match for each transformed result in |results| to |map|.
270 void AddTransformedHistoryResultsToMap(
271 const SearchSuggestionParser::SuggestResults
& results
,
272 int did_not_accept_suggestion
,
275 // Calculates relevance scores for all |results|.
276 SearchSuggestionParser::SuggestResults
ScoreHistoryResultsHelper(
277 const HistoryResults
& results
,
278 bool base_prevent_inline_autocomplete
,
279 bool input_multiple_words
,
280 const base::string16
& input_text
,
283 // Calculates relevance scores for |results|, adjusting for boundary
284 // conditions around multi-word queries. (See inline comments in function
285 // definition for more details.)
286 void ScoreHistoryResults(
287 const HistoryResults
& results
,
289 SearchSuggestionParser::SuggestResults
* scored_results
);
291 // Adds matches for |results| to |map|.
292 void AddSuggestResultsToMap(
293 const SearchSuggestionParser::SuggestResults
& results
,
294 const std::string
& metadata
,
297 // Gets the relevance score for the verbatim result. This value may be
298 // provided by the suggest server or calculated locally; if
299 // |relevance_from_server| is non-NULL, it will be set to indicate which of
301 int GetVerbatimRelevance(bool* relevance_from_server
) const;
303 // Calculates the relevance score for the verbatim result from the
304 // default search engine. This version takes into account context:
305 // i.e., whether the user has entered a keyword-based search or not.
306 int CalculateRelevanceForVerbatim() const;
308 // Calculates the relevance score for the verbatim result from the default
309 // search engine *ignoring* whether the input is a keyword-based search
310 // or not. This function should only be used to determine the minimum
311 // relevance score that the best result from this provider should have.
312 // For normal use, prefer the above function.
313 int CalculateRelevanceForVerbatimIgnoringKeywordModeState() const;
315 // Gets the relevance score for the keyword verbatim result.
316 // |relevance_from_server| is handled as in GetVerbatimRelevance().
317 // TODO(mpearson): Refactor so this duplication isn't necessary or
318 // restructure so one static function takes all the parameters it needs
319 // (rather than looking at internal state).
320 int GetKeywordVerbatimRelevance(bool* relevance_from_server
) const;
322 // |time| is the time at which this query was last seen. |is_keyword|
323 // indicates whether the results correspond to the keyword provider or default
324 // provider. |use_aggressive_method| says whether this function can use a
325 // method that gives high scores (1200+) rather than one that gives lower
326 // scores. When using the aggressive method, scores may exceed 1300
327 // unless |prevent_search_history_inlining| is set.
328 int CalculateRelevanceForHistory(const base::Time
& time
,
330 bool use_aggressive_method
,
331 bool prevent_search_history_inlining
) const;
333 // Returns an AutocompleteMatch for a navigational suggestion.
334 AutocompleteMatch
NavigationToMatch(
335 const SearchSuggestionParser::NavigationResult
& navigation
);
337 // Updates the value of |done_| from the internal state.
340 // Obtains a session token, regenerating if necessary.
341 std::string
GetSessionToken();
343 // Answers prefetch handling - finds the previously displayed answer matching
344 // the current top-scoring history result. If there is a previous answer,
345 // returns the query data associated with it. Otherwise, returns an empty
347 AnswersQueryData
FindAnswersPrefetchData();
349 AutocompleteProviderListener
* listener_
;
351 // The number of suggest results that haven't yet arrived. If it's greater
352 // than 0, it indicates that one of the URLFetchers is still running.
353 int suggest_results_pending_
;
355 // Maintains the TemplateURLs used.
356 Providers providers_
;
359 AutocompleteInput input_
;
361 // Input when searching against the keyword provider.
362 AutocompleteInput keyword_input_
;
364 // Searches in the user's history that begin with the input text.
365 HistoryResults raw_keyword_history_results_
;
366 HistoryResults raw_default_history_results_
;
368 // Scored searches in the user's history - based on |keyword_history_results_|
369 // or |default_history_results_| as appropriate.
370 SearchSuggestionParser::SuggestResults transformed_keyword_history_results_
;
371 SearchSuggestionParser::SuggestResults transformed_default_history_results_
;
373 // A timer to start a query to the suggest server after the user has stopped
374 // typing for long enough.
375 base::OneShotTimer
<SearchProvider
> timer_
;
377 // The time at which we sent a query to the suggest server.
378 base::TimeTicks time_suggest_request_sent_
;
380 // Fetchers used to retrieve results for the keyword and default providers.
381 scoped_ptr
<net::URLFetcher
> keyword_fetcher_
;
382 scoped_ptr
<net::URLFetcher
> default_fetcher_
;
384 // Results from the default and keyword search providers.
385 SearchSuggestionParser::Results default_results_
;
386 SearchSuggestionParser::Results keyword_results_
;
388 // The top query suggestion, left blank if none.
389 base::string16 top_query_suggestion_match_contents_
;
390 // The top navigation suggestion, left blank/invalid if none.
391 GURL top_navigation_suggestion_
;
393 GURL current_page_url_
;
395 // Session token management.
396 std::string current_token_
;
397 base::TimeTicks token_expiration_time_
;
399 // Answers prefetch management.
400 AnswersCache answers_cache_
; // Cache for last answers seen.
401 AnswersQueryData prefetch_data_
; // Data to use for query prefetching.
403 DISALLOW_COPY_AND_ASSIGN(SearchProvider
);
406 #endif // COMPONENTS_OMNIBOX_SEARCH_PROVIDER_H_