1 // Copyright 2014 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 class contains common functionality for search-based autocomplete
6 // providers. Search provider and zero suggest provider both use it for common
9 #ifndef CHROME_BROWSER_AUTOCOMPLETE_BASE_SEARCH_PROVIDER_H_
10 #define CHROME_BROWSER_AUTOCOMPLETE_BASE_SEARCH_PROVIDER_H_
17 #include "base/memory/scoped_vector.h"
18 #include "base/strings/string16.h"
19 #include "chrome/browser/autocomplete/autocomplete_input.h"
20 #include "chrome/browser/autocomplete/autocomplete_match.h"
21 #include "chrome/browser/autocomplete/autocomplete_provider.h"
22 #include "net/url_request/url_fetcher_delegate.h"
24 class AutocompleteProviderListener
;
27 class SuggestionDeletionHandler
;
35 // Base functionality for receiving suggestions from a search engine.
36 // This class is abstract and should only be used as a base for other
37 // autocomplete providers utilizing its functionality.
38 class BaseSearchProvider
: public AutocompleteProvider
,
39 public net::URLFetcherDelegate
{
41 // ID used in creating URLFetcher for default provider's suggest results.
42 static const int kDefaultProviderURLFetcherID
;
44 // ID used in creating URLFetcher for keyword provider's suggest results.
45 static const int kKeywordProviderURLFetcherID
;
47 // ID used in creating URLFetcher for deleting suggestion results.
48 static const int kDeletionURLFetcherID
;
50 BaseSearchProvider(AutocompleteProviderListener
* listener
,
52 AutocompleteProvider::Type type
);
54 // Returns whether |match| is flagged as a query that should be prefetched.
55 static bool ShouldPrefetch(const AutocompleteMatch
& match
);
57 // Returns a simpler AutocompleteMatch suitable for persistence like in
59 // NOTE: Use with care. Most likely you want the other CreateSearchSuggestion
60 // with protected access.
61 static AutocompleteMatch
CreateSearchSuggestion(
62 const base::string16
& suggestion
,
63 AutocompleteMatchType::Type type
,
64 bool from_keyword_provider
,
65 const TemplateURL
* template_url
);
67 // AutocompleteProvider:
68 virtual void Stop(bool clear_cached_results
) OVERRIDE
;
69 virtual void DeleteMatch(const AutocompleteMatch
& match
) OVERRIDE
;
70 virtual void AddProviderInfo(ProvidersInfo
* provider_info
) const OVERRIDE
;
72 bool field_trial_triggered_in_session() const {
73 return field_trial_triggered_in_session_
;
76 void set_in_app_list() { in_app_list_
= true; }
79 // The following keys are used to record additional information on matches.
81 // We annotate our AutocompleteMatches with whether their relevance scores
82 // were server-provided using this key in the |additional_info| field.
83 static const char kRelevanceFromServerKey
[];
85 // Indicates whether the server said a match should be prefetched.
86 static const char kShouldPrefetchKey
[];
88 // Used to store metadata from the server response, which is needed for
90 static const char kSuggestMetadataKey
[];
92 // Used to store a deletion request url for server-provided suggestions.
93 static const char kDeletionUrlKey
[];
95 // These are the values for the above keys.
96 static const char kTrue
[];
97 static const char kFalse
[];
99 virtual ~BaseSearchProvider();
101 // The Result classes are intermediate representations of AutocompleteMatches,
102 // simply containing relevance-ranked search and navigation suggestions.
103 // They may be cached to provide some synchronous matches while requests for
104 // new suggestions from updated input are in flight.
105 // TODO(msw) Extend these classes to generate their corresponding matches and
106 // other requisite data, in order to consolidate and simplify the
107 // highly fragmented SearchProvider logic for each Result type.
110 Result(bool from_keyword_provider
,
112 bool relevance_from_server
,
113 AutocompleteMatchType::Type type
,
114 const std::string
& deletion_url
);
117 bool from_keyword_provider() const { return from_keyword_provider_
; }
119 const base::string16
& match_contents() const { return match_contents_
; }
120 const ACMatchClassifications
& match_contents_class() const {
121 return match_contents_class_
;
124 AutocompleteMatchType::Type
type() const { return type_
; }
125 int relevance() const { return relevance_
; }
126 void set_relevance(int relevance
) { relevance_
= relevance
; }
128 bool relevance_from_server() const { return relevance_from_server_
; }
129 void set_relevance_from_server(bool relevance_from_server
) {
130 relevance_from_server_
= relevance_from_server
;
133 const std::string
& deletion_url() const { return deletion_url_
; }
135 // Returns if this result is inlineable against the current input |input|.
136 // Non-inlineable results are stale.
137 virtual bool IsInlineable(const base::string16
& input
) const = 0;
139 // Returns the default relevance value for this result (which may
140 // be left over from a previous omnibox input) given the current
141 // input and whether the current input caused a keyword provider
143 virtual int CalculateRelevance(const AutocompleteInput
& input
,
144 bool keyword_provider_requested
) const = 0;
147 // The contents to be displayed and its style info.
148 base::string16 match_contents_
;
149 ACMatchClassifications match_contents_class_
;
151 // True if the result came from the keyword provider.
152 bool from_keyword_provider_
;
154 AutocompleteMatchType::Type type_
;
156 // The relevance score.
160 // Whether this result's relevance score was fully or partly calculated
161 // based on server information, and thus is assumed to be more accurate.
162 // This is ultimately used in
163 // SearchProvider::ConvertResultsToAutocompleteMatches(), see comments
165 bool relevance_from_server_
;
167 // Optional deletion URL provided with suggestions. Fetching this URL
168 // should result in some reasonable deletion behaviour on the server,
169 // e.g. deleting this term out of a user's server-side search history.
170 std::string deletion_url_
;
173 class SuggestResult
: public Result
{
175 SuggestResult(const base::string16
& suggestion
,
176 AutocompleteMatchType::Type type
,
177 const base::string16
& match_contents
,
178 const base::string16
& match_contents_prefix
,
179 const base::string16
& annotation
,
180 const base::string16
& answer_contents
,
181 const base::string16
& answer_type
,
182 const std::string
& suggest_query_params
,
183 const std::string
& deletion_url
,
184 bool from_keyword_provider
,
186 bool relevance_from_server
,
187 bool should_prefetch
,
188 const base::string16
& input_text
);
189 virtual ~SuggestResult();
191 const base::string16
& suggestion() const { return suggestion_
; }
192 const base::string16
& match_contents_prefix() const {
193 return match_contents_prefix_
;
195 const base::string16
& annotation() const { return annotation_
; }
196 const std::string
& suggest_query_params() const {
197 return suggest_query_params_
;
200 const base::string16
& answer_contents() const { return answer_contents_
; }
201 const base::string16
& answer_type() const { return answer_type_
; }
203 bool should_prefetch() const { return should_prefetch_
; }
205 // Fills in |match_contents_class_| to reflect how |match_contents_| should
206 // be displayed and bolded against the current |input_text|. If
207 // |allow_bolding_all| is false and |match_contents_class_| would have all
208 // of |match_contents_| bolded, do nothing.
209 void ClassifyMatchContents(const bool allow_bolding_all
,
210 const base::string16
& input_text
);
213 virtual bool IsInlineable(const base::string16
& input
) const OVERRIDE
;
214 virtual int CalculateRelevance(
215 const AutocompleteInput
& input
,
216 bool keyword_provider_requested
) const OVERRIDE
;
219 // The search terms to be used for this suggestion.
220 base::string16 suggestion_
;
222 // The contents to be displayed as prefix of match contents.
223 // Used for postfix suggestions to display a leading ellipsis (or some
224 // equivalent character) to indicate omitted text.
225 // Only used to pass this information to about:omnibox's "Additional Info".
226 base::string16 match_contents_prefix_
;
228 // Optional annotation for the |match_contents_| for disambiguation.
229 // This may be displayed in the autocomplete match contents, but is defined
230 // separately to facilitate different formatting.
231 base::string16 annotation_
;
233 // Optional additional parameters to be added to the search URL.
234 std::string suggest_query_params_
;
236 // Optional formatted Answers result.
237 base::string16 answer_contents_
;
239 // Type of optional formatted Answers result.
240 base::string16 answer_type_
;
242 // Should this result be prefetched?
243 bool should_prefetch_
;
246 class NavigationResult
: public Result
{
248 // |provider| is necessary to use StringForURLDisplay() in order to
249 // compute |formatted_url_|.
250 NavigationResult(const AutocompleteProvider
& provider
,
252 AutocompleteMatchType::Type type
,
253 const base::string16
& description
,
254 const std::string
& deletion_url
,
255 bool from_keyword_provider
,
257 bool relevance_from_server
,
258 const base::string16
& input_text
,
259 const std::string
& languages
);
260 virtual ~NavigationResult();
262 const GURL
& url() const { return url_
; }
263 const base::string16
& description() const { return description_
; }
264 const base::string16
& formatted_url() const { return formatted_url_
; }
266 // Fills in |match_contents_| and |match_contents_class_| to reflect how
267 // the URL should be displayed and bolded against the current |input_text|
268 // and user |languages|. If |allow_bolding_nothing| is false and
269 // |match_contents_class_| would result in an entirely unbolded
270 // |match_contents_|, do nothing.
271 void CalculateAndClassifyMatchContents(const bool allow_bolding_nothing
,
272 const base::string16
& input_text
,
273 const std::string
& languages
);
276 virtual bool IsInlineable(const base::string16
& input
) const OVERRIDE
;
277 virtual int CalculateRelevance(
278 const AutocompleteInput
& input
,
279 bool keyword_provider_requested
) const OVERRIDE
;
282 // The suggested url for navigation.
285 // The properly formatted ("fixed up") URL string with equivalent meaning
286 // to the one in |url_|.
287 base::string16 formatted_url_
;
289 // The suggested navigational result description; generally the site name.
290 base::string16 description_
;
293 typedef std::vector
<SuggestResult
> SuggestResults
;
294 typedef std::vector
<NavigationResult
> NavigationResults
;
295 typedef std::pair
<base::string16
, std::string
> MatchKey
;
296 typedef std::map
<MatchKey
, AutocompleteMatch
> MatchMap
;
297 typedef ScopedVector
<SuggestionDeletionHandler
> SuggestionDeletionHandlers
;
299 // A simple structure bundling most of the information (including
300 // both SuggestResults and NavigationResults) returned by a call to
301 // the suggest server.
303 // This has to be declared after the typedefs since it relies on some of them.
308 // Clears |suggest_results| and |navigation_results| and resets
309 // |verbatim_relevance| to -1 (implies unset).
312 // Returns whether any of the results (including verbatim) have
313 // server-provided scores.
314 bool HasServerProvidedScores() const;
316 // Query suggestions sorted by relevance score.
317 SuggestResults suggest_results
;
319 // Navigational suggestions sorted by relevance score.
320 NavigationResults navigation_results
;
322 // The server supplied verbatim relevance scores. Negative values
323 // indicate that there is no suggested score; a value of 0
324 // suppresses the verbatim result.
325 int verbatim_relevance
;
327 // The JSON metadata associated with this server response.
328 std::string metadata
;
331 DISALLOW_COPY_AND_ASSIGN(Results
);
334 // Returns an AutocompleteMatch with the given |autocomplete_provider|
335 // for the search |suggestion|, which represents a search via |template_url|.
336 // If |template_url| is NULL, returns a match with an invalid destination URL.
338 // |input| is the original user input. Text in the input is used to highlight
339 // portions of the match contents to distinguish locally-typed text from
342 // |input| is also necessary for various other details, like whether we should
343 // allow inline autocompletion and what the transition type should be.
344 // |accepted_suggestion| and |omnibox_start_margin| are used to generate
345 // Assisted Query Stats.
346 // |append_extra_query_params| should be set if |template_url| is the default
347 // search engine, so the destination URL will contain any
348 // command-line-specified query params.
349 // |from_app_list| should be set if the search was made from the app list.
350 static AutocompleteMatch
CreateSearchSuggestion(
351 AutocompleteProvider
* autocomplete_provider
,
352 const AutocompleteInput
& input
,
353 const SuggestResult
& suggestion
,
354 const TemplateURL
* template_url
,
355 int accepted_suggestion
,
356 int omnibox_start_margin
,
357 bool append_extra_query_params
,
360 // Parses JSON response received from the provider, stripping XSSI
361 // protection if needed. Returns the parsed data if successful, NULL
363 static scoped_ptr
<base::Value
> DeserializeJsonData(std::string json_data
);
365 // Returns whether the requirements for requesting zero suggest results
366 // are met. The requirements are
367 // * The user is enrolled in a zero suggest experiment.
368 // * The user is not on the NTP.
369 // * The suggest request is sent over HTTPS. This avoids leaking the current
370 // page URL or personal data in unencrypted network traffic.
371 // * The user has suggest enabled in their settings and is not in incognito
372 // mode. (Incognito disables suggest entirely.)
373 // * The user's suggest provider is Google. We might want to allow other
374 // providers to see this data someday, but for now this has only been
375 // implemented for Google.
376 static bool ZeroSuggestEnabled(
377 const GURL
& suggest_url
,
378 const TemplateURL
* template_url
,
379 AutocompleteInput::PageClassification page_classification
,
382 // Returns whether we can send the URL of the current page in any suggest
383 // requests. Doing this requires that all the following hold:
384 // * ZeroSuggestEnabled() is true, so we meet the requirements above.
385 // * The current URL is HTTP, or HTTPS with the same domain as the suggest
386 // server. Non-HTTP[S] URLs (e.g. FTP/file URLs) may contain sensitive
387 // information. HTTPS URLs may also contain sensitive information, but if
388 // they're on the same domain as the suggest server, then the relevant
389 // entity could have already seen/logged this data.
390 // * The user is OK in principle with sending URLs of current pages to their
391 // provider. Today, there is no explicit setting that controls this, but if
392 // the user has tab sync enabled and tab sync is unencrypted, then they're
393 // already sending this data to Google for sync purposes. Thus we use this
394 // setting as a proxy for "it's OK to send such data". In the future,
395 // especially if we want to support suggest providers other than Google, we
396 // may change this to be a standalone setting or part of some explicit
398 static bool CanSendURL(
399 const GURL
& current_page_url
,
400 const GURL
& suggest_url
,
401 const TemplateURL
* template_url
,
402 AutocompleteInput::PageClassification page_classification
,
405 // net::URLFetcherDelegate:
406 virtual void OnURLFetchComplete(const net::URLFetcher
* source
) OVERRIDE
;
408 // If the |deletion_url| is valid, then set |match.deletable| to true and
409 // save the |deletion_url| into the |match|'s additional info under
410 // the key |kDeletionUrlKey|.
411 void SetDeletionURL(const std::string
& deletion_url
,
412 AutocompleteMatch
* match
);
414 // Creates an AutocompleteMatch from |result| to search for the query in
415 // |result|. Adds the created match to |map|; if such a match
416 // already exists, whichever one has lower relevance is eliminated.
417 // |metadata| and |accepted_suggestion| are used for generating an
418 // AutocompleteMatch.
419 // |mark_as_deletable| indicates whether the match should be marked deletable.
420 // NOTE: Any result containing a deletion URL is always marked deletable.
421 void AddMatchToMap(const SuggestResult
& result
,
422 const std::string
& metadata
,
423 int accepted_suggestion
,
424 bool mark_as_deletable
,
427 // Parses results from the suggest server and updates the appropriate suggest
428 // and navigation result lists in |results|. |is_keyword_result| indicates
429 // whether the response was received from the keyword provider.
430 // Returns whether the appropriate result list members were updated.
431 bool ParseSuggestResults(const base::Value
& root_val
,
432 bool is_keyword_result
,
435 // Called at the end of ParseSuggestResults to rank the |results|.
436 virtual void SortResults(bool is_keyword
,
437 const base::ListValue
* relevances
,
440 // Optionally, cache the received |json_data| and return true if we want
441 // to stop processing results at this point. The |parsed_data| is the parsed
442 // version of |json_data| used to determine if we received an empty result.
443 virtual bool StoreSuggestionResponse(const std::string
& json_data
,
444 const base::Value
& parsed_data
);
446 // Returns the TemplateURL corresponding to the keyword or default
447 // provider based on the value of |is_keyword|.
448 virtual const TemplateURL
* GetTemplateURL(bool is_keyword
) const = 0;
450 // Returns the AutocompleteInput for keyword provider or default provider
451 // based on the value of |is_keyword|.
452 virtual const AutocompleteInput
GetInput(bool is_keyword
) const = 0;
454 // Returns a pointer to a Results object, which will hold suggest results.
455 virtual Results
* GetResultsToFill(bool is_keyword
) = 0;
457 // Returns whether the destination URL corresponding to the given |result|
458 // should contain command-line-specified query params.
459 virtual bool ShouldAppendExtraParams(const SuggestResult
& result
) const = 0;
461 // Stops the suggest query.
462 // NOTE: This does not update |done_|. Callers must do so.
463 virtual void StopSuggest() = 0;
465 // Clears the current results.
466 virtual void ClearAllResults() = 0;
468 // Returns the relevance to use if it was not explicitly set by the server.
469 virtual int GetDefaultResultRelevance() const = 0;
471 // Records in UMA whether the deletion request resulted in success.
472 virtual void RecordDeletionResult(bool success
) = 0;
474 // Records UMA statistics about a suggest server response.
475 virtual void LogFetchComplete(bool succeeded
, bool is_keyword
) = 0;
477 // Modify provider-specific UMA statistics.
478 virtual void ModifyProviderInfo(
479 metrics::OmniboxEventProto_ProviderInfo
* provider_info
) const;
481 // Returns whether the |fetcher| is for the keyword provider.
482 virtual bool IsKeywordFetcher(const net::URLFetcher
* fetcher
) const = 0;
484 // Updates |matches_| from the latest results; applies calculated relevances
485 // if suggested relevances cause undesriable behavior. Updates |done_|.
486 virtual void UpdateMatches() = 0;
488 // Whether a field trial, if any, has triggered in the most recent
489 // autocomplete query. This field is set to true only if the suggestion
490 // provider has completed and the response contained
491 // '"google:fieldtrialtriggered":true'.
492 bool field_trial_triggered_
;
494 // Same as above except that it is maintained across the current Omnibox
496 bool field_trial_triggered_in_session_
;
498 // The number of suggest results that haven't yet arrived. If it's greater
499 // than 0, it indicates that one of the URLFetchers is still running.
500 int suggest_results_pending_
;
503 friend class SearchProviderTest
;
504 FRIEND_TEST_ALL_PREFIXES(SearchProviderTest
, TestDeleteMatch
);
506 // Removes the deleted |match| from the list of |matches_|.
507 void DeleteMatchFromMatches(const AutocompleteMatch
& match
);
509 // This gets called when we have requested a suggestion deletion from the
510 // server to handle the results of the deletion. It will be called after the
511 // deletion request completes.
512 void OnDeletionComplete(bool success
,
513 SuggestionDeletionHandler
* handler
);
515 // Each deletion handler in this vector corresponds to an outstanding request
516 // that a server delete a personalized suggestion. Making this a ScopedVector
517 // causes us to auto-cancel all such requests on shutdown.
518 SuggestionDeletionHandlers deletion_handlers_
;
520 // True if this provider's results are being displayed in the app list. By
521 // default this is false, meaning that the results will be shown in the
525 DISALLOW_COPY_AND_ASSIGN(BaseSearchProvider
);
528 #endif // CHROME_BROWSER_AUTOCOMPLETE_BASE_SEARCH_PROVIDER_H_