Add an exponential backoff to rechecking the app list doodle.
[chromium-blink-merge.git] / components / omnibox / search_provider.cc
blobd0abdd7e0376119ed48aa6427a95e65b20c761aa
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 "components/omnibox/search_provider.h"
7 #include <algorithm>
8 #include <cmath>
10 #include "base/base64.h"
11 #include "base/bind.h"
12 #include "base/callback.h"
13 #include "base/i18n/break_iterator.h"
14 #include "base/i18n/case_conversion.h"
15 #include "base/json/json_string_value_serializer.h"
16 #include "base/metrics/histogram.h"
17 #include "base/metrics/user_metrics.h"
18 #include "base/rand_util.h"
19 #include "base/strings/string_util.h"
20 #include "base/strings/utf_string_conversions.h"
21 #include "components/history/core/browser/in_memory_database.h"
22 #include "components/history/core/browser/keyword_search_term.h"
23 #include "components/metrics/proto/omnibox_input_type.pb.h"
24 #include "components/omnibox/autocomplete_provider_client.h"
25 #include "components/omnibox/autocomplete_provider_listener.h"
26 #include "components/omnibox/autocomplete_result.h"
27 #include "components/omnibox/keyword_provider.h"
28 #include "components/omnibox/omnibox_field_trial.h"
29 #include "components/omnibox/suggestion_answer.h"
30 #include "components/omnibox/url_prefix.h"
31 #include "components/search/search.h"
32 #include "components/search_engines/template_url_prepopulate_data.h"
33 #include "components/search_engines/template_url_service.h"
34 #include "components/variations/net/variations_http_header_provider.h"
35 #include "grit/components_strings.h"
36 #include "net/base/escape.h"
37 #include "net/base/load_flags.h"
38 #include "net/base/net_util.h"
39 #include "net/http/http_request_headers.h"
40 #include "net/url_request/url_fetcher.h"
41 #include "net/url_request/url_request_status.h"
42 #include "ui/base/l10n/l10n_util.h"
43 #include "url/url_constants.h"
44 #include "url/url_util.h"
46 // Helpers --------------------------------------------------------------------
48 namespace {
50 // We keep track in a histogram how many suggest requests we send, how
51 // many suggest requests we invalidate (e.g., due to a user typing
52 // another character), and how many replies we receive.
53 // *** ADD NEW ENUMS AFTER ALL PREVIOUSLY DEFINED ONES! ***
54 // (excluding the end-of-list enum value)
55 // We do not want values of existing enums to change or else it screws
56 // up the statistics.
57 enum SuggestRequestsHistogramValue {
58 REQUEST_SENT = 1,
59 REQUEST_INVALIDATED,
60 REPLY_RECEIVED,
61 MAX_SUGGEST_REQUEST_HISTOGRAM_VALUE
64 // The verbatim score for an input which is not an URL.
65 const int kNonURLVerbatimRelevance = 1300;
67 // Increments the appropriate value in the histogram by one.
68 void LogOmniboxSuggestRequest(
69 SuggestRequestsHistogramValue request_value) {
70 UMA_HISTOGRAM_ENUMERATION("Omnibox.SuggestRequests", request_value,
71 MAX_SUGGEST_REQUEST_HISTOGRAM_VALUE);
74 bool HasMultipleWords(const base::string16& text) {
75 base::i18n::BreakIterator i(text, base::i18n::BreakIterator::BREAK_WORD);
76 bool found_word = false;
77 if (i.Init()) {
78 while (i.Advance()) {
79 if (i.IsWord()) {
80 if (found_word)
81 return true;
82 found_word = true;
86 return false;
89 } // namespace
91 // SearchProvider::Providers --------------------------------------------------
93 SearchProvider::Providers::Providers(TemplateURLService* template_url_service)
94 : template_url_service_(template_url_service) {}
96 const TemplateURL* SearchProvider::Providers::GetDefaultProviderURL() const {
97 return default_provider_.empty() ? NULL :
98 template_url_service_->GetTemplateURLForKeyword(default_provider_);
101 const TemplateURL* SearchProvider::Providers::GetKeywordProviderURL() const {
102 return keyword_provider_.empty() ? NULL :
103 template_url_service_->GetTemplateURLForKeyword(keyword_provider_);
107 // SearchProvider::CompareScoredResults ---------------------------------------
109 class SearchProvider::CompareScoredResults {
110 public:
111 bool operator()(const SearchSuggestionParser::Result& a,
112 const SearchSuggestionParser::Result& b) {
113 // Sort in descending relevance order.
114 return a.relevance() > b.relevance();
119 // SearchProvider -------------------------------------------------------------
121 SearchProvider::SearchProvider(
122 AutocompleteProviderListener* listener,
123 TemplateURLService* template_url_service,
124 scoped_ptr<AutocompleteProviderClient> client)
125 : BaseSearchProvider(template_url_service, client.Pass(),
126 AutocompleteProvider::TYPE_SEARCH),
127 listener_(listener),
128 providers_(template_url_service),
129 answers_cache_(10) {
130 // |template_url_service_| can be null in tests.
131 if (template_url_service_)
132 template_url_service_->AddObserver(this);
135 // static
136 std::string SearchProvider::GetSuggestMetadata(const AutocompleteMatch& match) {
137 return match.GetAdditionalInfo(kSuggestMetadataKey);
140 void SearchProvider::ResetSession() {
141 field_trial_triggered_in_session_ = false;
144 void SearchProvider::OnTemplateURLServiceChanged() {
145 // Only update matches at this time if we haven't already claimed we're done
146 // processing the query.
147 if (done_)
148 return;
150 // Check that the engines we're using weren't renamed or deleted. (In short,
151 // require that an engine still exists with the keywords in use.) For each
152 // deleted engine, cancel the in-flight request if any, drop its suggestions,
153 // and, in the case when the default provider was affected, point the cached
154 // default provider keyword name at the new name for the default provider.
156 // Get...ProviderURL() looks up the provider using the cached keyword name
157 // stored in |providers_|.
158 const TemplateURL* template_url = providers_.GetDefaultProviderURL();
159 if (!template_url) {
160 CancelFetcher(&default_fetcher_);
161 default_results_.Clear();
162 providers_.set(template_url_service_->GetDefaultSearchProvider()->keyword(),
163 providers_.keyword_provider());
165 template_url = providers_.GetKeywordProviderURL();
166 if (!providers_.keyword_provider().empty() && !template_url) {
167 CancelFetcher(&keyword_fetcher_);
168 keyword_results_.Clear();
169 providers_.set(providers_.default_provider(), base::string16());
171 // It's possible the template URL changed without changing associated keyword.
172 // Hence, it's always necessary to update matches to use the new template
173 // URL. (One could cache the template URL and only call UpdateMatches() and
174 // OnProviderUpdate() if a keyword was deleted/renamed or the template URL
175 // was changed. That would save extra calls to these functions. However,
176 // this is uncommon and not likely to be worth the extra work.)
177 UpdateMatches();
178 listener_->OnProviderUpdate(true); // always pretend something changed
181 SearchProvider::~SearchProvider() {
182 if (template_url_service_)
183 template_url_service_->RemoveObserver(this);
186 // static
187 int SearchProvider::CalculateRelevanceForKeywordVerbatim(
188 metrics::OmniboxInputType::Type type,
189 bool prefer_keyword) {
190 // This function is responsible for scoring verbatim query matches
191 // for non-extension keywords. KeywordProvider::CalculateRelevance()
192 // scores verbatim query matches for extension keywords, as well as
193 // for keyword matches (i.e., suggestions of a keyword itself, not a
194 // suggestion of a query on a keyword search engine). These two
195 // functions are currently in sync, but there's no reason we
196 // couldn't decide in the future to score verbatim matches
197 // differently for extension and non-extension keywords. If you
198 // make such a change, however, you should update this comment to
199 // describe it, so it's clear why the functions diverge.
200 if (prefer_keyword)
201 return 1500;
202 return (type == metrics::OmniboxInputType::QUERY) ? 1450 : 1100;
205 // static
206 void SearchProvider::UpdateOldResults(
207 bool minimal_changes,
208 SearchSuggestionParser::Results* results) {
209 // When called without |minimal_changes|, it likely means the user has
210 // pressed a key. Revise the cached results appropriately.
211 if (!minimal_changes) {
212 for (SearchSuggestionParser::SuggestResults::iterator sug_it =
213 results->suggest_results.begin();
214 sug_it != results->suggest_results.end(); ++sug_it) {
215 sug_it->set_received_after_last_keystroke(false);
217 for (SearchSuggestionParser::NavigationResults::iterator nav_it =
218 results->navigation_results.begin();
219 nav_it != results->navigation_results.end(); ++nav_it) {
220 nav_it->set_received_after_last_keystroke(false);
225 // static
226 ACMatches::iterator SearchProvider::FindTopMatch(ACMatches* matches) {
227 ACMatches::iterator it = matches->begin();
228 while ((it != matches->end()) && !it->allowed_to_be_default_match)
229 ++it;
230 return it;
233 void SearchProvider::Start(const AutocompleteInput& input,
234 bool minimal_changes,
235 bool called_due_to_focus) {
236 // Do our best to load the model as early as possible. This will reduce
237 // odds of having the model not ready when really needed (a non-empty input).
238 TemplateURLService* model = providers_.template_url_service();
239 DCHECK(model);
240 model->Load();
242 matches_.clear();
243 field_trial_triggered_ = false;
245 // Can't return search/suggest results for bogus input.
246 if (called_due_to_focus ||
247 input.type() == metrics::OmniboxInputType::INVALID) {
248 Stop(true, false);
249 return;
252 keyword_input_ = input;
253 const TemplateURL* keyword_provider =
254 KeywordProvider::GetSubstitutingTemplateURLForInput(model,
255 &keyword_input_);
256 if (keyword_provider == NULL)
257 keyword_input_.Clear();
258 else if (keyword_input_.text().empty())
259 keyword_provider = NULL;
261 const TemplateURL* default_provider = model->GetDefaultSearchProvider();
262 if (default_provider &&
263 !default_provider->SupportsReplacement(model->search_terms_data()))
264 default_provider = NULL;
266 if (keyword_provider == default_provider)
267 default_provider = NULL; // No use in querying the same provider twice.
269 if (!default_provider && !keyword_provider) {
270 // No valid providers.
271 Stop(true, false);
272 return;
275 // If we're still running an old query but have since changed the query text
276 // or the providers, abort the query.
277 base::string16 default_provider_keyword(default_provider ?
278 default_provider->keyword() : base::string16());
279 base::string16 keyword_provider_keyword(keyword_provider ?
280 keyword_provider->keyword() : base::string16());
281 if (!minimal_changes ||
282 !providers_.equal(default_provider_keyword, keyword_provider_keyword)) {
283 // Cancel any in-flight suggest requests.
284 if (!done_)
285 Stop(false, false);
288 providers_.set(default_provider_keyword, keyword_provider_keyword);
290 if (input.text().empty()) {
291 // User typed "?" alone. Give them a placeholder result indicating what
292 // this syntax does.
293 if (default_provider) {
294 AutocompleteMatch match;
295 match.provider = this;
296 match.contents.assign(l10n_util::GetStringUTF16(IDS_EMPTY_KEYWORD_VALUE));
297 match.contents_class.push_back(
298 ACMatchClassification(0, ACMatchClassification::NONE));
299 match.keyword = providers_.default_provider();
300 match.allowed_to_be_default_match = true;
301 matches_.push_back(match);
303 Stop(true, false);
304 return;
307 input_ = input;
309 DoHistoryQuery(minimal_changes);
310 // Answers needs scored history results before any suggest query has been
311 // started, since the query for answer-bearing results needs additional
312 // prefetch information based on the highest-scored local history result.
313 if (OmniboxFieldTrial::EnableAnswersInSuggest()) {
314 ScoreHistoryResults(raw_default_history_results_,
315 false,
316 &transformed_default_history_results_);
317 ScoreHistoryResults(raw_keyword_history_results_,
318 true,
319 &transformed_keyword_history_results_);
320 prefetch_data_ = FindAnswersPrefetchData();
322 // Raw results are not needed any more.
323 raw_default_history_results_.clear();
324 raw_keyword_history_results_.clear();
327 StartOrStopSuggestQuery(minimal_changes);
328 UpdateMatches();
331 void SearchProvider::Stop(bool clear_cached_results,
332 bool due_to_user_inactivity) {
333 StopSuggest();
334 done_ = true;
336 if (clear_cached_results)
337 ClearAllResults();
340 const TemplateURL* SearchProvider::GetTemplateURL(bool is_keyword) const {
341 return is_keyword ? providers_.GetKeywordProviderURL()
342 : providers_.GetDefaultProviderURL();
345 const AutocompleteInput SearchProvider::GetInput(bool is_keyword) const {
346 return is_keyword ? keyword_input_ : input_;
349 bool SearchProvider::ShouldAppendExtraParams(
350 const SearchSuggestionParser::SuggestResult& result) const {
351 return !result.from_keyword_provider() ||
352 providers_.default_provider().empty();
355 void SearchProvider::RecordDeletionResult(bool success) {
356 if (success) {
357 base::RecordAction(
358 base::UserMetricsAction("Omnibox.ServerSuggestDelete.Success"));
359 } else {
360 base::RecordAction(
361 base::UserMetricsAction("Omnibox.ServerSuggestDelete.Failure"));
365 void SearchProvider::OnURLFetchComplete(const net::URLFetcher* source) {
366 DCHECK(!done_);
367 const bool is_keyword = source == keyword_fetcher_.get();
369 // Ensure the request succeeded and that the provider used is still available.
370 // A verbatim match cannot be generated without this provider, causing errors.
371 const bool request_succeeded =
372 source->GetStatus().is_success() && (source->GetResponseCode() == 200) &&
373 GetTemplateURL(is_keyword);
375 LogFetchComplete(request_succeeded, is_keyword);
377 bool results_updated = false;
378 if (request_succeeded) {
379 scoped_ptr<base::Value> data(SearchSuggestionParser::DeserializeJsonData(
380 SearchSuggestionParser::ExtractJsonData(source)));
381 if (data) {
382 SearchSuggestionParser::Results* results =
383 is_keyword ? &keyword_results_ : &default_results_;
384 results_updated = ParseSuggestResults(*data, -1, is_keyword, results);
385 if (results_updated)
386 SortResults(is_keyword, results);
390 // Delete the fetcher now that we're done with it.
391 if (is_keyword)
392 keyword_fetcher_.reset();
393 else
394 default_fetcher_.reset();
396 // Update matches, done status, etc., and send alerts if necessary.
397 UpdateMatches();
398 if (done_ || results_updated)
399 listener_->OnProviderUpdate(results_updated);
402 void SearchProvider::StopSuggest() {
403 CancelFetcher(&default_fetcher_);
404 CancelFetcher(&keyword_fetcher_);
405 timer_.Stop();
408 void SearchProvider::ClearAllResults() {
409 keyword_results_.Clear();
410 default_results_.Clear();
413 void SearchProvider::UpdateMatchContentsClass(
414 const base::string16& input_text,
415 SearchSuggestionParser::Results* results) {
416 for (SearchSuggestionParser::SuggestResults::iterator sug_it =
417 results->suggest_results.begin();
418 sug_it != results->suggest_results.end(); ++sug_it) {
419 sug_it->ClassifyMatchContents(false, input_text);
421 const std::string languages(client_->AcceptLanguages());
422 for (SearchSuggestionParser::NavigationResults::iterator nav_it =
423 results->navigation_results.begin();
424 nav_it != results->navigation_results.end(); ++nav_it) {
425 nav_it->CalculateAndClassifyMatchContents(false, input_text, languages);
429 void SearchProvider::SortResults(bool is_keyword,
430 SearchSuggestionParser::Results* results) {
431 // Ignore suggested scores for non-keyword matches in keyword mode; if the
432 // server is allowed to score these, it could interfere with the user's
433 // ability to get good keyword results.
434 const bool abandon_suggested_scores =
435 !is_keyword && !providers_.keyword_provider().empty();
436 // Apply calculated relevance scores to suggestions if valid relevances were
437 // not provided or we're abandoning suggested scores entirely.
438 if (!results->relevances_from_server || abandon_suggested_scores) {
439 ApplyCalculatedSuggestRelevance(&results->suggest_results);
440 ApplyCalculatedNavigationRelevance(&results->navigation_results);
441 // If abandoning scores entirely, also abandon the verbatim score.
442 if (abandon_suggested_scores)
443 results->verbatim_relevance = -1;
446 // Keep the result lists sorted.
447 const CompareScoredResults comparator = CompareScoredResults();
448 std::stable_sort(results->suggest_results.begin(),
449 results->suggest_results.end(),
450 comparator);
451 std::stable_sort(results->navigation_results.begin(),
452 results->navigation_results.end(),
453 comparator);
456 void SearchProvider::LogFetchComplete(bool success, bool is_keyword) {
457 LogOmniboxSuggestRequest(REPLY_RECEIVED);
458 // Record response time for suggest requests sent to Google. We care
459 // only about the common case: the Google default provider used in
460 // non-keyword mode.
461 const TemplateURL* default_url = providers_.GetDefaultProviderURL();
462 if (!is_keyword && default_url &&
463 (TemplateURLPrepopulateData::GetEngineType(
464 *default_url,
465 providers_.template_url_service()->search_terms_data()) ==
466 SEARCH_ENGINE_GOOGLE)) {
467 const base::TimeDelta elapsed_time =
468 base::TimeTicks::Now() - time_suggest_request_sent_;
469 if (success) {
470 UMA_HISTOGRAM_TIMES("Omnibox.SuggestRequest.Success.GoogleResponseTime",
471 elapsed_time);
472 } else {
473 UMA_HISTOGRAM_TIMES("Omnibox.SuggestRequest.Failure.GoogleResponseTime",
474 elapsed_time);
479 void SearchProvider::UpdateMatches() {
480 PersistTopSuggestions(&default_results_);
481 PersistTopSuggestions(&keyword_results_);
482 ConvertResultsToAutocompleteMatches();
484 // Check constraints that may be violated by suggested relevances.
485 if (!matches_.empty() &&
486 (default_results_.HasServerProvidedScores() ||
487 keyword_results_.HasServerProvidedScores())) {
488 // These blocks attempt to repair undesirable behavior by suggested
489 // relevances with minimal impact, preserving other suggested relevances.
490 const TemplateURL* keyword_url = providers_.GetKeywordProviderURL();
491 const bool is_extension_keyword = (keyword_url != NULL) &&
492 (keyword_url->GetType() == TemplateURL::OMNIBOX_API_EXTENSION);
493 if ((keyword_url != NULL) && !is_extension_keyword &&
494 (FindTopMatch() == matches_.end())) {
495 // In non-extension keyword mode, disregard the keyword verbatim suggested
496 // relevance if necessary, so at least one match is allowed to be default.
497 // (In extension keyword mode this is not necessary because the extension
498 // will return a default match.) Give keyword verbatim the lowest
499 // non-zero score to best reflect what the server desired.
500 DCHECK_EQ(0, keyword_results_.verbatim_relevance);
501 keyword_results_.verbatim_relevance = 1;
502 ConvertResultsToAutocompleteMatches();
504 if (IsTopMatchSearchWithURLInput()) {
505 // Disregard the suggested search and verbatim relevances if the input
506 // type is URL and the top match is a highly-ranked search suggestion.
507 // For example, prevent a search for "foo.com" from outranking another
508 // provider's navigation for "foo.com" or "foo.com/url_from_history".
509 ApplyCalculatedSuggestRelevance(&keyword_results_.suggest_results);
510 ApplyCalculatedSuggestRelevance(&default_results_.suggest_results);
511 default_results_.verbatim_relevance = -1;
512 keyword_results_.verbatim_relevance = -1;
513 ConvertResultsToAutocompleteMatches();
515 if (!is_extension_keyword && (FindTopMatch() == matches_.end())) {
516 // Guarantee that SearchProvider returns a legal default match (except
517 // when in extension-based keyword mode). The omnibox always needs at
518 // least one legal default match, and it relies on SearchProvider in
519 // combination with KeywordProvider (for extension-based keywords) to
520 // always return one. Give the verbatim suggestion the lowest non-zero
521 // scores to best reflect what the server desired.
522 DCHECK_EQ(0, default_results_.verbatim_relevance);
523 default_results_.verbatim_relevance = 1;
524 // We do not have to alter keyword_results_.verbatim_relevance here.
525 // If the user is in keyword mode, we already reverted (earlier in this
526 // function) the instructions to suppress keyword verbatim.
527 ConvertResultsToAutocompleteMatches();
529 DCHECK(!IsTopMatchSearchWithURLInput());
530 DCHECK(is_extension_keyword || (FindTopMatch() != matches_.end()));
532 UMA_HISTOGRAM_CUSTOM_COUNTS(
533 "Omnibox.SearchProviderMatches", matches_.size(), 1, 6, 7);
535 // Record the top suggestion (if any) for future use.
536 top_query_suggestion_match_contents_ = base::string16();
537 top_navigation_suggestion_ = GURL();
538 ACMatches::const_iterator first_match = FindTopMatch();
539 if ((first_match != matches_.end()) &&
540 !first_match->inline_autocompletion.empty()) {
541 // Identify if this match came from a query suggestion or a navsuggestion.
542 // In either case, extracts the identifying feature of the suggestion
543 // (query string or navigation url).
544 if (AutocompleteMatch::IsSearchType(first_match->type))
545 top_query_suggestion_match_contents_ = first_match->contents;
546 else
547 top_navigation_suggestion_ = first_match->destination_url;
550 UpdateDone();
553 void SearchProvider::Run(bool query_is_private) {
554 // Start a new request with the current input.
555 time_suggest_request_sent_ = base::TimeTicks::Now();
557 if (!query_is_private) {
558 default_fetcher_.reset(CreateSuggestFetcher(
559 kDefaultProviderURLFetcherID,
560 providers_.GetDefaultProviderURL(),
561 input_));
563 keyword_fetcher_.reset(CreateSuggestFetcher(
564 kKeywordProviderURLFetcherID,
565 providers_.GetKeywordProviderURL(),
566 keyword_input_));
568 // Both the above can fail if the providers have been modified or deleted
569 // since the query began.
570 if (!default_fetcher_ && !keyword_fetcher_) {
571 UpdateDone();
572 // We only need to update the listener if we're actually done.
573 if (done_)
574 listener_->OnProviderUpdate(false);
575 } else {
576 // Sent at least one request.
577 time_suggest_request_sent_ = base::TimeTicks::Now();
581 void SearchProvider::DoHistoryQuery(bool minimal_changes) {
582 // The history query results are synchronous, so if minimal_changes is true,
583 // we still have the last results and don't need to do anything.
584 if (minimal_changes)
585 return;
587 raw_keyword_history_results_.clear();
588 raw_default_history_results_.clear();
590 if (OmniboxFieldTrial::SearchHistoryDisable(
591 input_.current_page_classification()))
592 return;
594 history::URLDatabase* url_db = client_->InMemoryDatabase();
595 if (!url_db)
596 return;
598 // Request history for both the keyword and default provider. We grab many
599 // more matches than we'll ultimately clamp to so that if there are several
600 // recent multi-word matches who scores are lowered (see
601 // ScoreHistoryResults()), they won't crowd out older, higher-scoring
602 // matches. Note that this doesn't fix the problem entirely, but merely
603 // limits it to cases with a very large number of such multi-word matches; for
604 // now, this seems OK compared with the complexity of a real fix, which would
605 // require multiple searches and tracking of "single- vs. multi-word" in the
606 // database.
607 int num_matches = kMaxMatches * 5;
608 const TemplateURL* default_url = providers_.GetDefaultProviderURL();
609 if (default_url) {
610 const base::TimeTicks start_time = base::TimeTicks::Now();
611 url_db->GetMostRecentKeywordSearchTerms(default_url->id(),
612 input_.text(),
613 num_matches,
614 &raw_default_history_results_);
615 UMA_HISTOGRAM_TIMES(
616 "Omnibox.SearchProvider.GetMostRecentKeywordTermsDefaultProviderTime",
617 base::TimeTicks::Now() - start_time);
619 const TemplateURL* keyword_url = providers_.GetKeywordProviderURL();
620 if (keyword_url) {
621 url_db->GetMostRecentKeywordSearchTerms(keyword_url->id(),
622 keyword_input_.text(),
623 num_matches,
624 &raw_keyword_history_results_);
628 base::TimeDelta SearchProvider::GetSuggestQueryDelay() const {
629 bool from_last_keystroke;
630 int polling_delay_ms;
631 OmniboxFieldTrial::GetSuggestPollingStrategy(&from_last_keystroke,
632 &polling_delay_ms);
634 base::TimeDelta delay(base::TimeDelta::FromMilliseconds(polling_delay_ms));
635 if (from_last_keystroke)
636 return delay;
638 base::TimeDelta time_since_last_suggest_request =
639 base::TimeTicks::Now() - time_suggest_request_sent_;
640 return std::max(base::TimeDelta(), delay - time_since_last_suggest_request);
643 void SearchProvider::StartOrStopSuggestQuery(bool minimal_changes) {
644 bool query_is_private;
645 if (!IsQuerySuitableForSuggest(&query_is_private)) {
646 StopSuggest();
647 ClearAllResults();
648 return;
651 if (OmniboxFieldTrial::DisableResultsCaching())
652 ClearAllResults();
654 // For the minimal_changes case, if we finished the previous query and still
655 // have its results, or are allowed to keep running it, just do that, rather
656 // than starting a new query.
657 if (minimal_changes &&
658 (!default_results_.suggest_results.empty() ||
659 !default_results_.navigation_results.empty() ||
660 !keyword_results_.suggest_results.empty() ||
661 !keyword_results_.navigation_results.empty() ||
662 (!done_ && input_.want_asynchronous_matches())))
663 return;
665 // We can't keep running any previous query, so halt it.
666 StopSuggest();
668 UpdateAllOldResults(minimal_changes);
670 // Update the content classifications of remaining results so they look good
671 // against the current input.
672 UpdateMatchContentsClass(input_.text(), &default_results_);
673 if (!keyword_input_.text().empty())
674 UpdateMatchContentsClass(keyword_input_.text(), &keyword_results_);
676 // We can't start a new query if we're only allowed synchronous results.
677 if (!input_.want_asynchronous_matches())
678 return;
680 // Kick off a timer that will start the URL fetch if it completes before
681 // the user types another character. Requests may be delayed to avoid
682 // flooding the server with requests that are likely to be thrown away later
683 // anyway.
684 const base::TimeDelta delay = GetSuggestQueryDelay();
685 if (delay <= base::TimeDelta()) {
686 Run(query_is_private);
687 return;
689 timer_.Start(FROM_HERE,
690 delay,
691 base::Bind(&SearchProvider::Run,
692 base::Unretained(this),
693 query_is_private));
696 void SearchProvider::CancelFetcher(scoped_ptr<net::URLFetcher>* fetcher) {
697 if (*fetcher) {
698 LogOmniboxSuggestRequest(REQUEST_INVALIDATED);
699 fetcher->reset();
703 bool SearchProvider::IsQuerySuitableForSuggest(bool* query_is_private) const {
704 *query_is_private = IsQueryPotentionallyPrivate();
706 // Don't run Suggest in incognito mode, if the engine doesn't support it, or
707 // if the user has disabled it. Also don't send potentionally private data
708 // to the default search provider. (It's always okay to send explicit
709 // keyword input to a keyword suggest server, if any.)
710 const TemplateURL* default_url = providers_.GetDefaultProviderURL();
711 const TemplateURL* keyword_url = providers_.GetKeywordProviderURL();
712 return !client_->IsOffTheRecord() && client_->SearchSuggestEnabled() &&
713 ((default_url && !default_url->suggestions_url().empty() &&
714 !*query_is_private) ||
715 (keyword_url && !keyword_url->suggestions_url().empty()));
718 bool SearchProvider::IsQueryPotentionallyPrivate() const {
719 // If the input type might be a URL, we take extra care so that private data
720 // isn't sent to the server.
722 // FORCED_QUERY means the user is explicitly asking us to search for this, so
723 // we assume it isn't a URL and/or there isn't private data.
724 if (input_.type() == metrics::OmniboxInputType::FORCED_QUERY)
725 return false;
727 // Next we check the scheme. If this is UNKNOWN/URL with a scheme that isn't
728 // http/https/ftp, we shouldn't send it. Sending things like file: and data:
729 // is both a waste of time and a disclosure of potentially private, local
730 // data. Other "schemes" may actually be usernames, and we don't want to send
731 // passwords. If the scheme is OK, we still need to check other cases below.
732 // If this is QUERY, then the presence of these schemes means the user
733 // explicitly typed one, and thus this is probably a URL that's being entered
734 // and happens to currently be invalid -- in which case we again want to run
735 // our checks below. Other QUERY cases are less likely to be URLs and thus we
736 // assume we're OK.
737 if (!LowerCaseEqualsASCII(input_.scheme(), url::kHttpScheme) &&
738 !LowerCaseEqualsASCII(input_.scheme(), url::kHttpsScheme) &&
739 !LowerCaseEqualsASCII(input_.scheme(), url::kFtpScheme))
740 return (input_.type() != metrics::OmniboxInputType::QUERY);
742 // Don't send URLs with usernames, queries or refs. Some of these are
743 // private, and the Suggest server is unlikely to have any useful results
744 // for any of them. Also don't send URLs with ports, as we may initially
745 // think that a username + password is a host + port (and we don't want to
746 // send usernames/passwords), and even if the port really is a port, the
747 // server is once again unlikely to have and useful results.
748 // Note that we only block based on refs if the input is URL-typed, as search
749 // queries can legitimately have #s in them which the URL parser
750 // overaggressively categorizes as a url with a ref.
751 const url::Parsed& parts = input_.parts();
752 if (parts.username.is_nonempty() || parts.port.is_nonempty() ||
753 parts.query.is_nonempty() ||
754 (parts.ref.is_nonempty() &&
755 (input_.type() == metrics::OmniboxInputType::URL)))
756 return true;
758 // Don't send anything for https except the hostname. Hostnames are OK
759 // because they are visible when the TCP connection is established, but the
760 // specific path may reveal private information.
761 if (LowerCaseEqualsASCII(input_.scheme(), url::kHttpsScheme) &&
762 parts.path.is_nonempty())
763 return true;
765 return false;
768 void SearchProvider::UpdateAllOldResults(bool minimal_changes) {
769 if (keyword_input_.text().empty()) {
770 // User is either in keyword mode with a blank input or out of
771 // keyword mode entirely.
772 keyword_results_.Clear();
774 UpdateOldResults(minimal_changes, &default_results_);
775 UpdateOldResults(minimal_changes, &keyword_results_);
778 void SearchProvider::PersistTopSuggestions(
779 SearchSuggestionParser::Results* results) {
780 // Mark any results matching the current top results as having been received
781 // prior to the last keystroke. That prevents asynchronous updates from
782 // clobbering top results, which may be used for inline autocompletion.
783 // Other results don't need similar changes, because they shouldn't be
784 // displayed asynchronously anyway.
785 if (!top_query_suggestion_match_contents_.empty()) {
786 for (SearchSuggestionParser::SuggestResults::iterator sug_it =
787 results->suggest_results.begin();
788 sug_it != results->suggest_results.end(); ++sug_it) {
789 if (sug_it->match_contents() == top_query_suggestion_match_contents_)
790 sug_it->set_received_after_last_keystroke(false);
793 if (top_navigation_suggestion_.is_valid()) {
794 for (SearchSuggestionParser::NavigationResults::iterator nav_it =
795 results->navigation_results.begin();
796 nav_it != results->navigation_results.end(); ++nav_it) {
797 if (nav_it->url() == top_navigation_suggestion_)
798 nav_it->set_received_after_last_keystroke(false);
803 void SearchProvider::ApplyCalculatedSuggestRelevance(
804 SearchSuggestionParser::SuggestResults* list) {
805 for (size_t i = 0; i < list->size(); ++i) {
806 SearchSuggestionParser::SuggestResult& result = (*list)[i];
807 result.set_relevance(
808 result.CalculateRelevance(input_, providers_.has_keyword_provider()) +
809 (list->size() - i - 1));
810 result.set_relevance_from_server(false);
814 void SearchProvider::ApplyCalculatedNavigationRelevance(
815 SearchSuggestionParser::NavigationResults* list) {
816 for (size_t i = 0; i < list->size(); ++i) {
817 SearchSuggestionParser::NavigationResult& result = (*list)[i];
818 result.set_relevance(
819 result.CalculateRelevance(input_, providers_.has_keyword_provider()) +
820 (list->size() - i - 1));
821 result.set_relevance_from_server(false);
825 net::URLFetcher* SearchProvider::CreateSuggestFetcher(
826 int id,
827 const TemplateURL* template_url,
828 const AutocompleteInput& input) {
829 if (!template_url || template_url->suggestions_url().empty())
830 return NULL;
832 // Bail if the suggestion URL is invalid with the given replacements.
833 TemplateURLRef::SearchTermsArgs search_term_args(input.text());
834 search_term_args.input_type = input.type();
835 search_term_args.cursor_position = input.cursor_position();
836 search_term_args.page_classification = input.current_page_classification();
837 if (OmniboxFieldTrial::EnableAnswersInSuggest()) {
838 search_term_args.session_token = GetSessionToken();
839 if (!prefetch_data_.full_query_text.empty()) {
840 search_term_args.prefetch_query =
841 base::UTF16ToUTF8(prefetch_data_.full_query_text);
842 search_term_args.prefetch_query_type =
843 base::UTF16ToUTF8(prefetch_data_.query_type);
846 GURL suggest_url(template_url->suggestions_url_ref().ReplaceSearchTerms(
847 search_term_args,
848 providers_.template_url_service()->search_terms_data()));
849 if (!suggest_url.is_valid())
850 return NULL;
851 // Send the current page URL if user setting and URL requirements are met and
852 // the user is in the field trial.
853 if (CanSendURL(current_page_url_, suggest_url, template_url,
854 input.current_page_classification(),
855 template_url_service_->search_terms_data(), client_.get()) &&
856 OmniboxFieldTrial::InZeroSuggestAfterTypingFieldTrial()) {
857 search_term_args.current_page_url = current_page_url_.spec();
858 // Create the suggest URL again with the current page URL.
859 suggest_url = GURL(template_url->suggestions_url_ref().ReplaceSearchTerms(
860 search_term_args,
861 providers_.template_url_service()->search_terms_data()));
864 LogOmniboxSuggestRequest(REQUEST_SENT);
866 net::URLFetcher* fetcher =
867 net::URLFetcher::Create(id, suggest_url, net::URLFetcher::GET, this);
868 fetcher->SetRequestContext(client_->RequestContext());
869 fetcher->SetLoadFlags(net::LOAD_DO_NOT_SAVE_COOKIES);
870 // Add Chrome experiment state to the request headers.
871 net::HttpRequestHeaders headers;
872 variations::VariationsHttpHeaderProvider::GetInstance()->AppendHeaders(
873 fetcher->GetOriginalURL(), client_->IsOffTheRecord(), false, &headers);
874 fetcher->SetExtraRequestHeaders(headers.ToString());
875 fetcher->Start();
876 return fetcher;
879 void SearchProvider::ConvertResultsToAutocompleteMatches() {
880 // Convert all the results to matches and add them to a map, so we can keep
881 // the most relevant match for each result.
882 base::TimeTicks start_time(base::TimeTicks::Now());
883 MatchMap map;
884 const base::Time no_time;
885 int did_not_accept_keyword_suggestion =
886 keyword_results_.suggest_results.empty() ?
887 TemplateURLRef::NO_SUGGESTIONS_AVAILABLE :
888 TemplateURLRef::NO_SUGGESTION_CHOSEN;
890 bool relevance_from_server;
891 int verbatim_relevance = GetVerbatimRelevance(&relevance_from_server);
892 int did_not_accept_default_suggestion =
893 default_results_.suggest_results.empty() ?
894 TemplateURLRef::NO_SUGGESTIONS_AVAILABLE :
895 TemplateURLRef::NO_SUGGESTION_CHOSEN;
896 const TemplateURL* keyword_url = providers_.GetKeywordProviderURL();
897 if (verbatim_relevance > 0) {
898 const base::string16& trimmed_verbatim =
899 base::CollapseWhitespace(input_.text(), false);
901 // Verbatim results don't get suggestions and hence, answers.
902 // Scan previous matches if the last answer-bearing suggestion matches
903 // verbatim, and if so, copy over answer contents.
904 base::string16 answer_contents;
905 base::string16 answer_type;
906 scoped_ptr<SuggestionAnswer> answer;
907 for (ACMatches::iterator it = matches_.begin(); it != matches_.end();
908 ++it) {
909 if (it->answer && it->fill_into_edit == trimmed_verbatim) {
910 answer_contents = it->answer_contents;
911 answer_type = it->answer_type;
912 answer = SuggestionAnswer::copy(it->answer.get());
913 break;
917 SearchSuggestionParser::SuggestResult verbatim(
918 trimmed_verbatim, AutocompleteMatchType::SEARCH_WHAT_YOU_TYPED,
919 trimmed_verbatim, base::string16(), base::string16(), answer_contents,
920 answer_type, answer.Pass(), std::string(), std::string(), false,
921 verbatim_relevance, relevance_from_server, false, trimmed_verbatim);
922 AddMatchToMap(verbatim, std::string(), did_not_accept_default_suggestion,
923 false, keyword_url != NULL, &map);
925 if (!keyword_input_.text().empty()) {
926 // We only create the verbatim search query match for a keyword
927 // if it's not an extension keyword. Extension keywords are handled
928 // in KeywordProvider::Start(). (Extensions are complicated...)
929 // Note: in this provider, SEARCH_OTHER_ENGINE must correspond
930 // to the keyword verbatim search query. Do not create other matches
931 // of type SEARCH_OTHER_ENGINE.
932 if (keyword_url &&
933 (keyword_url->GetType() != TemplateURL::OMNIBOX_API_EXTENSION)) {
934 bool keyword_relevance_from_server;
935 const int keyword_verbatim_relevance =
936 GetKeywordVerbatimRelevance(&keyword_relevance_from_server);
937 if (keyword_verbatim_relevance > 0) {
938 const base::string16& trimmed_verbatim =
939 base::CollapseWhitespace(keyword_input_.text(), false);
940 SearchSuggestionParser::SuggestResult verbatim(
941 trimmed_verbatim, AutocompleteMatchType::SEARCH_OTHER_ENGINE,
942 trimmed_verbatim, base::string16(), base::string16(),
943 base::string16(), base::string16(), nullptr, std::string(),
944 std::string(), true, keyword_verbatim_relevance,
945 keyword_relevance_from_server, false, trimmed_verbatim);
946 AddMatchToMap(verbatim, std::string(),
947 did_not_accept_keyword_suggestion, false, true, &map);
951 AddRawHistoryResultsToMap(true, did_not_accept_keyword_suggestion, &map);
952 AddRawHistoryResultsToMap(false, did_not_accept_default_suggestion, &map);
954 AddSuggestResultsToMap(keyword_results_.suggest_results,
955 keyword_results_.metadata, &map);
956 AddSuggestResultsToMap(default_results_.suggest_results,
957 default_results_.metadata, &map);
959 ACMatches matches;
960 for (MatchMap::const_iterator i(map.begin()); i != map.end(); ++i)
961 matches.push_back(i->second);
963 AddNavigationResultsToMatches(keyword_results_.navigation_results, &matches);
964 AddNavigationResultsToMatches(default_results_.navigation_results, &matches);
966 // Now add the most relevant matches to |matches_|. We take up to kMaxMatches
967 // suggest/navsuggest matches, regardless of origin. We always include in
968 // that set a legal default match if possible. If Instant Extended is enabled
969 // and we have server-provided (and thus hopefully more accurate) scores for
970 // some suggestions, we allow more of those, until we reach
971 // AutocompleteResult::kMaxMatches total matches (that is, enough to fill the
972 // whole popup).
974 // We will always return any verbatim matches, no matter how we obtained their
975 // scores, unless we have already accepted AutocompleteResult::kMaxMatches
976 // higher-scoring matches under the conditions above.
977 std::sort(matches.begin(), matches.end(), &AutocompleteMatch::MoreRelevant);
979 // Guarantee that if there's a legal default match anywhere in the result
980 // set that it'll get returned. The rotate() call does this by moving the
981 // default match to the front of the list.
982 ACMatches::iterator default_match = FindTopMatch(&matches);
983 if (default_match != matches.end())
984 std::rotate(matches.begin(), default_match, default_match + 1);
986 // It's possible to get a copy of an answer from previous matches and get the
987 // same or a different answer to another server-provided suggestion. In the
988 // future we may decide that we want to have answers attached to multiple
989 // suggestions, but the current assumption is that there should only ever be
990 // one suggestion with an answer. To maintain this assumption, remove any
991 // answers after the first.
992 RemoveExtraAnswers(&matches);
994 matches_.clear();
995 size_t num_suggestions = 0;
996 for (ACMatches::const_iterator i(matches.begin());
997 (i != matches.end()) &&
998 (matches_.size() < AutocompleteResult::kMaxMatches);
999 ++i) {
1000 // SEARCH_OTHER_ENGINE is only used in the SearchProvider for the keyword
1001 // verbatim result, so this condition basically means "if this match is a
1002 // suggestion of some sort".
1003 if ((i->type != AutocompleteMatchType::SEARCH_WHAT_YOU_TYPED) &&
1004 (i->type != AutocompleteMatchType::SEARCH_OTHER_ENGINE)) {
1005 // If we've already hit the limit on non-server-scored suggestions, and
1006 // this isn't a server-scored suggestion we can add, skip it.
1007 if ((num_suggestions >= kMaxMatches) &&
1008 (!chrome::IsInstantExtendedAPIEnabled() ||
1009 (i->GetAdditionalInfo(kRelevanceFromServerKey) != kTrue))) {
1010 continue;
1013 ++num_suggestions;
1016 matches_.push_back(*i);
1018 UMA_HISTOGRAM_TIMES("Omnibox.SearchProvider.ConvertResultsTime",
1019 base::TimeTicks::Now() - start_time);
1022 void SearchProvider::RemoveExtraAnswers(ACMatches* matches) {
1023 bool answer_seen = false;
1024 for (ACMatches::iterator it = matches->begin(); it != matches->end(); ++it) {
1025 if (it->answer) {
1026 if (!answer_seen) {
1027 answer_seen = true;
1028 } else {
1029 it->answer_contents.clear();
1030 it->answer_type.clear();
1031 it->answer.reset();
1037 ACMatches::const_iterator SearchProvider::FindTopMatch() const {
1038 ACMatches::const_iterator it = matches_.begin();
1039 while ((it != matches_.end()) && !it->allowed_to_be_default_match)
1040 ++it;
1041 return it;
1044 bool SearchProvider::IsTopMatchSearchWithURLInput() const {
1045 ACMatches::const_iterator first_match = FindTopMatch();
1046 return (input_.type() == metrics::OmniboxInputType::URL) &&
1047 (first_match != matches_.end()) &&
1048 (first_match->relevance > CalculateRelevanceForVerbatim()) &&
1049 (first_match->type != AutocompleteMatchType::NAVSUGGEST) &&
1050 (first_match->type != AutocompleteMatchType::NAVSUGGEST_PERSONALIZED);
1053 void SearchProvider::AddNavigationResultsToMatches(
1054 const SearchSuggestionParser::NavigationResults& navigation_results,
1055 ACMatches* matches) {
1056 for (SearchSuggestionParser::NavigationResults::const_iterator it =
1057 navigation_results.begin(); it != navigation_results.end(); ++it) {
1058 matches->push_back(NavigationToMatch(*it));
1059 // In the absence of suggested relevance scores, use only the single
1060 // highest-scoring result. (The results are already sorted by relevance.)
1061 if (!it->relevance_from_server())
1062 return;
1066 void SearchProvider::AddRawHistoryResultsToMap(bool is_keyword,
1067 int did_not_accept_suggestion,
1068 MatchMap* map) {
1069 const HistoryResults& raw_results =
1070 is_keyword ? raw_keyword_history_results_ : raw_default_history_results_;
1071 if (!OmniboxFieldTrial::EnableAnswersInSuggest() && raw_results.empty())
1072 return;
1074 base::TimeTicks start_time(base::TimeTicks::Now());
1076 // Until Answers becomes default, scoring of history results will still happen
1077 // here for non-Answers Chrome, to prevent scoring performance regressions
1078 // resulting from moving the scoring code before the suggest request is sent.
1079 // For users with Answers enabled, the history results have already been
1080 // scored earlier, right after calling DoHistoryQuery().
1081 SearchSuggestionParser::SuggestResults local_transformed_results;
1082 const SearchSuggestionParser::SuggestResults* transformed_results = NULL;
1083 if (!OmniboxFieldTrial::EnableAnswersInSuggest()) {
1084 ScoreHistoryResults(raw_results, is_keyword, &local_transformed_results);
1085 transformed_results = &local_transformed_results;
1086 } else {
1087 transformed_results = is_keyword ? &transformed_keyword_history_results_
1088 : &transformed_default_history_results_;
1090 DCHECK(transformed_results);
1091 AddTransformedHistoryResultsToMap(
1092 *transformed_results, did_not_accept_suggestion, map);
1093 UMA_HISTOGRAM_TIMES("Omnibox.SearchProvider.AddHistoryResultsTime",
1094 base::TimeTicks::Now() - start_time);
1097 void SearchProvider::AddTransformedHistoryResultsToMap(
1098 const SearchSuggestionParser::SuggestResults& transformed_results,
1099 int did_not_accept_suggestion,
1100 MatchMap* map) {
1101 for (SearchSuggestionParser::SuggestResults::const_iterator i(
1102 transformed_results.begin());
1103 i != transformed_results.end();
1104 ++i) {
1105 AddMatchToMap(*i, std::string(), did_not_accept_suggestion, true,
1106 providers_.GetKeywordProviderURL() != NULL, map);
1110 SearchSuggestionParser::SuggestResults
1111 SearchProvider::ScoreHistoryResultsHelper(const HistoryResults& results,
1112 bool base_prevent_inline_autocomplete,
1113 bool input_multiple_words,
1114 const base::string16& input_text,
1115 bool is_keyword) {
1116 SearchSuggestionParser::SuggestResults scored_results;
1117 // True if the user has asked this exact query previously.
1118 bool found_what_you_typed_match = false;
1119 const bool prevent_search_history_inlining =
1120 OmniboxFieldTrial::SearchHistoryPreventInlining(
1121 input_.current_page_classification());
1122 const base::string16& trimmed_input =
1123 base::CollapseWhitespace(input_text, false);
1124 for (HistoryResults::const_iterator i(results.begin()); i != results.end();
1125 ++i) {
1126 const base::string16& trimmed_suggestion =
1127 base::CollapseWhitespace(i->term, false);
1129 // Don't autocomplete multi-word queries that have only been seen once
1130 // unless the user has typed more than one word.
1131 bool prevent_inline_autocomplete = base_prevent_inline_autocomplete ||
1132 (!input_multiple_words && (i->visits < 2) &&
1133 HasMultipleWords(trimmed_suggestion));
1135 int relevance = CalculateRelevanceForHistory(
1136 i->time, is_keyword, !prevent_inline_autocomplete,
1137 prevent_search_history_inlining);
1138 // Add the match to |scored_results| by putting the what-you-typed match
1139 // on the front and appending all other matches. We want the what-you-
1140 // typed match to always be first.
1141 SearchSuggestionParser::SuggestResults::iterator insertion_position =
1142 scored_results.end();
1143 if (trimmed_suggestion == trimmed_input) {
1144 found_what_you_typed_match = true;
1145 insertion_position = scored_results.begin();
1147 SearchSuggestionParser::SuggestResult history_suggestion(
1148 trimmed_suggestion, AutocompleteMatchType::SEARCH_HISTORY,
1149 trimmed_suggestion, base::string16(), base::string16(),
1150 base::string16(), base::string16(), nullptr, std::string(),
1151 std::string(), is_keyword, relevance, false, false, trimmed_input);
1152 // History results are synchronous; they are received on the last keystroke.
1153 history_suggestion.set_received_after_last_keystroke(false);
1154 scored_results.insert(insertion_position, history_suggestion);
1157 // History returns results sorted for us. However, we may have docked some
1158 // results' scores, so things are no longer in order. While keeping the
1159 // what-you-typed match at the front (if it exists), do a stable sort to get
1160 // things back in order without otherwise disturbing results with equal
1161 // scores, then force the scores to be unique, so that the order in which
1162 // they're shown is deterministic.
1163 std::stable_sort(scored_results.begin() +
1164 (found_what_you_typed_match ? 1 : 0),
1165 scored_results.end(),
1166 CompareScoredResults());
1168 // Don't autocomplete to search terms that would normally be treated as URLs
1169 // when typed. For example, if the user searched for "google.com" and types
1170 // "goog", don't autocomplete to the search term "google.com". Otherwise,
1171 // the input will look like a URL but act like a search, which is confusing.
1172 // The 1200 relevance score threshold in the test below is the lowest
1173 // possible score in CalculateRelevanceForHistory()'s aggressive-scoring
1174 // curve. This is an appropriate threshold to use to decide if we're overly
1175 // aggressively inlining because, if we decide the answer is yes, the
1176 // way we resolve it it to not use the aggressive-scoring curve.
1177 // NOTE: We don't check for autocompleting to URLs in the following cases:
1178 // * When inline autocomplete is disabled, we won't be inline autocompleting
1179 // this term, so we don't need to worry about confusion as much. This
1180 // also prevents calling Classify() again from inside the classifier
1181 // (which will corrupt state and likely crash), since the classifier
1182 // always disables inline autocomplete.
1183 // * When the user has typed the whole string before as a query, then it's
1184 // likely the user has no expectation that term should be interpreted as
1185 // as a URL, so we need not do anything special to preserve user
1186 // expectation.
1187 int last_relevance = 0;
1188 if (!base_prevent_inline_autocomplete && !found_what_you_typed_match &&
1189 scored_results.front().relevance() >= 1200) {
1190 AutocompleteMatch match;
1191 client_->Classify(scored_results.front().suggestion(), false, false,
1192 input_.current_page_classification(), &match, NULL);
1193 // Demote this match that would normally be interpreted as a URL to have
1194 // the highest score a previously-issued search query could have when
1195 // scoring with the non-aggressive method. A consequence of demoting
1196 // by revising |last_relevance| is that this match and all following
1197 // matches get demoted; the relative order of matches is preserved.
1198 // One could imagine demoting only those matches that might cause
1199 // confusion (which, by the way, might change the relative order of
1200 // matches. We have decided to go with the simple demote-all approach
1201 // because selective demotion requires multiple Classify() calls and
1202 // such calls can be expensive (as expensive as running the whole
1203 // autocomplete system).
1204 if (!AutocompleteMatch::IsSearchType(match.type)) {
1205 last_relevance = CalculateRelevanceForHistory(
1206 base::Time::Now(), is_keyword, false,
1207 prevent_search_history_inlining);
1211 for (SearchSuggestionParser::SuggestResults::iterator i(
1212 scored_results.begin()); i != scored_results.end(); ++i) {
1213 if ((last_relevance != 0) && (i->relevance() >= last_relevance))
1214 i->set_relevance(last_relevance - 1);
1215 last_relevance = i->relevance();
1218 return scored_results;
1221 void SearchProvider::ScoreHistoryResults(
1222 const HistoryResults& results,
1223 bool is_keyword,
1224 SearchSuggestionParser::SuggestResults* scored_results) {
1225 DCHECK(scored_results);
1226 scored_results->clear();
1228 if (results.empty()) {
1229 return;
1232 bool prevent_inline_autocomplete = input_.prevent_inline_autocomplete() ||
1233 (input_.type() == metrics::OmniboxInputType::URL);
1234 const base::string16 input_text = GetInput(is_keyword).text();
1235 bool input_multiple_words = HasMultipleWords(input_text);
1237 if (!prevent_inline_autocomplete && input_multiple_words) {
1238 // ScoreHistoryResultsHelper() allows autocompletion of multi-word, 1-visit
1239 // queries if the input also has multiple words. But if we were already
1240 // scoring a multi-word, multi-visit query aggressively, and the current
1241 // input is still a prefix of it, then changing the suggestion suddenly
1242 // feels wrong. To detect this case, first score as if only one word has
1243 // been typed, then check if the best result came from aggressive search
1244 // history scoring. If it did, then just keep that score set. This
1245 // 1200 the lowest possible score in CalculateRelevanceForHistory()'s
1246 // aggressive-scoring curve.
1247 *scored_results = ScoreHistoryResultsHelper(
1248 results, prevent_inline_autocomplete, false, input_text, is_keyword);
1249 if ((scored_results->front().relevance() < 1200) ||
1250 !HasMultipleWords(scored_results->front().suggestion()))
1251 scored_results->clear(); // Didn't detect the case above, score normally.
1253 if (scored_results->empty()) {
1254 *scored_results = ScoreHistoryResultsHelper(results,
1255 prevent_inline_autocomplete,
1256 input_multiple_words,
1257 input_text,
1258 is_keyword);
1262 void SearchProvider::AddSuggestResultsToMap(
1263 const SearchSuggestionParser::SuggestResults& results,
1264 const std::string& metadata,
1265 MatchMap* map) {
1266 for (size_t i = 0; i < results.size(); ++i) {
1267 AddMatchToMap(results[i], metadata, i, false,
1268 providers_.GetKeywordProviderURL() != NULL, map);
1272 int SearchProvider::GetVerbatimRelevance(bool* relevance_from_server) const {
1273 // Use the suggested verbatim relevance score if it is non-negative (valid),
1274 // if inline autocomplete isn't prevented (always show verbatim on backspace),
1275 // and if it won't suppress verbatim, leaving no default provider matches.
1276 // Otherwise, if the default provider returned no matches and was still able
1277 // to suppress verbatim, the user would have no search/nav matches and may be
1278 // left unable to search using their default provider from the omnibox.
1279 // Check for results on each verbatim calculation, as results from older
1280 // queries (on previous input) may be trimmed for failing to inline new input.
1281 bool use_server_relevance =
1282 (default_results_.verbatim_relevance >= 0) &&
1283 !input_.prevent_inline_autocomplete() &&
1284 ((default_results_.verbatim_relevance > 0) ||
1285 !default_results_.suggest_results.empty() ||
1286 !default_results_.navigation_results.empty());
1287 if (relevance_from_server)
1288 *relevance_from_server = use_server_relevance;
1289 return use_server_relevance ?
1290 default_results_.verbatim_relevance : CalculateRelevanceForVerbatim();
1293 int SearchProvider::CalculateRelevanceForVerbatim() const {
1294 if (!providers_.keyword_provider().empty())
1295 return 250;
1296 return CalculateRelevanceForVerbatimIgnoringKeywordModeState();
1299 int SearchProvider::
1300 CalculateRelevanceForVerbatimIgnoringKeywordModeState() const {
1301 switch (input_.type()) {
1302 case metrics::OmniboxInputType::UNKNOWN:
1303 case metrics::OmniboxInputType::QUERY:
1304 case metrics::OmniboxInputType::FORCED_QUERY:
1305 return kNonURLVerbatimRelevance;
1307 case metrics::OmniboxInputType::URL:
1308 return 850;
1310 default:
1311 NOTREACHED();
1312 return 0;
1316 int SearchProvider::GetKeywordVerbatimRelevance(
1317 bool* relevance_from_server) const {
1318 // Use the suggested verbatim relevance score if it is non-negative (valid),
1319 // if inline autocomplete isn't prevented (always show verbatim on backspace),
1320 // and if it won't suppress verbatim, leaving no keyword provider matches.
1321 // Otherwise, if the keyword provider returned no matches and was still able
1322 // to suppress verbatim, the user would have no search/nav matches and may be
1323 // left unable to search using their keyword provider from the omnibox.
1324 // Check for results on each verbatim calculation, as results from older
1325 // queries (on previous input) may be trimmed for failing to inline new input.
1326 bool use_server_relevance =
1327 (keyword_results_.verbatim_relevance >= 0) &&
1328 !input_.prevent_inline_autocomplete() &&
1329 ((keyword_results_.verbatim_relevance > 0) ||
1330 !keyword_results_.suggest_results.empty() ||
1331 !keyword_results_.navigation_results.empty());
1332 if (relevance_from_server)
1333 *relevance_from_server = use_server_relevance;
1334 return use_server_relevance ?
1335 keyword_results_.verbatim_relevance :
1336 CalculateRelevanceForKeywordVerbatim(keyword_input_.type(),
1337 keyword_input_.prefer_keyword());
1340 int SearchProvider::CalculateRelevanceForHistory(
1341 const base::Time& time,
1342 bool is_keyword,
1343 bool use_aggressive_method,
1344 bool prevent_search_history_inlining) const {
1345 // The relevance of past searches falls off over time. There are two distinct
1346 // equations used. If the first equation is used (searches to the primary
1347 // provider that we want to score aggressively), the score is in the range
1348 // 1300-1599 (unless |prevent_search_history_inlining|, in which case
1349 // it's in the range 1200-1299). If the second equation is used the
1350 // relevance of a search 15 minutes ago is discounted 50 points, while the
1351 // relevance of a search two weeks ago is discounted 450 points.
1352 double elapsed_time = std::max((base::Time::Now() - time).InSecondsF(), 0.0);
1353 bool is_primary_provider = is_keyword || !providers_.has_keyword_provider();
1354 if (is_primary_provider && use_aggressive_method) {
1355 // Searches with the past two days get a different curve.
1356 const double autocomplete_time = 2 * 24 * 60 * 60;
1357 if (elapsed_time < autocomplete_time) {
1358 int max_score = is_keyword ? 1599 : 1399;
1359 if (prevent_search_history_inlining)
1360 max_score = 1299;
1361 return max_score - static_cast<int>(99 *
1362 std::pow(elapsed_time / autocomplete_time, 2.5));
1364 elapsed_time -= autocomplete_time;
1367 const int score_discount =
1368 static_cast<int>(6.5 * std::pow(elapsed_time, 0.3));
1370 // Don't let scores go below 0. Negative relevance scores are meaningful in
1371 // a different way.
1372 int base_score;
1373 if (is_primary_provider)
1374 base_score = (input_.type() == metrics::OmniboxInputType::URL) ? 750 : 1050;
1375 else
1376 base_score = 200;
1377 return std::max(0, base_score - score_discount);
1380 AutocompleteMatch SearchProvider::NavigationToMatch(
1381 const SearchSuggestionParser::NavigationResult& navigation) {
1382 base::string16 input;
1383 const bool trimmed_whitespace = base::TrimWhitespace(
1384 navigation.from_keyword_provider() ?
1385 keyword_input_.text() : input_.text(),
1386 base::TRIM_TRAILING, &input) != base::TRIM_NONE;
1387 AutocompleteMatch match(this, navigation.relevance(), false,
1388 navigation.type());
1389 match.destination_url = navigation.url();
1390 BaseSearchProvider::SetDeletionURL(navigation.deletion_url(), &match);
1391 // First look for the user's input inside the formatted url as it would be
1392 // without trimming the scheme, so we can find matches at the beginning of the
1393 // scheme.
1394 const URLPrefix* prefix =
1395 URLPrefix::BestURLPrefix(navigation.formatted_url(), input);
1396 size_t match_start = (prefix == NULL) ?
1397 navigation.formatted_url().find(input) : prefix->prefix.length();
1398 bool trim_http = !AutocompleteInput::HasHTTPScheme(input) &&
1399 (!prefix || (match_start != 0));
1400 const net::FormatUrlTypes format_types =
1401 net::kFormatUrlOmitAll & ~(trim_http ? 0 : net::kFormatUrlOmitHTTP);
1403 const std::string languages(client_->AcceptLanguages());
1404 size_t inline_autocomplete_offset = (prefix == NULL) ?
1405 base::string16::npos : (match_start + input.length());
1406 match.fill_into_edit +=
1407 AutocompleteInput::FormattedStringWithEquivalentMeaning(
1408 navigation.url(),
1409 net::FormatUrl(navigation.url(), languages, format_types,
1410 net::UnescapeRule::SPACES, NULL, NULL,
1411 &inline_autocomplete_offset),
1412 client_->SchemeClassifier());
1413 // Preserve the forced query '?' prefix in |match.fill_into_edit|.
1414 // Otherwise, user edits to a suggestion would show non-Search results.
1415 if (input_.type() == metrics::OmniboxInputType::FORCED_QUERY) {
1416 match.fill_into_edit.insert(0, base::ASCIIToUTF16("?"));
1417 if (inline_autocomplete_offset != base::string16::npos)
1418 ++inline_autocomplete_offset;
1420 if (inline_autocomplete_offset != base::string16::npos) {
1421 DCHECK(inline_autocomplete_offset <= match.fill_into_edit.length());
1422 match.inline_autocompletion =
1423 match.fill_into_edit.substr(inline_autocomplete_offset);
1425 // An inlineable navsuggestion can only be the default match when there
1426 // is no keyword provider active, lest it appear first and break the user
1427 // out of keyword mode. We also must have received the navsuggestion before
1428 // the last keystroke, to prevent asynchronous inline autocompletions changes.
1429 // The navsuggestion can also only be default if either the inline
1430 // autocompletion is empty or we're not preventing inline autocompletion.
1431 // Finally, if we have an inlineable navsuggestion with an inline completion
1432 // that we're not preventing, make sure we didn't trim any whitespace.
1433 // We don't want to claim http://foo.com/bar is inlineable against the
1434 // input "foo.com/b ".
1435 match.allowed_to_be_default_match =
1436 (prefix != NULL) &&
1437 (providers_.GetKeywordProviderURL() == NULL) &&
1438 !navigation.received_after_last_keystroke() &&
1439 (match.inline_autocompletion.empty() ||
1440 (!input_.prevent_inline_autocomplete() && !trimmed_whitespace));
1441 match.EnsureUWYTIsAllowedToBeDefault(
1442 input_.canonicalized_url(), providers_.template_url_service());
1444 match.contents = navigation.match_contents();
1445 match.contents_class = navigation.match_contents_class();
1446 match.description = navigation.description();
1447 AutocompleteMatch::ClassifyMatchInString(input, match.description,
1448 ACMatchClassification::NONE, &match.description_class);
1450 match.RecordAdditionalInfo(
1451 kRelevanceFromServerKey,
1452 navigation.relevance_from_server() ? kTrue : kFalse);
1453 match.RecordAdditionalInfo(kShouldPrefetchKey, kFalse);
1455 return match;
1458 void SearchProvider::UpdateDone() {
1459 // We're done when the timer isn't running and there are no suggest queries
1460 // pending.
1461 done_ = !timer_.IsRunning() && !default_fetcher_ && !keyword_fetcher_;
1464 std::string SearchProvider::GetSessionToken() {
1465 base::TimeTicks current_time(base::TimeTicks::Now());
1466 // Renew token if it expired.
1467 if (current_time > token_expiration_time_) {
1468 const size_t kTokenBytes = 12;
1469 std::string raw_data;
1470 base::RandBytes(WriteInto(&raw_data, kTokenBytes + 1), kTokenBytes);
1471 base::Base64Encode(raw_data, &current_token_);
1473 // Make the base64 encoded value URL and filename safe(see RFC 3548).
1474 std::replace(current_token_.begin(), current_token_.end(), '+', '-');
1475 std::replace(current_token_.begin(), current_token_.end(), '/', '_');
1478 // Extend expiration time another 60 seconds.
1479 token_expiration_time_ = current_time + base::TimeDelta::FromSeconds(60);
1481 return current_token_;
1484 void SearchProvider::RegisterDisplayedAnswers(
1485 const AutocompleteResult& result) {
1486 if (result.empty())
1487 return;
1489 // The answer must be in the first or second slot to be considered. It should
1490 // only be in the second slot if AutocompleteController ranked a local search
1491 // history or a verbatim item higher than the answer.
1492 AutocompleteResult::const_iterator match = result.begin();
1493 if (match->answer_contents.empty() && result.size() > 1)
1494 ++match;
1495 if (match->answer_contents.empty() || match->answer_type.empty() ||
1496 match->fill_into_edit.empty())
1497 return;
1499 // Valid answer encountered, cache it for further queries.
1500 answers_cache_.UpdateRecentAnswers(match->fill_into_edit, match->answer_type);
1503 AnswersQueryData SearchProvider::FindAnswersPrefetchData() {
1504 // Retrieve the top entry from scored history results.
1505 MatchMap map;
1506 AddTransformedHistoryResultsToMap(transformed_keyword_history_results_,
1507 TemplateURLRef::NO_SUGGESTIONS_AVAILABLE,
1508 &map);
1509 AddTransformedHistoryResultsToMap(transformed_default_history_results_,
1510 TemplateURLRef::NO_SUGGESTIONS_AVAILABLE,
1511 &map);
1513 ACMatches matches;
1514 for (MatchMap::const_iterator i(map.begin()); i != map.end(); ++i)
1515 matches.push_back(i->second);
1516 std::sort(matches.begin(), matches.end(), &AutocompleteMatch::MoreRelevant);
1518 // If there is a top scoring entry, find the corresponding answer.
1519 if (!matches.empty())
1520 return answers_cache_.GetTopAnswerEntry(matches[0].contents);
1522 return AnswersQueryData();