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.
5 #include "chrome/browser/autocomplete/search_provider.h"
10 #include "base/callback.h"
11 #include "base/i18n/break_iterator.h"
12 #include "base/i18n/case_conversion.h"
13 #include "base/i18n/icu_string_conversions.h"
14 #include "base/json/json_string_value_serializer.h"
15 #include "base/message_loop/message_loop.h"
16 #include "base/metrics/histogram.h"
17 #include "base/prefs/pref_service.h"
18 #include "base/strings/string16.h"
19 #include "base/strings/string_util.h"
20 #include "base/strings/utf_string_conversions.h"
21 #include "chrome/browser/autocomplete/autocomplete_classifier.h"
22 #include "chrome/browser/autocomplete/autocomplete_classifier_factory.h"
23 #include "chrome/browser/autocomplete/autocomplete_match.h"
24 #include "chrome/browser/autocomplete/autocomplete_provider_listener.h"
25 #include "chrome/browser/autocomplete/autocomplete_result.h"
26 #include "chrome/browser/autocomplete/keyword_provider.h"
27 #include "chrome/browser/autocomplete/url_prefix.h"
28 #include "chrome/browser/google/google_util.h"
29 #include "chrome/browser/history/history_service.h"
30 #include "chrome/browser/history/history_service_factory.h"
31 #include "chrome/browser/history/in_memory_database.h"
32 #include "chrome/browser/metrics/variations/variations_http_header_provider.h"
33 #include "chrome/browser/omnibox/omnibox_field_trial.h"
34 #include "chrome/browser/profiles/profile.h"
35 #include "chrome/browser/search/search.h"
36 #include "chrome/browser/search_engines/template_url_prepopulate_data.h"
37 #include "chrome/browser/search_engines/template_url_service.h"
38 #include "chrome/browser/search_engines/template_url_service_factory.h"
39 #include "chrome/browser/sync/profile_sync_service.h"
40 #include "chrome/browser/sync/profile_sync_service_factory.h"
41 #include "chrome/browser/ui/browser.h"
42 #include "chrome/browser/ui/browser_finder.h"
43 #include "chrome/browser/ui/browser_instant_controller.h"
44 #include "chrome/browser/ui/search/instant_controller.h"
45 #include "chrome/common/net/url_fixer_upper.h"
46 #include "chrome/common/pref_names.h"
47 #include "chrome/common/url_constants.h"
48 #include "content/public/browser/user_metrics.h"
49 #include "grit/generated_resources.h"
50 #include "net/base/escape.h"
51 #include "net/base/load_flags.h"
52 #include "net/base/net_util.h"
53 #include "net/base/registry_controlled_domains/registry_controlled_domain.h"
54 #include "net/http/http_request_headers.h"
55 #include "net/http/http_response_headers.h"
56 #include "net/url_request/url_fetcher.h"
57 #include "net/url_request/url_request_status.h"
58 #include "ui/base/l10n/l10n_util.h"
59 #include "url/url_util.h"
62 // Helpers --------------------------------------------------------------------
66 // We keep track in a histogram how many suggest requests we send, how
67 // many suggest requests we invalidate (e.g., due to a user typing
68 // another character), and how many replies we receive.
69 // *** ADD NEW ENUMS AFTER ALL PREVIOUSLY DEFINED ONES! ***
70 // (excluding the end-of-list enum value)
71 // We do not want values of existing enums to change or else it screws
73 enum SuggestRequestsHistogramValue
{
77 MAX_SUGGEST_REQUEST_HISTOGRAM_VALUE
80 // The verbatim score for an input which is not an URL.
81 const int kNonURLVerbatimRelevance
= 1300;
83 // Increments the appropriate value in the histogram by one.
84 void LogOmniboxSuggestRequest(
85 SuggestRequestsHistogramValue request_value
) {
86 UMA_HISTOGRAM_ENUMERATION("Omnibox.SuggestRequests", request_value
,
87 MAX_SUGGEST_REQUEST_HISTOGRAM_VALUE
);
90 bool HasMultipleWords(const base::string16
& text
) {
91 base::i18n::BreakIterator
i(text
, base::i18n::BreakIterator::BREAK_WORD
);
92 bool found_word
= false;
105 AutocompleteMatchType::Type
GetAutocompleteMatchType(const std::string
& type
) {
106 if (type
== "ENTITY")
107 return AutocompleteMatchType::SEARCH_SUGGEST_ENTITY
;
108 if (type
== "INFINITE")
109 return AutocompleteMatchType::SEARCH_SUGGEST_INFINITE
;
110 if (type
== "PERSONALIZED")
111 return AutocompleteMatchType::SEARCH_SUGGEST_PERSONALIZED
;
112 if (type
== "PROFILE")
113 return AutocompleteMatchType::SEARCH_SUGGEST_PROFILE
;
114 return AutocompleteMatchType::SEARCH_SUGGEST
;
120 // SuggestionDeletionHandler -------------------------------------------------
122 // This class handles making requests to the server in order to delete
123 // personalized suggestions.
124 class SuggestionDeletionHandler
: public net::URLFetcherDelegate
{
126 typedef base::Callback
<void(bool, SuggestionDeletionHandler
*)>
127 DeletionCompletedCallback
;
129 SuggestionDeletionHandler(
130 const std::string
& deletion_url
,
132 const DeletionCompletedCallback
& callback
);
134 virtual ~SuggestionDeletionHandler();
137 // net::URLFetcherDelegate:
138 virtual void OnURLFetchComplete(const net::URLFetcher
* source
) OVERRIDE
;
140 scoped_ptr
<net::URLFetcher
> deletion_fetcher_
;
141 DeletionCompletedCallback callback_
;
143 DISALLOW_COPY_AND_ASSIGN(SuggestionDeletionHandler
);
147 SuggestionDeletionHandler::SuggestionDeletionHandler(
148 const std::string
& deletion_url
,
150 const DeletionCompletedCallback
& callback
) : callback_(callback
) {
151 GURL
url(deletion_url
);
152 DCHECK(url
.is_valid());
154 deletion_fetcher_
.reset(net::URLFetcher::Create(
155 SearchProvider::kDeletionURLFetcherID
,
157 net::URLFetcher::GET
,
159 deletion_fetcher_
->SetRequestContext(profile
->GetRequestContext());
160 deletion_fetcher_
->Start();
163 SuggestionDeletionHandler::~SuggestionDeletionHandler() {
166 void SuggestionDeletionHandler::OnURLFetchComplete(
167 const net::URLFetcher
* source
) {
168 DCHECK(source
== deletion_fetcher_
.get());
170 source
->GetStatus().is_success() && (source
->GetResponseCode() == 200),
175 // SearchProvider::Providers --------------------------------------------------
177 SearchProvider::Providers::Providers(TemplateURLService
* template_url_service
)
178 : template_url_service_(template_url_service
) {
181 const TemplateURL
* SearchProvider::Providers::GetDefaultProviderURL() const {
182 return default_provider_
.empty() ? NULL
:
183 template_url_service_
->GetTemplateURLForKeyword(default_provider_
);
186 const TemplateURL
* SearchProvider::Providers::GetKeywordProviderURL() const {
187 return keyword_provider_
.empty() ? NULL
:
188 template_url_service_
->GetTemplateURLForKeyword(keyword_provider_
);
192 // SearchProvider::Result -----------------------------------------------------
194 SearchProvider::Result::Result(bool from_keyword_provider
,
196 bool relevance_from_server
)
197 : from_keyword_provider_(from_keyword_provider
),
198 relevance_(relevance
),
199 relevance_from_server_(relevance_from_server
) {
202 SearchProvider::Result::~Result() {
206 // SearchProvider::SuggestResult ----------------------------------------------
208 SearchProvider::SuggestResult::SuggestResult(
209 const base::string16
& suggestion
,
210 AutocompleteMatchType::Type type
,
211 const base::string16
& match_contents
,
212 const base::string16
& annotation
,
213 const std::string
& suggest_query_params
,
214 const std::string
& deletion_url
,
215 bool from_keyword_provider
,
217 bool relevance_from_server
,
218 bool should_prefetch
,
219 const base::string16
& input_text
)
220 : Result(from_keyword_provider
, relevance
, relevance_from_server
),
221 suggestion_(suggestion
),
223 annotation_(annotation
),
224 suggest_query_params_(suggest_query_params
),
225 deletion_url_(deletion_url
),
226 should_prefetch_(should_prefetch
) {
227 match_contents_
= match_contents
;
228 DCHECK(!match_contents_
.empty());
229 ClassifyMatchContents(true, input_text
);
232 SearchProvider::SuggestResult::~SuggestResult() {
235 void SearchProvider::SuggestResult::ClassifyMatchContents(
236 const bool allow_bolding_all
,
237 const base::string16
& input_text
) {
238 size_t input_position
= match_contents_
.find(input_text
);
239 if (!allow_bolding_all
&& (input_position
== base::string16::npos
)) {
240 // Bail if the code below to update the bolding would bold the whole
241 // string. Note that the string may already be entirely bolded; if
242 // so, leave it as is.
245 match_contents_class_
.clear();
246 // We do intra-string highlighting for suggestions - the suggested segment
247 // will be highlighted, e.g. for input_text = "you" the suggestion may be
248 // "youtube", so we'll bold the "tube" section: you*tube*.
249 if (input_text
!= match_contents_
) {
250 if (input_position
== base::string16::npos
) {
251 // The input text is not a substring of the query string, e.g. input
252 // text is "slasdot" and the query string is "slashdot", so we bold the
254 match_contents_class_
.push_back(ACMatchClassification(
255 0, ACMatchClassification::MATCH
));
257 // We don't iterate over the string here annotating all matches because
258 // it looks odd to have every occurrence of a substring that may be as
259 // short as a single character highlighted in a query suggestion result,
260 // e.g. for input text "s" and query string "southwest airlines", it
261 // looks odd if both the first and last s are highlighted.
262 if (input_position
!= 0) {
263 match_contents_class_
.push_back(ACMatchClassification(
264 0, ACMatchClassification::MATCH
));
266 match_contents_class_
.push_back(
267 ACMatchClassification(input_position
, ACMatchClassification::NONE
));
268 size_t next_fragment_position
= input_position
+ input_text
.length();
269 if (next_fragment_position
< match_contents_
.length()) {
270 match_contents_class_
.push_back(ACMatchClassification(
271 next_fragment_position
, ACMatchClassification::MATCH
));
275 // Otherwise, match_contents_ is a verbatim (what-you-typed) match, either
276 // for the default provider or a keyword search provider.
277 match_contents_class_
.push_back(ACMatchClassification(
278 0, ACMatchClassification::NONE
));
282 bool SearchProvider::SuggestResult::IsInlineable(
283 const base::string16
& input
) const {
284 return StartsWith(suggestion_
, input
, false);
287 int SearchProvider::SuggestResult::CalculateRelevance(
288 const AutocompleteInput
& input
,
289 bool keyword_provider_requested
) const {
290 if (!from_keyword_provider_
&& keyword_provider_requested
)
292 return ((input
.type() == AutocompleteInput::URL
) ? 300 : 600);
296 // SearchProvider::NavigationResult -------------------------------------------
298 SearchProvider::NavigationResult::NavigationResult(
299 const AutocompleteProvider
& provider
,
301 const base::string16
& description
,
302 bool from_keyword_provider
,
304 bool relevance_from_server
,
305 const base::string16
& input_text
,
306 const std::string
& languages
)
307 : Result(from_keyword_provider
, relevance
, relevance_from_server
),
309 formatted_url_(AutocompleteInput::FormattedStringWithEquivalentMeaning(
310 url
, provider
.StringForURLDisplay(url
, true, false))),
311 description_(description
) {
312 DCHECK(url_
.is_valid());
313 CalculateAndClassifyMatchContents(true, input_text
, languages
);
316 SearchProvider::NavigationResult::~NavigationResult() {
319 void SearchProvider::NavigationResult::CalculateAndClassifyMatchContents(
320 const bool allow_bolding_nothing
,
321 const base::string16
& input_text
,
322 const std::string
& languages
) {
323 // First look for the user's input inside the formatted url as it would be
324 // without trimming the scheme, so we can find matches at the beginning of the
326 const URLPrefix
* prefix
=
327 URLPrefix::BestURLPrefix(formatted_url_
, input_text
);
328 size_t match_start
= (prefix
== NULL
) ?
329 formatted_url_
.find(input_text
) : prefix
->prefix
.length();
330 bool trim_http
= !AutocompleteInput::HasHTTPScheme(input_text
) &&
331 (!prefix
|| (match_start
!= 0));
332 const net::FormatUrlTypes format_types
=
333 net::kFormatUrlOmitAll
& ~(trim_http
? 0 : net::kFormatUrlOmitHTTP
);
335 base::string16 match_contents
= net::FormatUrl(url_
, languages
, format_types
,
336 net::UnescapeRule::SPACES
, NULL
, NULL
, &match_start
);
337 // If the first match in the untrimmed string was inside a scheme that we
338 // trimmed, look for a subsequent match.
339 if (match_start
== base::string16::npos
)
340 match_start
= match_contents
.find(input_text
);
341 // Update |match_contents_| and |match_contents_class_| if it's allowed.
342 if (allow_bolding_nothing
|| (match_start
!= base::string16::npos
)) {
343 match_contents_
= match_contents
;
344 // Safe if |match_start| is npos; also safe if the input is longer than the
345 // remaining contents after |match_start|.
346 AutocompleteMatch::ClassifyLocationInString(match_start
,
347 input_text
.length(), match_contents_
.length(),
348 ACMatchClassification::URL
, &match_contents_class_
);
352 bool SearchProvider::NavigationResult::IsInlineable(
353 const base::string16
& input
) const {
354 return URLPrefix::BestURLPrefix(formatted_url_
, input
) != NULL
;
357 int SearchProvider::NavigationResult::CalculateRelevance(
358 const AutocompleteInput
& input
,
359 bool keyword_provider_requested
) const {
360 return (from_keyword_provider_
|| !keyword_provider_requested
) ? 800 : 150;
364 // SearchProvider::CompareScoredResults ---------------------------------------
366 class SearchProvider::CompareScoredResults
{
368 bool operator()(const Result
& a
, const Result
& b
) {
369 // Sort in descending relevance order.
370 return a
.relevance() > b
.relevance();
375 // SearchProvider::Results ----------------------------------------------------
377 SearchProvider::Results::Results() : verbatim_relevance(-1) {
380 SearchProvider::Results::~Results() {
383 void SearchProvider::Results::Clear() {
384 suggest_results
.clear();
385 navigation_results
.clear();
386 verbatim_relevance
= -1;
390 bool SearchProvider::Results::HasServerProvidedScores() const {
391 if (verbatim_relevance
>= 0)
394 // Right now either all results of one type will be server-scored or they will
395 // all be locally scored, but in case we change this later, we'll just check
397 for (SuggestResults::const_iterator
i(suggest_results
.begin());
398 i
!= suggest_results
.end(); ++i
) {
399 if (i
->relevance_from_server())
402 for (NavigationResults::const_iterator
i(navigation_results
.begin());
403 i
!= navigation_results
.end(); ++i
) {
404 if (i
->relevance_from_server())
412 // SearchProvider -------------------------------------------------------------
415 const int SearchProvider::kDefaultProviderURLFetcherID
= 1;
416 const int SearchProvider::kKeywordProviderURLFetcherID
= 2;
417 const int SearchProvider::kDeletionURLFetcherID
= 3;
418 int SearchProvider::kMinimumTimeBetweenSuggestQueriesMs
= 100;
419 const char SearchProvider::kRelevanceFromServerKey
[] = "relevance_from_server";
420 const char SearchProvider::kShouldPrefetchKey
[] = "should_prefetch";
421 const char SearchProvider::kSuggestMetadataKey
[] = "suggest_metadata";
422 const char SearchProvider::kDeletionUrlKey
[] = "deletion_url";
423 const char SearchProvider::kTrue
[] = "true";
424 const char SearchProvider::kFalse
[] = "false";
426 SearchProvider::SearchProvider(AutocompleteProviderListener
* listener
,
428 : AutocompleteProvider(listener
, profile
,
429 AutocompleteProvider::TYPE_SEARCH
),
430 providers_(TemplateURLServiceFactory::GetForProfile(profile
)),
431 suggest_results_pending_(0),
432 field_trial_triggered_(false),
433 field_trial_triggered_in_session_(false) {
437 AutocompleteMatch
SearchProvider::CreateSearchSuggestion(
438 AutocompleteProvider
* autocomplete_provider
,
439 const AutocompleteInput
& input
,
440 const base::string16
& input_text
,
441 const SuggestResult
& suggestion
,
442 const TemplateURL
* template_url
,
443 int accepted_suggestion
,
444 int omnibox_start_margin
,
445 bool append_extra_query_params
) {
446 AutocompleteMatch
match(autocomplete_provider
, suggestion
.relevance(), false,
451 match
.keyword
= template_url
->keyword();
452 match
.contents
= suggestion
.match_contents();
453 match
.contents_class
= suggestion
.match_contents_class();
455 if (!suggestion
.annotation().empty())
456 match
.description
= suggestion
.annotation();
458 match
.allowed_to_be_default_match
=
459 (input_text
== suggestion
.match_contents());
461 // When the user forced a query, we need to make sure all the fill_into_edit
462 // values preserve that property. Otherwise, if the user starts editing a
463 // suggestion, non-Search results will suddenly appear.
464 if (input
.type() == AutocompleteInput::FORCED_QUERY
)
465 match
.fill_into_edit
.assign(base::ASCIIToUTF16("?"));
466 if (suggestion
.from_keyword_provider())
467 match
.fill_into_edit
.append(match
.keyword
+ base::char16(' '));
468 if (!input
.prevent_inline_autocomplete() &&
469 StartsWith(suggestion
.suggestion(), input_text
, false)) {
470 match
.inline_autocompletion
=
471 suggestion
.suggestion().substr(input_text
.length());
472 match
.allowed_to_be_default_match
= true;
474 match
.fill_into_edit
.append(suggestion
.suggestion());
476 const TemplateURLRef
& search_url
= template_url
->url_ref();
477 DCHECK(search_url
.SupportsReplacement());
478 match
.search_terms_args
.reset(
479 new TemplateURLRef::SearchTermsArgs(suggestion
.suggestion()));
480 match
.search_terms_args
->original_query
= input_text
;
481 match
.search_terms_args
->accepted_suggestion
= accepted_suggestion
;
482 match
.search_terms_args
->omnibox_start_margin
= omnibox_start_margin
;
483 match
.search_terms_args
->suggest_query_params
=
484 suggestion
.suggest_query_params();
485 match
.search_terms_args
->append_extra_query_params
=
486 append_extra_query_params
;
487 // This is the destination URL sans assisted query stats. This must be set
488 // so the AutocompleteController can properly de-dupe; the controller will
489 // eventually overwrite it before it reaches the user.
490 match
.destination_url
=
491 GURL(search_url
.ReplaceSearchTerms(*match
.search_terms_args
.get()));
493 // Search results don't look like URLs.
494 match
.transition
= suggestion
.from_keyword_provider() ?
495 content::PAGE_TRANSITION_KEYWORD
: content::PAGE_TRANSITION_GENERATED
;
501 bool SearchProvider::ShouldPrefetch(const AutocompleteMatch
& match
) {
502 return match
.GetAdditionalInfo(kShouldPrefetchKey
) == kTrue
;
506 std::string
SearchProvider::GetSuggestMetadata(const AutocompleteMatch
& match
) {
507 return match
.GetAdditionalInfo(kSuggestMetadataKey
);
510 void SearchProvider::AddProviderInfo(ProvidersInfo
* provider_info
) const {
511 provider_info
->push_back(metrics::OmniboxEventProto_ProviderInfo());
512 metrics::OmniboxEventProto_ProviderInfo
& new_entry
= provider_info
->back();
513 new_entry
.set_provider(AsOmniboxEventProviderType());
514 new_entry
.set_provider_done(done_
);
515 std::vector
<uint32
> field_trial_hashes
;
516 OmniboxFieldTrial::GetActiveSuggestFieldTrialHashes(&field_trial_hashes
);
517 for (size_t i
= 0; i
< field_trial_hashes
.size(); ++i
) {
518 if (field_trial_triggered_
)
519 new_entry
.mutable_field_trial_triggered()->Add(field_trial_hashes
[i
]);
520 if (field_trial_triggered_in_session_
) {
521 new_entry
.mutable_field_trial_triggered_in_session()->Add(
522 field_trial_hashes
[i
]);
527 void SearchProvider::DeleteMatch(const AutocompleteMatch
& match
) {
528 DCHECK(match
.deletable
);
530 deletion_handlers_
.push_back(new SuggestionDeletionHandler(
531 match
.GetAdditionalInfo(SearchProvider::kDeletionUrlKey
),
533 base::Bind(&SearchProvider::OnDeletionComplete
, base::Unretained(this))));
535 HistoryService
* const history_service
=
536 HistoryServiceFactory::GetForProfile(profile_
, Profile::EXPLICIT_ACCESS
);
537 TemplateURL
* template_url
= match
.GetTemplateURL(profile_
, false);
538 // This may be NULL if the template corresponding to the keyword has been
539 // deleted or there is no keyword set.
540 if (template_url
!= NULL
) {
541 history_service
->DeleteMatchingURLsForKeyword(template_url
->id(),
545 // Immediately update the list of matches to show the match was deleted,
546 // regardless of whether the server request actually succeeds.
547 DeleteMatchFromMatches(match
);
550 void SearchProvider::ResetSession() {
551 field_trial_triggered_in_session_
= false;
554 SearchProvider::~SearchProvider() {
558 void SearchProvider::RemoveStaleResults(const base::string16
& input
,
559 int verbatim_relevance
,
560 SuggestResults
* suggest_results
,
561 NavigationResults
* navigation_results
) {
562 DCHECK_GE(verbatim_relevance
, 0);
563 // Keep pointers to the head of (the highest scoring elements of)
564 // |suggest_results| and |navigation_results|. Iterate down the lists
565 // removing non-inlineable results in order of decreasing relevance
566 // scores. Stop when the highest scoring element among those remaining
567 // is inlineable or the element is less than |verbatim_relevance|.
568 // This allows non-inlineable lower-scoring results to remain
569 // because (i) they are guaranteed to not be inlined and (ii)
570 // letting them remain reduces visual jank. For instance, as the
571 // user types the mis-spelled query "fpobar" (for foobar), the
572 // suggestion "foobar" will be suggested on every keystroke. If the
573 // SearchProvider always removes all non-inlineable results, the user will
574 // see visual jitter/jank as the result disappears and re-appears moments
575 // later as the suggest server returns results.
576 SuggestResults::iterator sug_it
= suggest_results
->begin();
577 NavigationResults::iterator nav_it
= navigation_results
->begin();
578 while ((sug_it
!= suggest_results
->end()) ||
579 (nav_it
!= navigation_results
->end())) {
581 (sug_it
!= suggest_results
->end()) ? sug_it
->relevance() : -1;
583 (nav_it
!= navigation_results
->end()) ? nav_it
->relevance() : -1;
584 if (std::max(sug_rel
, nav_rel
) < verbatim_relevance
)
586 if (sug_rel
> nav_rel
) {
587 // The current top result is a search suggestion.
588 if (sug_it
->IsInlineable(input
))
590 sug_it
= suggest_results
->erase(sug_it
);
591 } else if (sug_rel
== nav_rel
) {
592 // Have both results and they're tied.
593 const bool sug_inlineable
= sug_it
->IsInlineable(input
);
594 const bool nav_inlineable
= nav_it
->IsInlineable(input
);
596 sug_it
= suggest_results
->erase(sug_it
);
598 nav_it
= navigation_results
->erase(nav_it
);
599 if (sug_inlineable
|| nav_inlineable
)
602 // The current top result is a navigational suggestion.
603 if (nav_it
->IsInlineable(input
))
605 nav_it
= navigation_results
->erase(nav_it
);
610 void SearchProvider::UpdateMatchContentsClass(const base::string16
& input_text
,
612 for (SuggestResults::iterator sug_it
= results
->suggest_results
.begin();
613 sug_it
!= results
->suggest_results
.end(); ++sug_it
) {
614 sug_it
->ClassifyMatchContents(false, input_text
);
616 const std::string
languages(
617 profile_
->GetPrefs()->GetString(prefs::kAcceptLanguages
));
618 for (NavigationResults::iterator nav_it
= results
->navigation_results
.begin();
619 nav_it
!= results
->navigation_results
.end(); ++nav_it
) {
620 nav_it
->CalculateAndClassifyMatchContents(false, input_text
, languages
);
625 int SearchProvider::CalculateRelevanceForKeywordVerbatim(
626 AutocompleteInput::Type type
,
627 bool prefer_keyword
) {
628 // This function is responsible for scoring verbatim query matches
629 // for non-extension keywords. KeywordProvider::CalculateRelevance()
630 // scores verbatim query matches for extension keywords, as well as
631 // for keyword matches (i.e., suggestions of a keyword itself, not a
632 // suggestion of a query on a keyword search engine). These two
633 // functions are currently in sync, but there's no reason we
634 // couldn't decide in the future to score verbatim matches
635 // differently for extension and non-extension keywords. If you
636 // make such a change, however, you should update this comment to
637 // describe it, so it's clear why the functions diverge.
640 return (type
== AutocompleteInput::QUERY
) ? 1450 : 1100;
643 void SearchProvider::Start(const AutocompleteInput
& input
,
644 bool minimal_changes
) {
645 // Do our best to load the model as early as possible. This will reduce
646 // odds of having the model not ready when really needed (a non-empty input).
647 TemplateURLService
* model
= providers_
.template_url_service();
652 field_trial_triggered_
= false;
654 // Can't return search/suggest results for bogus input or without a profile.
655 if (!profile_
|| (input
.type() == AutocompleteInput::INVALID
)) {
660 keyword_input_
= input
;
661 const TemplateURL
* keyword_provider
=
662 KeywordProvider::GetSubstitutingTemplateURLForInput(model
,
664 if (keyword_provider
== NULL
)
665 keyword_input_
.Clear();
666 else if (keyword_input_
.text().empty())
667 keyword_provider
= NULL
;
669 const TemplateURL
* default_provider
= model
->GetDefaultSearchProvider();
670 if (default_provider
&& !default_provider
->SupportsReplacement())
671 default_provider
= NULL
;
673 if (keyword_provider
== default_provider
)
674 default_provider
= NULL
; // No use in querying the same provider twice.
676 if (!default_provider
&& !keyword_provider
) {
677 // No valid providers.
682 // If we're still running an old query but have since changed the query text
683 // or the providers, abort the query.
684 base::string16
default_provider_keyword(default_provider
?
685 default_provider
->keyword() : base::string16());
686 base::string16
keyword_provider_keyword(keyword_provider
?
687 keyword_provider
->keyword() : base::string16());
688 if (!minimal_changes
||
689 !providers_
.equal(default_provider_keyword
, keyword_provider_keyword
)) {
690 // Cancel any in-flight suggest requests.
695 providers_
.set(default_provider_keyword
, keyword_provider_keyword
);
697 if (input
.text().empty()) {
698 // User typed "?" alone. Give them a placeholder result indicating what
700 if (default_provider
) {
701 AutocompleteMatch match
;
702 match
.provider
= this;
703 match
.contents
.assign(l10n_util::GetStringUTF16(IDS_EMPTY_KEYWORD_VALUE
));
704 match
.contents_class
.push_back(
705 ACMatchClassification(0, ACMatchClassification::NONE
));
706 match
.keyword
= providers_
.default_provider();
707 match
.allowed_to_be_default_match
= true;
708 matches_
.push_back(match
);
716 DoHistoryQuery(minimal_changes
);
717 StartOrStopSuggestQuery(minimal_changes
);
721 void SearchProvider::Stop(bool clear_cached_results
) {
725 if (clear_cached_results
)
729 void SearchProvider::OnURLFetchComplete(const net::URLFetcher
* source
) {
731 suggest_results_pending_
--;
732 LogOmniboxSuggestRequest(REPLY_RECEIVED
);
733 DCHECK_GE(suggest_results_pending_
, 0); // Should never go negative.
735 const bool is_keyword
= (source
== keyword_fetcher_
.get());
736 // Ensure the request succeeded and that the provider used is still available.
737 // A verbatim match cannot be generated without this provider, causing errors.
738 const bool request_succeeded
=
739 source
->GetStatus().is_success() && (source
->GetResponseCode() == 200) &&
741 providers_
.GetKeywordProviderURL() :
742 providers_
.GetDefaultProviderURL());
744 // Record response time for suggest requests sent to Google. We care
745 // only about the common case: the Google default provider used in
747 const TemplateURL
* default_url
= providers_
.GetDefaultProviderURL();
748 if (!is_keyword
&& default_url
&&
749 (TemplateURLPrepopulateData::GetEngineType(*default_url
) ==
750 SEARCH_ENGINE_GOOGLE
)) {
751 const base::TimeDelta elapsed_time
=
752 base::TimeTicks::Now() - time_suggest_request_sent_
;
753 if (request_succeeded
) {
754 UMA_HISTOGRAM_TIMES("Omnibox.SuggestRequest.Success.GoogleResponseTime",
757 UMA_HISTOGRAM_TIMES("Omnibox.SuggestRequest.Failure.GoogleResponseTime",
762 bool results_updated
= false;
763 if (request_succeeded
) {
764 const net::HttpResponseHeaders
* const response_headers
=
765 source
->GetResponseHeaders();
766 std::string json_data
;
767 source
->GetResponseAsString(&json_data
);
769 // JSON is supposed to be UTF-8, but some suggest service providers send
770 // JSON files in non-UTF-8 encodings. The actual encoding is usually
771 // specified in the Content-Type header field.
772 if (response_headers
) {
774 if (response_headers
->GetCharset(&charset
)) {
775 base::string16 data_16
;
776 // TODO(jungshik): Switch to CodePageToUTF8 after it's added.
777 if (base::CodepageToUTF16(json_data
, charset
.c_str(),
778 base::OnStringConversionError::FAIL
,
780 json_data
= base::UTF16ToUTF8(data_16
);
784 scoped_ptr
<base::Value
> data(DeserializeJsonData(json_data
));
785 results_updated
= data
.get() && ParseSuggestResults(data
.get(), is_keyword
);
789 if (done_
|| results_updated
)
790 listener_
->OnProviderUpdate(results_updated
);
793 void SearchProvider::OnDeletionComplete(bool success
,
794 SuggestionDeletionHandler
* handler
) {
795 RecordDeletionResult(success
);
796 SuggestionDeletionHandlers::iterator it
= std::find(
797 deletion_handlers_
.begin(), deletion_handlers_
.end(), handler
);
798 DCHECK(it
!= deletion_handlers_
.end());
799 deletion_handlers_
.erase(it
);
803 void SearchProvider::RecordDeletionResult(bool success
) {
805 content::RecordAction(
806 base::UserMetricsAction("Omnibox.ServerSuggestDelete.Success"));
808 content::RecordAction(
809 base::UserMetricsAction("Omnibox.ServerSuggestDelete.Failure"));
813 void SearchProvider::DeleteMatchFromMatches(const AutocompleteMatch
& match
) {
814 for (ACMatches::iterator
i(matches_
.begin()); i
!= matches_
.end(); ++i
) {
815 // Find the desired match to delete by checking the type and contents.
816 // We can't check the destination URL, because the autocomplete controller
817 // may have reformulated that. Not that while checking for matching
818 // contents works for personalized suggestions, if more match types gain
819 // deletion support, this algorithm may need to be re-examined.
820 if (i
->contents
== match
.contents
&& i
->type
== match
.type
) {
825 listener_
->OnProviderUpdate(true);
828 void SearchProvider::Run() {
829 // Start a new request with the current input.
830 suggest_results_pending_
= 0;
831 time_suggest_request_sent_
= base::TimeTicks::Now();
833 default_fetcher_
.reset(CreateSuggestFetcher(kDefaultProviderURLFetcherID
,
834 providers_
.GetDefaultProviderURL(), input_
));
835 keyword_fetcher_
.reset(CreateSuggestFetcher(kKeywordProviderURLFetcherID
,
836 providers_
.GetKeywordProviderURL(), keyword_input_
));
838 // Both the above can fail if the providers have been modified or deleted
839 // since the query began.
840 if (suggest_results_pending_
== 0) {
842 // We only need to update the listener if we're actually done.
844 listener_
->OnProviderUpdate(false);
848 void SearchProvider::DoHistoryQuery(bool minimal_changes
) {
849 // The history query results are synchronous, so if minimal_changes is true,
850 // we still have the last results and don't need to do anything.
854 base::TimeTicks
do_history_query_start_time(base::TimeTicks::Now());
856 keyword_history_results_
.clear();
857 default_history_results_
.clear();
859 if (OmniboxFieldTrial::SearchHistoryDisable(
860 input_
.current_page_classification()))
863 base::TimeTicks
start_time(base::TimeTicks::Now());
864 HistoryService
* const history_service
=
865 HistoryServiceFactory::GetForProfile(profile_
, Profile::EXPLICIT_ACCESS
);
866 base::TimeTicks
now(base::TimeTicks::Now());
867 UMA_HISTOGRAM_TIMES("Omnibox.SearchProvider.GetHistoryServiceTime",
870 history::URLDatabase
* url_db
= history_service
?
871 history_service
->InMemoryDatabase() : NULL
;
872 UMA_HISTOGRAM_TIMES("Omnibox.SearchProvider.InMemoryDatabaseTime",
873 base::TimeTicks::Now() - start_time
);
877 // Request history for both the keyword and default provider. We grab many
878 // more matches than we'll ultimately clamp to so that if there are several
879 // recent multi-word matches who scores are lowered (see
880 // AddHistoryResultsToMap()), they won't crowd out older, higher-scoring
881 // matches. Note that this doesn't fix the problem entirely, but merely
882 // limits it to cases with a very large number of such multi-word matches; for
883 // now, this seems OK compared with the complexity of a real fix, which would
884 // require multiple searches and tracking of "single- vs. multi-word" in the
886 int num_matches
= kMaxMatches
* 5;
887 const TemplateURL
* default_url
= providers_
.GetDefaultProviderURL();
889 start_time
= base::TimeTicks::Now();
890 url_db
->GetMostRecentKeywordSearchTerms(default_url
->id(), input_
.text(),
891 num_matches
, &default_history_results_
);
893 "Omnibox.SearchProvider.GetMostRecentKeywordTermsDefaultProviderTime",
894 base::TimeTicks::Now() - start_time
);
896 const TemplateURL
* keyword_url
= providers_
.GetKeywordProviderURL();
898 url_db
->GetMostRecentKeywordSearchTerms(keyword_url
->id(),
899 keyword_input_
.text(), num_matches
, &keyword_history_results_
);
901 UMA_HISTOGRAM_TIMES("Omnibox.SearchProvider.DoHistoryQueryTime",
902 base::TimeTicks::Now() - do_history_query_start_time
);
905 void SearchProvider::StartOrStopSuggestQuery(bool minimal_changes
) {
906 if (!IsQuerySuitableForSuggest()) {
912 // For the minimal_changes case, if we finished the previous query and still
913 // have its results, or are allowed to keep running it, just do that, rather
914 // than starting a new query.
915 if (minimal_changes
&&
916 (!default_results_
.suggest_results
.empty() ||
917 !default_results_
.navigation_results
.empty() ||
918 !keyword_results_
.suggest_results
.empty() ||
919 !keyword_results_
.navigation_results
.empty() ||
921 input_
.matches_requested() == AutocompleteInput::ALL_MATCHES
)))
924 // We can't keep running any previous query, so halt it.
927 // Remove existing results that cannot inline autocomplete the new input.
928 RemoveAllStaleResults();
930 // Update the content classifications of remaining results so they look good
931 // against the current input.
932 UpdateMatchContentsClass(input_
.text(), &default_results_
);
933 if (!keyword_input_
.text().empty())
934 UpdateMatchContentsClass(keyword_input_
.text(), &keyword_results_
);
936 // We can't start a new query if we're only allowed synchronous results.
937 if (input_
.matches_requested() != AutocompleteInput::ALL_MATCHES
)
940 // To avoid flooding the suggest server, don't send a query until at
941 // least 100 ms since the last query.
942 base::TimeTicks
next_suggest_time(time_suggest_request_sent_
+
943 base::TimeDelta::FromMilliseconds(kMinimumTimeBetweenSuggestQueriesMs
));
944 base::TimeTicks
now(base::TimeTicks::Now());
945 if (now
>= next_suggest_time
) {
949 timer_
.Start(FROM_HERE
, next_suggest_time
- now
, this, &SearchProvider::Run
);
952 bool SearchProvider::IsQuerySuitableForSuggest() const {
953 // Don't run Suggest in incognito mode, if the engine doesn't support it, or
954 // if the user has disabled it.
955 const TemplateURL
* default_url
= providers_
.GetDefaultProviderURL();
956 const TemplateURL
* keyword_url
= providers_
.GetKeywordProviderURL();
957 if (profile_
->IsOffTheRecord() ||
958 ((!default_url
|| default_url
->suggestions_url().empty()) &&
959 (!keyword_url
|| keyword_url
->suggestions_url().empty())) ||
960 !profile_
->GetPrefs()->GetBoolean(prefs::kSearchSuggestEnabled
))
963 // If the input type might be a URL, we take extra care so that private data
964 // isn't sent to the server.
966 // FORCED_QUERY means the user is explicitly asking us to search for this, so
967 // we assume it isn't a URL and/or there isn't private data.
968 if (input_
.type() == AutocompleteInput::FORCED_QUERY
)
971 // Next we check the scheme. If this is UNKNOWN/URL with a scheme that isn't
972 // http/https/ftp, we shouldn't send it. Sending things like file: and data:
973 // is both a waste of time and a disclosure of potentially private, local
974 // data. Other "schemes" may actually be usernames, and we don't want to send
975 // passwords. If the scheme is OK, we still need to check other cases below.
976 // If this is QUERY, then the presence of these schemes means the user
977 // explicitly typed one, and thus this is probably a URL that's being entered
978 // and happens to currently be invalid -- in which case we again want to run
979 // our checks below. Other QUERY cases are less likely to be URLs and thus we
981 if (!LowerCaseEqualsASCII(input_
.scheme(), content::kHttpScheme
) &&
982 !LowerCaseEqualsASCII(input_
.scheme(), content::kHttpsScheme
) &&
983 !LowerCaseEqualsASCII(input_
.scheme(), content::kFtpScheme
))
984 return (input_
.type() == AutocompleteInput::QUERY
);
986 // Don't send URLs with usernames, queries or refs. Some of these are
987 // private, and the Suggest server is unlikely to have any useful results
988 // for any of them. Also don't send URLs with ports, as we may initially
989 // think that a username + password is a host + port (and we don't want to
990 // send usernames/passwords), and even if the port really is a port, the
991 // server is once again unlikely to have and useful results.
992 // Note that we only block based on refs if the input is URL-typed, as search
993 // queries can legitimately have #s in them which the URL parser
994 // overaggressively categorizes as a url with a ref.
995 const url_parse::Parsed
& parts
= input_
.parts();
996 if (parts
.username
.is_nonempty() || parts
.port
.is_nonempty() ||
997 parts
.query
.is_nonempty() ||
998 (parts
.ref
.is_nonempty() && (input_
.type() == AutocompleteInput::URL
)))
1001 // Don't send anything for https except the hostname. Hostnames are OK
1002 // because they are visible when the TCP connection is established, but the
1003 // specific path may reveal private information.
1004 if (LowerCaseEqualsASCII(input_
.scheme(), content::kHttpsScheme
) &&
1005 parts
.path
.is_nonempty())
1011 void SearchProvider::StopSuggest() {
1012 // Increment the appropriate field in the histogram by the number of
1013 // pending requests that were invalidated.
1014 for (int i
= 0; i
< suggest_results_pending_
; i
++)
1015 LogOmniboxSuggestRequest(REQUEST_INVALIDATED
);
1016 suggest_results_pending_
= 0;
1018 // Stop any in-progress URL fetches.
1019 keyword_fetcher_
.reset();
1020 default_fetcher_
.reset();
1023 void SearchProvider::ClearAllResults() {
1024 keyword_results_
.Clear();
1025 default_results_
.Clear();
1028 void SearchProvider::RemoveAllStaleResults() {
1029 // We only need to remove stale results (which ensures the top-scoring
1030 // match is inlineable) if the user is not in reorder mode. In reorder
1031 // mode, the autocomplete system will reorder results to make sure the
1032 // top result is inlineable.
1033 const bool omnibox_will_reorder_for_legal_default_match
=
1034 OmniboxFieldTrial::ReorderForLegalDefaultMatch(
1035 input_
.current_page_classification());
1036 // In theory it would be better to run an algorithm like that in
1037 // RemoveStaleResults(...) below that uses all four results lists
1038 // and both verbatim scores at once. However, that will be much
1039 // more complicated for little obvious gain. For code simplicity
1040 // and ease in reasoning about the invariants involved, this code
1041 // removes stales results from the keyword provider and default
1042 // provider independently.
1043 if (!omnibox_will_reorder_for_legal_default_match
) {
1044 RemoveStaleResults(input_
.text(), GetVerbatimRelevance(NULL
),
1045 &default_results_
.suggest_results
,
1046 &default_results_
.navigation_results
);
1047 if (!keyword_input_
.text().empty()) {
1048 RemoveStaleResults(keyword_input_
.text(),
1049 GetKeywordVerbatimRelevance(NULL
),
1050 &keyword_results_
.suggest_results
,
1051 &keyword_results_
.navigation_results
);
1054 if (keyword_input_
.text().empty()) {
1055 // User is either in keyword mode with a blank input or out of
1056 // keyword mode entirely.
1057 keyword_results_
.Clear();
1061 void SearchProvider::ApplyCalculatedRelevance() {
1062 ApplyCalculatedSuggestRelevance(&keyword_results_
.suggest_results
);
1063 ApplyCalculatedSuggestRelevance(&default_results_
.suggest_results
);
1064 ApplyCalculatedNavigationRelevance(&keyword_results_
.navigation_results
);
1065 ApplyCalculatedNavigationRelevance(&default_results_
.navigation_results
);
1066 default_results_
.verbatim_relevance
= -1;
1067 keyword_results_
.verbatim_relevance
= -1;
1070 void SearchProvider::ApplyCalculatedSuggestRelevance(SuggestResults
* list
) {
1071 for (size_t i
= 0; i
< list
->size(); ++i
) {
1072 SuggestResult
& result
= (*list
)[i
];
1073 result
.set_relevance(
1074 result
.CalculateRelevance(input_
, providers_
.has_keyword_provider()) +
1075 (list
->size() - i
- 1));
1076 result
.set_relevance_from_server(false);
1080 void SearchProvider::ApplyCalculatedNavigationRelevance(
1081 NavigationResults
* list
) {
1082 for (size_t i
= 0; i
< list
->size(); ++i
) {
1083 NavigationResult
& result
= (*list
)[i
];
1084 result
.set_relevance(
1085 result
.CalculateRelevance(input_
, providers_
.has_keyword_provider()) +
1086 (list
->size() - i
- 1));
1087 result
.set_relevance_from_server(false);
1091 net::URLFetcher
* SearchProvider::CreateSuggestFetcher(
1093 const TemplateURL
* template_url
,
1094 const AutocompleteInput
& input
) {
1095 if (!template_url
|| template_url
->suggestions_url().empty())
1098 // Bail if the suggestion URL is invalid with the given replacements.
1099 TemplateURLRef::SearchTermsArgs
search_term_args(input
.text());
1100 search_term_args
.cursor_position
= input
.cursor_position();
1101 search_term_args
.page_classification
= input
.current_page_classification();
1102 GURL
suggest_url(template_url
->suggestions_url_ref().ReplaceSearchTerms(
1104 if (!suggest_url
.is_valid())
1106 // Send the current page URL if user setting and URL requirements are met and
1107 // the user is in the field trial.
1108 if (CanSendURL(current_page_url_
, suggest_url
, template_url
,
1109 input
.current_page_classification(), profile_
) &&
1110 OmniboxFieldTrial::InZeroSuggestAfterTypingFieldTrial()) {
1111 search_term_args
.current_page_url
= current_page_url_
.spec();
1112 // Create the suggest URL again with the current page URL.
1113 suggest_url
= GURL(template_url
->suggestions_url_ref().ReplaceSearchTerms(
1117 suggest_results_pending_
++;
1118 LogOmniboxSuggestRequest(REQUEST_SENT
);
1120 net::URLFetcher
* fetcher
=
1121 net::URLFetcher::Create(id
, suggest_url
, net::URLFetcher::GET
, this);
1122 fetcher
->SetRequestContext(profile_
->GetRequestContext());
1123 fetcher
->SetLoadFlags(net::LOAD_DO_NOT_SAVE_COOKIES
);
1124 // Add Chrome experiment state to the request headers.
1125 net::HttpRequestHeaders headers
;
1126 chrome_variations::VariationsHttpHeaderProvider::GetInstance()->AppendHeaders(
1127 fetcher
->GetOriginalURL(), profile_
->IsOffTheRecord(), false, &headers
);
1128 fetcher
->SetExtraRequestHeaders(headers
.ToString());
1133 scoped_ptr
<base::Value
> SearchProvider::DeserializeJsonData(
1134 std::string json_data
) {
1135 // The JSON response should be an array.
1136 for (size_t response_start_index
= json_data
.find("["), i
= 0;
1137 response_start_index
!= std::string::npos
&& i
< 5;
1138 response_start_index
= json_data
.find("[", 1), i
++) {
1139 // Remove any XSSI guards to allow for JSON parsing.
1140 if (response_start_index
> 0)
1141 json_data
.erase(0, response_start_index
);
1143 JSONStringValueSerializer
deserializer(json_data
);
1144 deserializer
.set_allow_trailing_comma(true);
1146 scoped_ptr
<base::Value
> data(deserializer
.Deserialize(&error_code
, NULL
));
1147 if (error_code
== 0)
1150 return scoped_ptr
<base::Value
>();
1153 bool SearchProvider::ParseSuggestResults(base::Value
* root_val
,
1155 base::string16 query
;
1156 base::ListValue
* root_list
= NULL
;
1157 base::ListValue
* results_list
= NULL
;
1158 const base::string16
& input_text
=
1159 is_keyword
? keyword_input_
.text() : input_
.text();
1160 if (!root_val
->GetAsList(&root_list
) || !root_list
->GetString(0, &query
) ||
1161 (query
!= input_text
) || !root_list
->GetList(1, &results_list
))
1164 // 3rd element: Description list.
1165 base::ListValue
* descriptions
= NULL
;
1166 root_list
->GetList(2, &descriptions
);
1168 // 4th element: Disregard the query URL list for now.
1170 // Reset suggested relevance information from the default provider.
1171 Results
* results
= is_keyword
? &keyword_results_
: &default_results_
;
1172 results
->verbatim_relevance
= -1;
1174 // 5th element: Optional key-value pairs from the Suggest server.
1175 base::ListValue
* types
= NULL
;
1176 base::ListValue
* relevances
= NULL
;
1177 base::ListValue
* suggestion_details
= NULL
;
1178 base::DictionaryValue
* extras
= NULL
;
1179 int prefetch_index
= -1;
1180 if (root_list
->GetDictionary(4, &extras
)) {
1181 extras
->GetList("google:suggesttype", &types
);
1183 // Discard this list if its size does not match that of the suggestions.
1184 if (extras
->GetList("google:suggestrelevance", &relevances
) &&
1185 (relevances
->GetSize() != results_list
->GetSize()))
1187 extras
->GetInteger("google:verbatimrelevance",
1188 &results
->verbatim_relevance
);
1190 // Check if the active suggest field trial (if any) has triggered either
1191 // for the default provider or keyword provider.
1192 bool triggered
= false;
1193 extras
->GetBoolean("google:fieldtrialtriggered", &triggered
);
1194 field_trial_triggered_
|= triggered
;
1195 field_trial_triggered_in_session_
|= triggered
;
1197 base::DictionaryValue
* client_data
= NULL
;
1198 if (extras
->GetDictionary("google:clientdata", &client_data
) && client_data
)
1199 client_data
->GetInteger("phi", &prefetch_index
);
1201 if (extras
->GetList("google:suggestdetail", &suggestion_details
) &&
1202 suggestion_details
->GetSize() != results_list
->GetSize())
1203 suggestion_details
= NULL
;
1205 // Store the metadata that came with the response in case we need to pass it
1206 // along with the prefetch query to Instant.
1207 JSONStringValueSerializer
json_serializer(&results
->metadata
);
1208 json_serializer
.Serialize(*extras
);
1211 // Clear the previous results now that new results are available.
1212 results
->suggest_results
.clear();
1213 results
->navigation_results
.clear();
1215 base::string16 suggestion
;
1218 // Prohibit navsuggest in FORCED_QUERY mode. Users wants queries, not URLs.
1219 const bool allow_navsuggest
=
1220 (is_keyword
? keyword_input_
.type() : input_
.type()) !=
1221 AutocompleteInput::FORCED_QUERY
;
1222 const std::string
languages(
1223 profile_
->GetPrefs()->GetString(prefs::kAcceptLanguages
));
1224 for (size_t index
= 0; results_list
->GetString(index
, &suggestion
); ++index
) {
1225 // Google search may return empty suggestions for weird input characters,
1226 // they make no sense at all and can cause problems in our code.
1227 if (suggestion
.empty())
1230 // Apply valid suggested relevance scores; discard invalid lists.
1231 if (relevances
!= NULL
&& !relevances
->GetInteger(index
, &relevance
))
1233 if (types
&& types
->GetString(index
, &type
) && (type
== "NAVIGATION")) {
1234 // Do not blindly trust the URL coming from the server to be valid.
1235 GURL
url(URLFixerUpper::FixupURL(
1236 base::UTF16ToUTF8(suggestion
), std::string()));
1237 if (url
.is_valid() && allow_navsuggest
) {
1238 base::string16 title
;
1239 if (descriptions
!= NULL
)
1240 descriptions
->GetString(index
, &title
);
1241 results
->navigation_results
.push_back(NavigationResult(
1242 *this, url
, title
, is_keyword
, relevance
, true, input_text
,
1246 AutocompleteMatchType::Type match_type
= GetAutocompleteMatchType(type
);
1247 bool should_prefetch
= static_cast<int>(index
) == prefetch_index
;
1248 base::DictionaryValue
* suggestion_detail
= NULL
;
1249 base::string16 match_contents
= suggestion
;
1250 base::string16 annotation
;
1251 std::string suggest_query_params
;
1252 std::string deletion_url
;
1254 if (suggestion_details
) {
1255 suggestion_details
->GetDictionary(index
, &suggestion_detail
);
1256 if (suggestion_detail
) {
1257 suggestion_detail
->GetString("du", &deletion_url
);
1258 suggestion_detail
->GetString("title", &match_contents
) ||
1259 suggestion_detail
->GetString("t", &match_contents
);
1260 // Error correction for bad data from server.
1261 if (match_contents
.empty())
1262 match_contents
= suggestion
;
1263 suggestion_detail
->GetString("annotation", &annotation
) ||
1264 suggestion_detail
->GetString("a", &annotation
);
1265 suggestion_detail
->GetString("query_params", &suggest_query_params
) ||
1266 suggestion_detail
->GetString("q", &suggest_query_params
);
1270 // TODO(kochi): Improve calculator suggestion presentation.
1271 results
->suggest_results
.push_back(SuggestResult(
1272 suggestion
, match_type
, match_contents
, annotation
,
1273 suggest_query_params
, deletion_url
, is_keyword
, relevance
, true,
1274 should_prefetch
, input_text
));
1278 // Ignore suggested scores for non-keyword matches in keyword mode; if the
1279 // server is allowed to score these, it could interfere with the user's
1280 // ability to get good keyword results.
1281 const bool abandon_suggested_scores
=
1282 !is_keyword
&& !providers_
.keyword_provider().empty();
1283 // Apply calculated relevance scores to suggestions if a valid list was
1284 // not provided or we're abandoning suggested scores entirely.
1285 if ((relevances
== NULL
) || abandon_suggested_scores
) {
1286 ApplyCalculatedSuggestRelevance(&results
->suggest_results
);
1287 ApplyCalculatedNavigationRelevance(&results
->navigation_results
);
1288 // If abandoning scores entirely, also abandon the verbatim score.
1289 if (abandon_suggested_scores
)
1290 results
->verbatim_relevance
= -1;
1293 // Keep the result lists sorted.
1294 const CompareScoredResults comparator
= CompareScoredResults();
1295 std::stable_sort(results
->suggest_results
.begin(),
1296 results
->suggest_results
.end(),
1298 std::stable_sort(results
->navigation_results
.begin(),
1299 results
->navigation_results
.end(),
1304 void SearchProvider::ConvertResultsToAutocompleteMatches() {
1305 // Convert all the results to matches and add them to a map, so we can keep
1306 // the most relevant match for each result.
1307 base::TimeTicks
start_time(base::TimeTicks::Now());
1309 const base::Time no_time
;
1310 int did_not_accept_keyword_suggestion
=
1311 keyword_results_
.suggest_results
.empty() ?
1312 TemplateURLRef::NO_SUGGESTIONS_AVAILABLE
:
1313 TemplateURLRef::NO_SUGGESTION_CHOSEN
;
1315 bool relevance_from_server
;
1316 int verbatim_relevance
= GetVerbatimRelevance(&relevance_from_server
);
1317 int did_not_accept_default_suggestion
=
1318 default_results_
.suggest_results
.empty() ?
1319 TemplateURLRef::NO_SUGGESTIONS_AVAILABLE
:
1320 TemplateURLRef::NO_SUGGESTION_CHOSEN
;
1321 if (verbatim_relevance
> 0) {
1322 SuggestResult
verbatim(
1323 input_
.text(), AutocompleteMatchType::SEARCH_WHAT_YOU_TYPED
,
1324 input_
.text(), base::string16(), std::string(), std::string(), false,
1325 verbatim_relevance
, relevance_from_server
, false, input_
.text());
1326 AddMatchToMap(verbatim
, input_
.text(), std::string(),
1327 did_not_accept_default_suggestion
, &map
);
1329 if (!keyword_input_
.text().empty()) {
1330 const TemplateURL
* keyword_url
= providers_
.GetKeywordProviderURL();
1331 // We only create the verbatim search query match for a keyword
1332 // if it's not an extension keyword. Extension keywords are handled
1333 // in KeywordProvider::Start(). (Extensions are complicated...)
1334 // Note: in this provider, SEARCH_OTHER_ENGINE must correspond
1335 // to the keyword verbatim search query. Do not create other matches
1336 // of type SEARCH_OTHER_ENGINE.
1338 (keyword_url
->GetType() != TemplateURL::OMNIBOX_API_EXTENSION
)) {
1339 bool keyword_relevance_from_server
;
1340 const int keyword_verbatim_relevance
=
1341 GetKeywordVerbatimRelevance(&keyword_relevance_from_server
);
1342 if (keyword_verbatim_relevance
> 0) {
1343 SuggestResult
verbatim(
1344 keyword_input_
.text(), AutocompleteMatchType::SEARCH_OTHER_ENGINE
,
1345 keyword_input_
.text(), base::string16(), std::string(),
1346 std::string(), true, keyword_verbatim_relevance
,
1347 keyword_relevance_from_server
, false, keyword_input_
.text());
1348 AddMatchToMap(verbatim
, keyword_input_
.text(), std::string(),
1349 did_not_accept_keyword_suggestion
, &map
);
1353 AddHistoryResultsToMap(keyword_history_results_
, true,
1354 did_not_accept_keyword_suggestion
, &map
);
1355 AddHistoryResultsToMap(default_history_results_
, false,
1356 did_not_accept_default_suggestion
, &map
);
1358 AddSuggestResultsToMap(keyword_results_
.suggest_results
,
1359 keyword_results_
.metadata
, &map
);
1360 AddSuggestResultsToMap(default_results_
.suggest_results
,
1361 default_results_
.metadata
, &map
);
1364 for (MatchMap::const_iterator
i(map
.begin()); i
!= map
.end(); ++i
)
1365 matches
.push_back(i
->second
);
1367 AddNavigationResultsToMatches(keyword_results_
.navigation_results
, &matches
);
1368 AddNavigationResultsToMatches(default_results_
.navigation_results
, &matches
);
1370 // Now add the most relevant matches to |matches_|. We take up to kMaxMatches
1371 // suggest/navsuggest matches, regardless of origin. If Instant Extended is
1372 // enabled and we have server-provided (and thus hopefully more accurate)
1373 // scores for some suggestions, we allow more of those, until we reach
1374 // AutocompleteResult::kMaxMatches total matches (that is, enough to fill the
1377 // We will always return any verbatim matches, no matter how we obtained their
1378 // scores, unless we have already accepted AutocompleteResult::kMaxMatches
1379 // higher-scoring matches under the conditions above.
1380 UMA_HISTOGRAM_CUSTOM_COUNTS(
1381 "Omnibox.SearchProvider.NumMatchesToSort", matches
.size(), 1, 50, 20);
1382 std::sort(matches
.begin(), matches
.end(), &AutocompleteMatch::MoreRelevant
);
1385 size_t num_suggestions
= 0;
1386 for (ACMatches::const_iterator
i(matches
.begin());
1387 (i
!= matches
.end()) &&
1388 (matches_
.size() < AutocompleteResult::kMaxMatches
);
1390 // SEARCH_OTHER_ENGINE is only used in the SearchProvider for the keyword
1391 // verbatim result, so this condition basically means "if this match is a
1392 // suggestion of some sort".
1393 if ((i
->type
!= AutocompleteMatchType::SEARCH_WHAT_YOU_TYPED
) &&
1394 (i
->type
!= AutocompleteMatchType::SEARCH_OTHER_ENGINE
)) {
1395 // If we've already hit the limit on non-server-scored suggestions, and
1396 // this isn't a server-scored suggestion we can add, skip it.
1397 if ((num_suggestions
>= kMaxMatches
) &&
1398 (!chrome::IsInstantExtendedAPIEnabled() ||
1399 (i
->GetAdditionalInfo(kRelevanceFromServerKey
) != kTrue
))) {
1406 matches_
.push_back(*i
);
1408 UMA_HISTOGRAM_TIMES("Omnibox.SearchProvider.ConvertResultsTime",
1409 base::TimeTicks::Now() - start_time
);
1412 ACMatches::const_iterator
SearchProvider::FindTopMatch(
1413 bool autocomplete_result_will_reorder_for_default_match
) const {
1414 if (!autocomplete_result_will_reorder_for_default_match
)
1415 return matches_
.begin();
1416 ACMatches::const_iterator it
= matches_
.begin();
1417 while ((it
!= matches_
.end()) && !it
->allowed_to_be_default_match
)
1422 bool SearchProvider::IsTopMatchNavigationInKeywordMode(
1423 bool autocomplete_result_will_reorder_for_default_match
) const {
1424 ACMatches::const_iterator first_match
=
1425 FindTopMatch(autocomplete_result_will_reorder_for_default_match
);
1426 return !providers_
.keyword_provider().empty() &&
1427 (first_match
!= matches_
.end()) &&
1428 (first_match
->type
== AutocompleteMatchType::NAVSUGGEST
);
1431 bool SearchProvider::HasKeywordDefaultMatchInKeywordMode() const {
1432 const TemplateURL
* keyword_url
= providers_
.GetKeywordProviderURL();
1433 // If the user is not in keyword mode, return true to say that this
1434 // constraint is not violated.
1435 if (keyword_url
== NULL
)
1437 for (ACMatches::const_iterator it
= matches_
.begin(); it
!= matches_
.end();
1439 if ((it
->keyword
== keyword_url
->keyword()) &&
1440 it
->allowed_to_be_default_match
)
1446 bool SearchProvider::IsTopMatchScoreTooLow(
1447 bool autocomplete_result_will_reorder_for_default_match
) const {
1448 // In reorder mode, there's no such thing as a score that's too low.
1449 if (autocomplete_result_will_reorder_for_default_match
)
1452 // Here we use CalculateRelevanceForVerbatimIgnoringKeywordModeState()
1453 // rather than CalculateRelevanceForVerbatim() because the latter returns
1454 // a very low score (250) if keyword mode is active. This is because
1455 // when keyword mode is active the user probably wants the keyword matches,
1456 // not matches from the default provider. Hence, we use the version of
1457 // the function that ignores whether keyword mode is active. This allows
1458 // SearchProvider to maintain its contract with the AutocompleteController
1459 // that it will always provide an inlineable match with a reasonable
1461 return matches_
.front().relevance
<
1462 CalculateRelevanceForVerbatimIgnoringKeywordModeState();
1465 bool SearchProvider::IsTopMatchSearchWithURLInput(
1466 bool autocomplete_result_will_reorder_for_default_match
) const {
1467 ACMatches::const_iterator first_match
=
1468 FindTopMatch(autocomplete_result_will_reorder_for_default_match
);
1469 return (input_
.type() == AutocompleteInput::URL
) &&
1470 (first_match
!= matches_
.end()) &&
1471 (first_match
->relevance
> CalculateRelevanceForVerbatim()) &&
1472 (first_match
->type
!= AutocompleteMatchType::NAVSUGGEST
);
1475 bool SearchProvider::HasValidDefaultMatch(
1476 bool autocomplete_result_will_reorder_for_default_match
) const {
1477 // One of the SearchProvider matches may need to be the overall default. If
1478 // AutocompleteResult is allowed to reorder matches, this means we simply
1479 // need at least one match in the list to be |allowed_to_be_default_match|.
1480 // If no reordering is possible, however, then our first match needs to have
1482 for (ACMatches::const_iterator it
= matches_
.begin(); it
!= matches_
.end();
1484 if (it
->allowed_to_be_default_match
)
1486 if (!autocomplete_result_will_reorder_for_default_match
)
1492 void SearchProvider::UpdateMatches() {
1493 base::TimeTicks
update_matches_start_time(base::TimeTicks::Now());
1494 ConvertResultsToAutocompleteMatches();
1496 // Check constraints that may be violated by suggested relevances.
1497 if (!matches_
.empty() &&
1498 (default_results_
.HasServerProvidedScores() ||
1499 keyword_results_
.HasServerProvidedScores())) {
1500 // These blocks attempt to repair undesirable behavior by suggested
1501 // relevances with minimal impact, preserving other suggested relevances.
1503 // True if the omnibox will reorder matches as necessary to make the first
1504 // one something that is allowed to be the default match.
1505 const bool omnibox_will_reorder_for_legal_default_match
=
1506 OmniboxFieldTrial::ReorderForLegalDefaultMatch(
1507 input_
.current_page_classification());
1508 if (IsTopMatchNavigationInKeywordMode(
1509 omnibox_will_reorder_for_legal_default_match
)) {
1510 // Correct the suggested relevance scores if the top match is a
1511 // navigation in keyword mode, since inlining a navigation match
1512 // would break the user out of keyword mode. This will only be
1513 // triggered in regular (non-reorder) mode; in reorder mode,
1514 // navigation matches are marked as not allowed to be the default
1515 // match and hence IsTopMatchNavigation() will always return false.
1516 DCHECK(!omnibox_will_reorder_for_legal_default_match
);
1517 DemoteKeywordNavigationMatchesPastTopQuery();
1518 ConvertResultsToAutocompleteMatches();
1519 DCHECK(!IsTopMatchNavigationInKeywordMode(
1520 omnibox_will_reorder_for_legal_default_match
));
1522 if (!HasKeywordDefaultMatchInKeywordMode()) {
1523 // In keyword mode, disregard the keyword verbatim suggested relevance
1524 // if necessary so there at least one keyword match that's allowed to
1525 // be the default match.
1526 keyword_results_
.verbatim_relevance
= -1;
1527 ConvertResultsToAutocompleteMatches();
1529 if (IsTopMatchScoreTooLow(omnibox_will_reorder_for_legal_default_match
)) {
1530 // Disregard the suggested verbatim relevance if the top score is below
1531 // the usual verbatim value. For example, a BarProvider may rely on
1532 // SearchProvider's verbatim or inlineable matches for input "foo" (all
1533 // allowed to be default match) to always outrank its own lowly-ranked
1534 // "bar" matches that shouldn't be the default match.
1535 default_results_
.verbatim_relevance
= -1;
1536 keyword_results_
.verbatim_relevance
= -1;
1537 ConvertResultsToAutocompleteMatches();
1539 if (IsTopMatchSearchWithURLInput(
1540 omnibox_will_reorder_for_legal_default_match
)) {
1541 // Disregard the suggested search and verbatim relevances if the input
1542 // type is URL and the top match is a highly-ranked search suggestion.
1543 // For example, prevent a search for "foo.com" from outranking another
1544 // provider's navigation for "foo.com" or "foo.com/url_from_history".
1545 ApplyCalculatedSuggestRelevance(&keyword_results_
.suggest_results
);
1546 ApplyCalculatedSuggestRelevance(&default_results_
.suggest_results
);
1547 default_results_
.verbatim_relevance
= -1;
1548 keyword_results_
.verbatim_relevance
= -1;
1549 ConvertResultsToAutocompleteMatches();
1551 if (!HasValidDefaultMatch(omnibox_will_reorder_for_legal_default_match
)) {
1552 // If the omnibox is not going to reorder results to put a legal default
1553 // match at the top, then this provider needs to guarantee that its top
1554 // scoring result is a legal default match (i.e., it's either a verbatim
1555 // match or inlinable). For example, input "foo" should not invoke a
1556 // search for "bar", which would happen if the "bar" search match
1557 // outranked all other matches. On the other hand, if the omnibox will
1558 // reorder matches as necessary to put a legal default match at the top,
1559 // all we need to guarantee is that SearchProvider returns a legal
1560 // default match. (The omnibox always needs at least one legal default
1561 // match, and it relies on SearchProvider to always return one.)
1562 ApplyCalculatedRelevance();
1563 ConvertResultsToAutocompleteMatches();
1565 DCHECK(!IsTopMatchNavigationInKeywordMode(
1566 omnibox_will_reorder_for_legal_default_match
));
1567 DCHECK(HasKeywordDefaultMatchInKeywordMode());
1568 DCHECK(!IsTopMatchScoreTooLow(
1569 omnibox_will_reorder_for_legal_default_match
));
1570 DCHECK(!IsTopMatchSearchWithURLInput(
1571 omnibox_will_reorder_for_legal_default_match
));
1572 DCHECK(HasValidDefaultMatch(omnibox_will_reorder_for_legal_default_match
));
1575 const TemplateURL
* keyword_url
= providers_
.GetKeywordProviderURL();
1576 if ((keyword_url
!= NULL
) && HasKeywordDefaultMatchInKeywordMode()) {
1577 // If there is a keyword match that is allowed to be the default match,
1578 // then prohibit default provider matches from being the default match lest
1579 // such matches cause the user to break out of keyword mode.
1580 for (ACMatches::iterator it
= matches_
.begin(); it
!= matches_
.end();
1582 if (it
->keyword
!= keyword_url
->keyword())
1583 it
->allowed_to_be_default_match
= false;
1587 base::TimeTicks
update_starred_start_time(base::TimeTicks::Now());
1588 UpdateStarredStateOfMatches();
1589 UMA_HISTOGRAM_TIMES("Omnibox.SearchProvider.UpdateStarredTime",
1590 base::TimeTicks::Now() - update_starred_start_time
);
1592 UMA_HISTOGRAM_TIMES("Omnibox.SearchProvider.UpdateMatchesTime",
1593 base::TimeTicks::Now() - update_matches_start_time
);
1596 void SearchProvider::AddNavigationResultsToMatches(
1597 const NavigationResults
& navigation_results
,
1598 ACMatches
* matches
) {
1599 for (NavigationResults::const_iterator it
= navigation_results
.begin();
1600 it
!= navigation_results
.end(); ++it
) {
1601 matches
->push_back(NavigationToMatch(*it
));
1602 // In the absence of suggested relevance scores, use only the single
1603 // highest-scoring result. (The results are already sorted by relevance.)
1604 if (!it
->relevance_from_server())
1609 void SearchProvider::AddHistoryResultsToMap(const HistoryResults
& results
,
1611 int did_not_accept_suggestion
,
1613 if (results
.empty())
1616 base::TimeTicks
start_time(base::TimeTicks::Now());
1617 bool prevent_inline_autocomplete
= input_
.prevent_inline_autocomplete() ||
1618 (input_
.type() == AutocompleteInput::URL
);
1619 const base::string16
& input_text
=
1620 is_keyword
? keyword_input_
.text() : input_
.text();
1621 bool input_multiple_words
= HasMultipleWords(input_text
);
1623 SuggestResults scored_results
;
1624 if (!prevent_inline_autocomplete
&& input_multiple_words
) {
1625 // ScoreHistoryResults() allows autocompletion of multi-word, 1-visit
1626 // queries if the input also has multiple words. But if we were already
1627 // autocompleting a multi-word, multi-visit query, and the current input is
1628 // still a prefix of it, then changing the autocompletion suddenly feels
1629 // wrong. To detect this case, first score as if only one word has been
1630 // typed, then check for a best result that is an autocompleted, multi-word
1631 // query. If we find one, then just keep that score set.
1632 scored_results
= ScoreHistoryResults(results
, prevent_inline_autocomplete
,
1633 false, input_text
, is_keyword
);
1634 if ((scored_results
.front().relevance() <
1635 AutocompleteResult::kLowestDefaultScore
) ||
1636 !HasMultipleWords(scored_results
.front().suggestion()))
1637 scored_results
.clear(); // Didn't detect the case above, score normally.
1639 if (scored_results
.empty())
1640 scored_results
= ScoreHistoryResults(results
, prevent_inline_autocomplete
,
1641 input_multiple_words
, input_text
,
1643 for (SuggestResults::const_iterator
i(scored_results
.begin());
1644 i
!= scored_results
.end(); ++i
) {
1645 AddMatchToMap(*i
, input_text
, std::string(),
1646 did_not_accept_suggestion
, map
);
1648 UMA_HISTOGRAM_TIMES("Omnibox.SearchProvider.AddHistoryResultsTime",
1649 base::TimeTicks::Now() - start_time
);
1652 SearchProvider::SuggestResults
SearchProvider::ScoreHistoryResults(
1653 const HistoryResults
& results
,
1654 bool base_prevent_inline_autocomplete
,
1655 bool input_multiple_words
,
1656 const base::string16
& input_text
,
1658 AutocompleteClassifier
* classifier
=
1659 AutocompleteClassifierFactory::GetForProfile(profile_
);
1660 SuggestResults scored_results
;
1661 const bool prevent_search_history_inlining
=
1662 OmniboxFieldTrial::SearchHistoryPreventInlining(
1663 input_
.current_page_classification());
1664 for (HistoryResults::const_iterator
i(results
.begin()); i
!= results
.end();
1666 // Don't autocomplete multi-word queries that have only been seen once
1667 // unless the user has typed more than one word.
1668 bool prevent_inline_autocomplete
= base_prevent_inline_autocomplete
||
1669 (!input_multiple_words
&& (i
->visits
< 2) && HasMultipleWords(i
->term
));
1671 // Don't autocomplete search terms that would normally be treated as URLs
1672 // when typed. For example, if the user searched for "google.com" and types
1673 // "goog", don't autocomplete to the search term "google.com". Otherwise,
1674 // the input will look like a URL but act like a search, which is confusing.
1675 // NOTE: We don't check this in the following cases:
1676 // * When inline autocomplete is disabled, we won't be inline
1677 // autocompleting this term, so we don't need to worry about confusion as
1678 // much. This also prevents calling Classify() again from inside the
1679 // classifier (which will corrupt state and likely crash), since the
1680 // classifier always disables inline autocomplete.
1681 // * When the user has typed the whole term, the "what you typed" history
1682 // match will outrank us for URL-like inputs anyway, so we need not do
1683 // anything special.
1684 if (!prevent_inline_autocomplete
&& classifier
&& (i
->term
!= input_text
)) {
1685 AutocompleteMatch match
;
1686 classifier
->Classify(i
->term
, false, false, &match
, NULL
);
1687 prevent_inline_autocomplete
=
1688 !AutocompleteMatch::IsSearchType(match
.type
);
1691 int relevance
= CalculateRelevanceForHistory(
1692 i
->time
, is_keyword
, !prevent_inline_autocomplete
,
1693 prevent_search_history_inlining
);
1694 scored_results
.push_back(SuggestResult(
1695 i
->term
, AutocompleteMatchType::SEARCH_HISTORY
, i
->term
,
1696 base::string16(), std::string(), std::string(), is_keyword
, relevance
,
1697 false, false, input_text
));
1700 // History returns results sorted for us. However, we may have docked some
1701 // results' scores, so things are no longer in order. Do a stable sort to get
1702 // things back in order without otherwise disturbing results with equal
1703 // scores, then force the scores to be unique, so that the order in which
1704 // they're shown is deterministic.
1705 std::stable_sort(scored_results
.begin(), scored_results
.end(),
1706 CompareScoredResults());
1707 int last_relevance
= 0;
1708 for (SuggestResults::iterator
i(scored_results
.begin());
1709 i
!= scored_results
.end(); ++i
) {
1710 if ((i
!= scored_results
.begin()) && (i
->relevance() >= last_relevance
))
1711 i
->set_relevance(last_relevance
- 1);
1712 last_relevance
= i
->relevance();
1715 return scored_results
;
1718 void SearchProvider::AddSuggestResultsToMap(const SuggestResults
& results
,
1719 const std::string
& metadata
,
1721 for (size_t i
= 0; i
< results
.size(); ++i
) {
1722 const bool is_keyword
= results
[i
].from_keyword_provider();
1723 const base::string16
& input
= is_keyword
? keyword_input_
.text()
1725 AddMatchToMap(results
[i
], input
, metadata
, i
, map
);
1729 int SearchProvider::GetVerbatimRelevance(bool* relevance_from_server
) const {
1730 // Use the suggested verbatim relevance score if it is non-negative (valid),
1731 // if inline autocomplete isn't prevented (always show verbatim on backspace),
1732 // and if it won't suppress verbatim, leaving no default provider matches.
1733 // Otherwise, if the default provider returned no matches and was still able
1734 // to suppress verbatim, the user would have no search/nav matches and may be
1735 // left unable to search using their default provider from the omnibox.
1736 // Check for results on each verbatim calculation, as results from older
1737 // queries (on previous input) may be trimmed for failing to inline new input.
1738 bool use_server_relevance
=
1739 (default_results_
.verbatim_relevance
>= 0) &&
1740 !input_
.prevent_inline_autocomplete() &&
1741 ((default_results_
.verbatim_relevance
> 0) ||
1742 !default_results_
.suggest_results
.empty() ||
1743 !default_results_
.navigation_results
.empty());
1744 if (relevance_from_server
)
1745 *relevance_from_server
= use_server_relevance
;
1746 return use_server_relevance
?
1747 default_results_
.verbatim_relevance
: CalculateRelevanceForVerbatim();
1750 int SearchProvider::CalculateRelevanceForVerbatim() const {
1751 if (!providers_
.keyword_provider().empty())
1753 return CalculateRelevanceForVerbatimIgnoringKeywordModeState();
1756 int SearchProvider::
1757 CalculateRelevanceForVerbatimIgnoringKeywordModeState() const {
1758 switch (input_
.type()) {
1759 case AutocompleteInput::UNKNOWN
:
1760 case AutocompleteInput::QUERY
:
1761 case AutocompleteInput::FORCED_QUERY
:
1762 return kNonURLVerbatimRelevance
;
1764 case AutocompleteInput::URL
:
1773 int SearchProvider::GetKeywordVerbatimRelevance(
1774 bool* relevance_from_server
) const {
1775 // Use the suggested verbatim relevance score if it is non-negative (valid),
1776 // if inline autocomplete isn't prevented (always show verbatim on backspace),
1777 // and if it won't suppress verbatim, leaving no keyword provider matches.
1778 // Otherwise, if the keyword provider returned no matches and was still able
1779 // to suppress verbatim, the user would have no search/nav matches and may be
1780 // left unable to search using their keyword provider from the omnibox.
1781 // Check for results on each verbatim calculation, as results from older
1782 // queries (on previous input) may be trimmed for failing to inline new input.
1783 bool use_server_relevance
=
1784 (keyword_results_
.verbatim_relevance
>= 0) &&
1785 !input_
.prevent_inline_autocomplete() &&
1786 ((keyword_results_
.verbatim_relevance
> 0) ||
1787 !keyword_results_
.suggest_results
.empty() ||
1788 !keyword_results_
.navigation_results
.empty());
1789 if (relevance_from_server
)
1790 *relevance_from_server
= use_server_relevance
;
1791 return use_server_relevance
?
1792 keyword_results_
.verbatim_relevance
:
1793 CalculateRelevanceForKeywordVerbatim(keyword_input_
.type(),
1794 keyword_input_
.prefer_keyword());
1797 int SearchProvider::CalculateRelevanceForHistory(
1798 const base::Time
& time
,
1800 bool use_aggressive_method
,
1801 bool prevent_search_history_inlining
) const {
1802 // The relevance of past searches falls off over time. There are two distinct
1803 // equations used. If the first equation is used (searches to the primary
1804 // provider that we want to score aggressively), the score is in the range
1805 // 1300-1599 (unless |prevent_search_history_inlining|, in which case
1806 // it's in the range 1200-1299). If the second equation is used the
1807 // relevance of a search 15 minutes ago is discounted 50 points, while the
1808 // relevance of a search two weeks ago is discounted 450 points.
1809 double elapsed_time
= std::max((base::Time::Now() - time
).InSecondsF(), 0.0);
1810 bool is_primary_provider
= is_keyword
|| !providers_
.has_keyword_provider();
1811 if (is_primary_provider
&& use_aggressive_method
) {
1812 // Searches with the past two days get a different curve.
1813 const double autocomplete_time
= 2 * 24 * 60 * 60;
1814 if (elapsed_time
< autocomplete_time
) {
1815 int max_score
= is_keyword
? 1599 : 1399;
1816 if (prevent_search_history_inlining
)
1818 return max_score
- static_cast<int>(99 *
1819 std::pow(elapsed_time
/ autocomplete_time
, 2.5));
1821 elapsed_time
-= autocomplete_time
;
1824 const int score_discount
=
1825 static_cast<int>(6.5 * std::pow(elapsed_time
, 0.3));
1827 // Don't let scores go below 0. Negative relevance scores are meaningful in
1830 if (is_primary_provider
)
1831 base_score
= (input_
.type() == AutocompleteInput::URL
) ? 750 : 1050;
1834 return std::max(0, base_score
- score_discount
);
1837 void SearchProvider::AddMatchToMap(const SuggestResult
& result
,
1838 const base::string16
& input_text
,
1839 const std::string
& metadata
,
1840 int accepted_suggestion
,
1842 // On non-mobile, ask the instant controller for the appropriate start margin.
1843 // On mobile the start margin is unused, so leave the value as default there.
1844 int omnibox_start_margin
= chrome::kDisableStartMargin
;
1845 #if !defined(OS_ANDROID) && !defined(IOS)
1846 if (chrome::IsInstantExtendedAPIEnabled()) {
1848 chrome::FindBrowserWithProfile(profile_
, chrome::GetActiveDesktop());
1849 if (browser
&& browser
->instant_controller() &&
1850 browser
->instant_controller()->instant()) {
1851 omnibox_start_margin
=
1852 browser
->instant_controller()->instant()->omnibox_bounds().x();
1855 #endif // !defined(OS_ANDROID) && !defined(IOS)
1857 const TemplateURL
* template_url
= result
.from_keyword_provider() ?
1858 providers_
.GetKeywordProviderURL() : providers_
.GetDefaultProviderURL();
1859 AutocompleteMatch match
= CreateSearchSuggestion(
1860 this, input_
, input_text
, result
, template_url
, accepted_suggestion
,
1861 omnibox_start_margin
,
1862 !result
.from_keyword_provider() || providers_
.default_provider().empty());
1863 if (!match
.destination_url
.is_valid())
1865 match
.search_terms_args
->bookmark_bar_pinned
=
1866 profile_
->GetPrefs()->GetBoolean(prefs::kShowBookmarkBar
);
1867 match
.RecordAdditionalInfo(kRelevanceFromServerKey
,
1868 result
.relevance_from_server() ? kTrue
: kFalse
);
1869 match
.RecordAdditionalInfo(kShouldPrefetchKey
,
1870 result
.should_prefetch() ? kTrue
: kFalse
);
1872 if (!result
.deletion_url().empty()) {
1873 GURL
url(match
.destination_url
.GetOrigin().Resolve(result
.deletion_url()));
1874 if (url
.is_valid()) {
1875 match
.RecordAdditionalInfo(kDeletionUrlKey
, url
.spec());
1876 match
.deletable
= true;
1880 // Metadata is needed only for prefetching queries.
1881 if (result
.should_prefetch())
1882 match
.RecordAdditionalInfo(kSuggestMetadataKey
, metadata
);
1884 // Try to add |match| to |map|. If a match for |query_string| is already in
1885 // |map|, replace it if |match| is more relevant.
1886 // NOTE: Keep this ToLower() call in sync with url_database.cc.
1888 std::make_pair(base::i18n::ToLower(result
.suggestion()),
1889 match
.search_terms_args
->suggest_query_params
));
1890 const std::pair
<MatchMap::iterator
, bool> i(
1891 map
->insert(std::make_pair(match_key
, match
)));
1893 bool should_prefetch
= result
.should_prefetch();
1895 // NOTE: We purposefully do a direct relevance comparison here instead of
1896 // using AutocompleteMatch::MoreRelevant(), so that we'll prefer "items
1897 // added first" rather than "items alphabetically first" when the scores are
1898 // equal. The only case this matters is when a user has results with the
1899 // same score that differ only by capitalization; because the history system
1900 // returns results sorted by recency, this means we'll pick the most
1901 // recent such result even if the precision of our relevance score is too
1902 // low to distinguish the two.
1903 if (match
.relevance
> i
.first
->second
.relevance
) {
1904 i
.first
->second
= match
;
1905 } else if (match
.keyword
== i
.first
->second
.keyword
) {
1906 // Old and new matches are from the same search provider. It is okay to
1907 // record one match's prefetch data onto a different match (for the same
1908 // query string) for the following reasons:
1909 // 1. Because the suggest server only sends down a query string from which
1910 // we construct a URL, rather than sending a full URL, and because we
1911 // construct URLs from query strings in the same way every time, the URLs
1912 // for the two matches will be the same. Therefore, we won't end up
1913 // prefetching something the server didn't intend.
1914 // 2. Presumably the server sets the prefetch bit on a match it things is
1915 // sufficiently relevant that the user is likely to choose it. Surely
1916 // setting the prefetch bit on a match of even higher relevance won't
1917 // violate this assumption.
1918 should_prefetch
|= ShouldPrefetch(i
.first
->second
);
1919 i
.first
->second
.RecordAdditionalInfo(kShouldPrefetchKey
,
1920 should_prefetch
? kTrue
: kFalse
);
1921 if (should_prefetch
)
1922 i
.first
->second
.RecordAdditionalInfo(kSuggestMetadataKey
, metadata
);
1927 AutocompleteMatch
SearchProvider::NavigationToMatch(
1928 const NavigationResult
& navigation
) {
1929 const base::string16
& input
= navigation
.from_keyword_provider() ?
1930 keyword_input_
.text() : input_
.text();
1931 AutocompleteMatch
match(this, navigation
.relevance(), false,
1932 AutocompleteMatchType::NAVSUGGEST
);
1933 match
.destination_url
= navigation
.url();
1935 // First look for the user's input inside the formatted url as it would be
1936 // without trimming the scheme, so we can find matches at the beginning of the
1938 const URLPrefix
* prefix
=
1939 URLPrefix::BestURLPrefix(navigation
.formatted_url(), input
);
1940 size_t match_start
= (prefix
== NULL
) ?
1941 navigation
.formatted_url().find(input
) : prefix
->prefix
.length();
1942 bool trim_http
= !AutocompleteInput::HasHTTPScheme(input
) &&
1943 (!prefix
|| (match_start
!= 0));
1944 const net::FormatUrlTypes format_types
=
1945 net::kFormatUrlOmitAll
& ~(trim_http
? 0 : net::kFormatUrlOmitHTTP
);
1947 const std::string
languages(
1948 profile_
->GetPrefs()->GetString(prefs::kAcceptLanguages
));
1949 size_t inline_autocomplete_offset
= (prefix
== NULL
) ?
1950 base::string16::npos
: (match_start
+ input
.length());
1951 match
.fill_into_edit
+=
1952 AutocompleteInput::FormattedStringWithEquivalentMeaning(navigation
.url(),
1953 net::FormatUrl(navigation
.url(), languages
, format_types
,
1954 net::UnescapeRule::SPACES
, NULL
, NULL
,
1955 &inline_autocomplete_offset
));
1956 // Preserve the forced query '?' prefix in |match.fill_into_edit|.
1957 // Otherwise, user edits to a suggestion would show non-Search results.
1958 if (input_
.type() == AutocompleteInput::FORCED_QUERY
) {
1959 match
.fill_into_edit
.insert(0, base::ASCIIToUTF16("?"));
1960 if (inline_autocomplete_offset
!= base::string16::npos
)
1961 ++inline_autocomplete_offset
;
1963 if (!input_
.prevent_inline_autocomplete() &&
1964 (inline_autocomplete_offset
!= base::string16::npos
)) {
1965 DCHECK(inline_autocomplete_offset
<= match
.fill_into_edit
.length());
1966 // A navsuggestion can only be the default match when there is no
1967 // keyword provider active, lest it appear first and break the user
1968 // out of keyword mode.
1969 match
.allowed_to_be_default_match
=
1970 (providers_
.GetKeywordProviderURL() == NULL
);
1971 match
.inline_autocompletion
=
1972 match
.fill_into_edit
.substr(inline_autocomplete_offset
);
1975 match
.contents
= navigation
.match_contents();
1976 match
.contents_class
= navigation
.match_contents_class();
1977 match
.description
= navigation
.description();
1978 AutocompleteMatch::ClassifyMatchInString(input
, match
.description
,
1979 ACMatchClassification::NONE
, &match
.description_class
);
1981 match
.RecordAdditionalInfo(
1982 kRelevanceFromServerKey
,
1983 navigation
.relevance_from_server() ? kTrue
: kFalse
);
1984 match
.RecordAdditionalInfo(kShouldPrefetchKey
, kFalse
);
1989 void SearchProvider::DemoteKeywordNavigationMatchesPastTopQuery() {
1990 // First, determine the maximum score of any keyword query match (verbatim or
1991 // query suggestion).
1992 bool relevance_from_server
;
1993 int max_query_relevance
= GetKeywordVerbatimRelevance(&relevance_from_server
);
1994 if (!keyword_results_
.suggest_results
.empty()) {
1995 const SuggestResult
& top_keyword
= keyword_results_
.suggest_results
.front();
1996 const int suggest_relevance
= top_keyword
.relevance();
1997 if (suggest_relevance
> max_query_relevance
) {
1998 max_query_relevance
= suggest_relevance
;
1999 relevance_from_server
= top_keyword
.relevance_from_server();
2000 } else if (suggest_relevance
== max_query_relevance
) {
2001 relevance_from_server
|= top_keyword
.relevance_from_server();
2004 // If no query is supposed to appear, then navigational matches cannot
2005 // be demoted past it. Get rid of suggested relevance scores for
2006 // navsuggestions and introduce the verbatim results again. The keyword
2007 // verbatim match will outscore the navsuggest matches.
2008 if (max_query_relevance
== 0) {
2009 ApplyCalculatedNavigationRelevance(&keyword_results_
.navigation_results
);
2010 ApplyCalculatedNavigationRelevance(&default_results_
.navigation_results
);
2011 keyword_results_
.verbatim_relevance
= -1;
2012 default_results_
.verbatim_relevance
= -1;
2015 // Now we know we can enforce the minimum score constraint even after
2016 // the navigation matches are demoted. Proceed to demote the navigation
2017 // matches to enforce the query-must-come-first constraint.
2018 // Cap the relevance score of all results.
2019 for (NavigationResults::iterator it
=
2020 keyword_results_
.navigation_results
.begin();
2021 it
!= keyword_results_
.navigation_results
.end(); ++it
) {
2022 if (it
->relevance() < max_query_relevance
)
2024 max_query_relevance
= std::max(max_query_relevance
- 1, 0);
2025 it
->set_relevance(max_query_relevance
);
2026 it
->set_relevance_from_server(relevance_from_server
);
2030 void SearchProvider::UpdateDone() {
2031 // We're done when the timer isn't running, there are no suggest queries
2032 // pending, and we're not waiting on Instant.
2033 done_
= !timer_
.IsRunning() && (suggest_results_pending_
== 0);
2036 bool SearchProvider::CanSendURL(
2037 const GURL
& current_page_url
,
2038 const GURL
& suggest_url
,
2039 const TemplateURL
* template_url
,
2040 AutocompleteInput::PageClassification page_classification
,
2042 if (!current_page_url
.is_valid())
2045 // TODO(hfung): Show Most Visited on NTP with appropriate verbatim
2046 // description when the user actively focuses on the omnibox as discussed in
2047 // crbug/305366 if Most Visited (or something similar) will launch.
2048 if ((page_classification
==
2049 AutocompleteInput::INSTANT_NTP_WITH_FAKEBOX_AS_STARTING_FOCUS
) ||
2050 (page_classification
==
2051 AutocompleteInput::INSTANT_NTP_WITH_OMNIBOX_AS_STARTING_FOCUS
))
2054 // Only allow HTTP URLs or HTTPS URLs for the same domain as the search
2056 if ((current_page_url
.scheme() != content::kHttpScheme
) &&
2057 ((current_page_url
.scheme() != content::kHttpsScheme
) ||
2058 !net::registry_controlled_domains::SameDomainOrHost(
2059 current_page_url
, suggest_url
,
2060 net::registry_controlled_domains::EXCLUDE_PRIVATE_REGISTRIES
)))
2063 // Make sure we are sending the suggest request through HTTPS to prevent
2064 // exposing the current page URL to networks before the search provider.
2065 if (!suggest_url
.SchemeIs(content::kHttpsScheme
))
2068 // Don't run if there's no profile or in incognito mode.
2069 if (profile
== NULL
|| profile
->IsOffTheRecord())
2072 // Don't run if we can't get preferences or search suggest is not enabled.
2073 PrefService
* prefs
= profile
->GetPrefs();
2074 if (!prefs
->GetBoolean(prefs::kSearchSuggestEnabled
))
2077 // Only make the request if we know that the provider supports zero suggest
2078 // (currently only the prepopulated Google provider).
2079 if (template_url
== NULL
|| !template_url
->SupportsReplacement() ||
2080 TemplateURLPrepopulateData::GetEngineType(*template_url
) !=
2081 SEARCH_ENGINE_GOOGLE
)
2084 // Check field trials and settings allow sending the URL on suggest requests.
2085 ProfileSyncService
* service
=
2086 ProfileSyncServiceFactory::GetInstance()->GetForProfile(profile
);
2087 browser_sync::SyncPrefs
sync_prefs(prefs
);
2088 if (!OmniboxFieldTrial::InZeroSuggestFieldTrial() ||
2090 !service
->IsSyncEnabledAndLoggedIn() ||
2091 !sync_prefs
.GetPreferredDataTypes(syncer::UserTypes()).Has(
2092 syncer::PROXY_TABS
) ||
2093 service
->GetEncryptedDataTypes().Has(syncer::SESSIONS
))