Content settings: remove some plugin-related code/resources when... there are no...
[chromium-blink-merge.git] / components / omnibox / browser / search_provider.cc
blob7f4aab1bea67bc7ce6f33fbd9396c859d273406a
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/browser/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_macros.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/browser/autocomplete_provider_client.h"
25 #include "components/omnibox/browser/autocomplete_provider_listener.h"
26 #include "components/omnibox/browser/autocomplete_result.h"
27 #include "components/omnibox/browser/keyword_provider.h"
28 #include "components/omnibox/browser/omnibox_field_trial.h"
29 #include "components/omnibox/browser/suggestion_answer.h"
30 #include "components/omnibox/browser/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/url_formatter/url_formatter.h"
35 #include "components/variations/net/variations_http_header_provider.h"
36 #include "grit/components_strings.h"
37 #include "net/base/escape.h"
38 #include "net/base/load_flags.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(AutocompleteProviderClient* client,
122 AutocompleteProviderListener* listener)
123 : BaseSearchProvider(AutocompleteProvider::TYPE_SEARCH, client),
124 listener_(listener),
125 providers_(client->GetTemplateURLService()),
126 answers_cache_(10) {
127 TemplateURLService* template_url_service = client->GetTemplateURLService();
129 // |template_url_service| can be null in tests.
130 if (template_url_service)
131 template_url_service->AddObserver(this);
134 // static
135 std::string SearchProvider::GetSuggestMetadata(const AutocompleteMatch& match) {
136 return match.GetAdditionalInfo(kSuggestMetadataKey);
139 void SearchProvider::ResetSession() {
140 set_field_trial_triggered_in_session(false);
143 void SearchProvider::OnTemplateURLServiceChanged() {
144 // Only update matches at this time if we haven't already claimed we're done
145 // processing the query.
146 if (done_)
147 return;
149 // Check that the engines we're using weren't renamed or deleted. (In short,
150 // require that an engine still exists with the keywords in use.) For each
151 // deleted engine, cancel the in-flight request if any, drop its suggestions,
152 // and, in the case when the default provider was affected, point the cached
153 // default provider keyword name at the new name for the default provider.
155 // Get...ProviderURL() looks up the provider using the cached keyword name
156 // stored in |providers_|.
157 const TemplateURL* template_url = providers_.GetDefaultProviderURL();
158 if (!template_url) {
159 CancelFetcher(&default_fetcher_);
160 default_results_.Clear();
161 providers_.set(client()
162 ->GetTemplateURLService()
163 ->GetDefaultSearchProvider()
164 ->keyword(),
165 providers_.keyword_provider());
167 template_url = providers_.GetKeywordProviderURL();
168 if (!providers_.keyword_provider().empty() && !template_url) {
169 CancelFetcher(&keyword_fetcher_);
170 keyword_results_.Clear();
171 providers_.set(providers_.default_provider(), base::string16());
173 // It's possible the template URL changed without changing associated keyword.
174 // Hence, it's always necessary to update matches to use the new template
175 // URL. (One could cache the template URL and only call UpdateMatches() and
176 // OnProviderUpdate() if a keyword was deleted/renamed or the template URL
177 // was changed. That would save extra calls to these functions. However,
178 // this is uncommon and not likely to be worth the extra work.)
179 UpdateMatches();
180 listener_->OnProviderUpdate(true); // always pretend something changed
183 SearchProvider::~SearchProvider() {
184 TemplateURLService* template_url_service = client()->GetTemplateURLService();
185 if (template_url_service)
186 template_url_service->RemoveObserver(this);
189 // static
190 int SearchProvider::CalculateRelevanceForKeywordVerbatim(
191 metrics::OmniboxInputType::Type type,
192 bool prefer_keyword) {
193 // This function is responsible for scoring verbatim query matches
194 // for non-extension keywords. KeywordProvider::CalculateRelevance()
195 // scores verbatim query matches for extension keywords, as well as
196 // for keyword matches (i.e., suggestions of a keyword itself, not a
197 // suggestion of a query on a keyword search engine). These two
198 // functions are currently in sync, but there's no reason we
199 // couldn't decide in the future to score verbatim matches
200 // differently for extension and non-extension keywords. If you
201 // make such a change, however, you should update this comment to
202 // describe it, so it's clear why the functions diverge.
203 if (prefer_keyword)
204 return 1500;
205 return (type == metrics::OmniboxInputType::QUERY) ? 1450 : 1100;
208 // static
209 void SearchProvider::UpdateOldResults(
210 bool minimal_changes,
211 SearchSuggestionParser::Results* results) {
212 // When called without |minimal_changes|, it likely means the user has
213 // pressed a key. Revise the cached results appropriately.
214 if (!minimal_changes) {
215 for (SearchSuggestionParser::SuggestResults::iterator sug_it =
216 results->suggest_results.begin();
217 sug_it != results->suggest_results.end(); ++sug_it) {
218 sug_it->set_received_after_last_keystroke(false);
220 for (SearchSuggestionParser::NavigationResults::iterator nav_it =
221 results->navigation_results.begin();
222 nav_it != results->navigation_results.end(); ++nav_it) {
223 nav_it->set_received_after_last_keystroke(false);
228 // static
229 ACMatches::iterator SearchProvider::FindTopMatch(ACMatches* matches) {
230 ACMatches::iterator it = matches->begin();
231 while ((it != matches->end()) && !it->allowed_to_be_default_match)
232 ++it;
233 return it;
236 void SearchProvider::Start(const AutocompleteInput& input,
237 bool minimal_changes) {
238 // Do our best to load the model as early as possible. This will reduce
239 // odds of having the model not ready when really needed (a non-empty input).
240 TemplateURLService* model = client()->GetTemplateURLService();
241 DCHECK(model);
242 model->Load();
244 matches_.clear();
245 set_field_trial_triggered(false);
247 // Can't return search/suggest results for bogus input.
248 if (input.from_omnibox_focus() ||
249 input.type() == metrics::OmniboxInputType::INVALID) {
250 Stop(true, false);
251 return;
254 keyword_input_ = input;
255 const TemplateURL* keyword_provider =
256 KeywordProvider::GetSubstitutingTemplateURLForInput(model,
257 &keyword_input_);
258 if (keyword_provider == NULL)
259 keyword_input_.Clear();
260 else if (keyword_input_.text().empty())
261 keyword_provider = NULL;
263 const TemplateURL* default_provider = model->GetDefaultSearchProvider();
264 if (default_provider &&
265 !default_provider->SupportsReplacement(model->search_terms_data()))
266 default_provider = NULL;
268 if (keyword_provider == default_provider)
269 default_provider = NULL; // No use in querying the same provider twice.
271 if (!default_provider && !keyword_provider) {
272 // No valid providers.
273 Stop(true, false);
274 return;
277 // If we're still running an old query but have since changed the query text
278 // or the providers, abort the query.
279 base::string16 default_provider_keyword(default_provider ?
280 default_provider->keyword() : base::string16());
281 base::string16 keyword_provider_keyword(keyword_provider ?
282 keyword_provider->keyword() : base::string16());
283 if (!minimal_changes ||
284 !providers_.equal(default_provider_keyword, keyword_provider_keyword)) {
285 // Cancel any in-flight suggest requests.
286 if (!done_)
287 Stop(false, false);
290 providers_.set(default_provider_keyword, keyword_provider_keyword);
292 if (input.text().empty()) {
293 // User typed "?" alone. Give them a placeholder result indicating what
294 // this syntax does.
295 if (default_provider) {
296 AutocompleteMatch match;
297 match.provider = this;
298 match.contents.assign(l10n_util::GetStringUTF16(IDS_EMPTY_KEYWORD_VALUE));
299 match.contents_class.push_back(
300 ACMatchClassification(0, ACMatchClassification::NONE));
301 match.keyword = providers_.default_provider();
302 match.allowed_to_be_default_match = true;
303 matches_.push_back(match);
305 Stop(true, false);
306 return;
309 input_ = input;
311 DoHistoryQuery(minimal_changes);
312 // Answers needs scored history results before any suggest query has been
313 // started, since the query for answer-bearing results needs additional
314 // prefetch information based on the highest-scored local history result.
315 ScoreHistoryResults(raw_default_history_results_,
316 false,
317 &transformed_default_history_results_);
318 ScoreHistoryResults(raw_keyword_history_results_,
319 true,
320 &transformed_keyword_history_results_);
321 prefetch_data_ = FindAnswersPrefetchData();
323 // Raw results are not needed any more.
324 raw_default_history_results_.clear();
325 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()->GetAcceptLanguages());
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 client()->GetTemplateURLService()->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_ =
559 CreateSuggestFetcher(kDefaultProviderURLFetcherID,
560 providers_.GetDefaultProviderURL(), input_);
562 keyword_fetcher_ =
563 CreateSuggestFetcher(kKeywordProviderURLFetcherID,
564 providers_.GetKeywordProviderURL(), keyword_input_);
566 // Both the above can fail if the providers have been modified or deleted
567 // since the query began.
568 if (!default_fetcher_ && !keyword_fetcher_) {
569 UpdateDone();
570 // We only need to update the listener if we're actually done.
571 if (done_)
572 listener_->OnProviderUpdate(false);
573 } else {
574 // Sent at least one request.
575 time_suggest_request_sent_ = base::TimeTicks::Now();
579 void SearchProvider::DoHistoryQuery(bool minimal_changes) {
580 // The history query results are synchronous, so if minimal_changes is true,
581 // we still have the last results and don't need to do anything.
582 if (minimal_changes)
583 return;
585 raw_keyword_history_results_.clear();
586 raw_default_history_results_.clear();
588 if (OmniboxFieldTrial::SearchHistoryDisable(
589 input_.current_page_classification()))
590 return;
592 history::URLDatabase* url_db = client()->GetInMemoryDatabase();
593 if (!url_db)
594 return;
596 // Request history for both the keyword and default provider. We grab many
597 // more matches than we'll ultimately clamp to so that if there are several
598 // recent multi-word matches who scores are lowered (see
599 // ScoreHistoryResults()), they won't crowd out older, higher-scoring
600 // matches. Note that this doesn't fix the problem entirely, but merely
601 // limits it to cases with a very large number of such multi-word matches; for
602 // now, this seems OK compared with the complexity of a real fix, which would
603 // require multiple searches and tracking of "single- vs. multi-word" in the
604 // database.
605 int num_matches = kMaxMatches * 5;
606 const TemplateURL* default_url = providers_.GetDefaultProviderURL();
607 if (default_url) {
608 const base::TimeTicks start_time = base::TimeTicks::Now();
609 url_db->GetMostRecentKeywordSearchTerms(default_url->id(),
610 input_.text(),
611 num_matches,
612 &raw_default_history_results_);
613 UMA_HISTOGRAM_TIMES(
614 "Omnibox.SearchProvider.GetMostRecentKeywordTermsDefaultProviderTime",
615 base::TimeTicks::Now() - start_time);
617 const TemplateURL* keyword_url = providers_.GetKeywordProviderURL();
618 if (keyword_url) {
619 url_db->GetMostRecentKeywordSearchTerms(keyword_url->id(),
620 keyword_input_.text(),
621 num_matches,
622 &raw_keyword_history_results_);
626 base::TimeDelta SearchProvider::GetSuggestQueryDelay() const {
627 bool from_last_keystroke;
628 int polling_delay_ms;
629 OmniboxFieldTrial::GetSuggestPollingStrategy(&from_last_keystroke,
630 &polling_delay_ms);
632 base::TimeDelta delay(base::TimeDelta::FromMilliseconds(polling_delay_ms));
633 if (from_last_keystroke)
634 return delay;
636 base::TimeDelta time_since_last_suggest_request =
637 base::TimeTicks::Now() - time_suggest_request_sent_;
638 return std::max(base::TimeDelta(), delay - time_since_last_suggest_request);
641 void SearchProvider::StartOrStopSuggestQuery(bool minimal_changes) {
642 bool query_is_private;
643 if (!IsQuerySuitableForSuggest(&query_is_private)) {
644 StopSuggest();
645 ClearAllResults();
646 return;
649 if (OmniboxFieldTrial::DisableResultsCaching())
650 ClearAllResults();
652 // For the minimal_changes case, if we finished the previous query and still
653 // have its results, or are allowed to keep running it, just do that, rather
654 // than starting a new query.
655 if (minimal_changes &&
656 (!default_results_.suggest_results.empty() ||
657 !default_results_.navigation_results.empty() ||
658 !keyword_results_.suggest_results.empty() ||
659 !keyword_results_.navigation_results.empty() ||
660 (!done_ && input_.want_asynchronous_matches())))
661 return;
663 // We can't keep running any previous query, so halt it.
664 StopSuggest();
666 UpdateAllOldResults(minimal_changes);
668 // Update the content classifications of remaining results so they look good
669 // against the current input.
670 UpdateMatchContentsClass(input_.text(), &default_results_);
671 if (!keyword_input_.text().empty())
672 UpdateMatchContentsClass(keyword_input_.text(), &keyword_results_);
674 // We can't start a new query if we're only allowed synchronous results.
675 if (!input_.want_asynchronous_matches())
676 return;
678 // Kick off a timer that will start the URL fetch if it completes before
679 // the user types another character. Requests may be delayed to avoid
680 // flooding the server with requests that are likely to be thrown away later
681 // anyway.
682 const base::TimeDelta delay = GetSuggestQueryDelay();
683 if (delay <= base::TimeDelta()) {
684 Run(query_is_private);
685 return;
687 timer_.Start(FROM_HERE,
688 delay,
689 base::Bind(&SearchProvider::Run,
690 base::Unretained(this),
691 query_is_private));
694 void SearchProvider::CancelFetcher(scoped_ptr<net::URLFetcher>* fetcher) {
695 if (*fetcher) {
696 LogOmniboxSuggestRequest(REQUEST_INVALIDATED);
697 fetcher->reset();
701 bool SearchProvider::IsQuerySuitableForSuggest(bool* query_is_private) const {
702 *query_is_private = IsQueryPotentionallyPrivate();
704 // Don't run Suggest in incognito mode, if the engine doesn't support it, or
705 // if the user has disabled it. Also don't send potentionally private data
706 // to the default search provider. (It's always okay to send explicit
707 // keyword input to a keyword suggest server, if any.)
708 const TemplateURL* default_url = providers_.GetDefaultProviderURL();
709 const TemplateURL* keyword_url = providers_.GetKeywordProviderURL();
710 return !client()->IsOffTheRecord() && client()->SearchSuggestEnabled() &&
711 ((default_url && !default_url->suggestions_url().empty() &&
712 !*query_is_private) ||
713 (keyword_url && !keyword_url->suggestions_url().empty()));
716 bool SearchProvider::IsQueryPotentionallyPrivate() const {
717 // If the input type might be a URL, we take extra care so that private data
718 // isn't sent to the server.
720 // FORCED_QUERY means the user is explicitly asking us to search for this, so
721 // we assume it isn't a URL and/or there isn't private data.
722 if (input_.type() == metrics::OmniboxInputType::FORCED_QUERY)
723 return false;
725 // Next we check the scheme. If this is UNKNOWN/URL with a scheme that isn't
726 // http/https/ftp, we shouldn't send it. Sending things like file: and data:
727 // is both a waste of time and a disclosure of potentially private, local
728 // data. Other "schemes" may actually be usernames, and we don't want to send
729 // passwords. If the scheme is OK, we still need to check other cases below.
730 // If this is QUERY, then the presence of these schemes means the user
731 // explicitly typed one, and thus this is probably a URL that's being entered
732 // and happens to currently be invalid -- in which case we again want to run
733 // our checks below. Other QUERY cases are less likely to be URLs and thus we
734 // assume we're OK.
735 if (!base::LowerCaseEqualsASCII(input_.scheme(), url::kHttpScheme) &&
736 !base::LowerCaseEqualsASCII(input_.scheme(), url::kHttpsScheme) &&
737 !base::LowerCaseEqualsASCII(input_.scheme(), url::kFtpScheme))
738 return (input_.type() != metrics::OmniboxInputType::QUERY);
740 // Don't send URLs with usernames, queries or refs. Some of these are
741 // private, and the Suggest server is unlikely to have any useful results
742 // for any of them. Also don't send URLs with ports, as we may initially
743 // think that a username + password is a host + port (and we don't want to
744 // send usernames/passwords), and even if the port really is a port, the
745 // server is once again unlikely to have and useful results.
746 // Note that we only block based on refs if the input is URL-typed, as search
747 // queries can legitimately have #s in them which the URL parser
748 // overaggressively categorizes as a url with a ref.
749 const url::Parsed& parts = input_.parts();
750 if (parts.username.is_nonempty() || parts.port.is_nonempty() ||
751 parts.query.is_nonempty() ||
752 (parts.ref.is_nonempty() &&
753 (input_.type() == metrics::OmniboxInputType::URL)))
754 return true;
756 // Don't send anything for https except the hostname. Hostnames are OK
757 // because they are visible when the TCP connection is established, but the
758 // specific path may reveal private information.
759 if (base::LowerCaseEqualsASCII(input_.scheme(), url::kHttpsScheme) &&
760 parts.path.is_nonempty())
761 return true;
763 return false;
766 void SearchProvider::UpdateAllOldResults(bool minimal_changes) {
767 if (keyword_input_.text().empty()) {
768 // User is either in keyword mode with a blank input or out of
769 // keyword mode entirely.
770 keyword_results_.Clear();
772 UpdateOldResults(minimal_changes, &default_results_);
773 UpdateOldResults(minimal_changes, &keyword_results_);
776 void SearchProvider::PersistTopSuggestions(
777 SearchSuggestionParser::Results* results) {
778 // Mark any results matching the current top results as having been received
779 // prior to the last keystroke. That prevents asynchronous updates from
780 // clobbering top results, which may be used for inline autocompletion.
781 // Other results don't need similar changes, because they shouldn't be
782 // displayed asynchronously anyway.
783 if (!top_query_suggestion_match_contents_.empty()) {
784 for (SearchSuggestionParser::SuggestResults::iterator sug_it =
785 results->suggest_results.begin();
786 sug_it != results->suggest_results.end(); ++sug_it) {
787 if (sug_it->match_contents() == top_query_suggestion_match_contents_)
788 sug_it->set_received_after_last_keystroke(false);
791 if (top_navigation_suggestion_.is_valid()) {
792 for (SearchSuggestionParser::NavigationResults::iterator nav_it =
793 results->navigation_results.begin();
794 nav_it != results->navigation_results.end(); ++nav_it) {
795 if (nav_it->url() == top_navigation_suggestion_)
796 nav_it->set_received_after_last_keystroke(false);
801 void SearchProvider::ApplyCalculatedSuggestRelevance(
802 SearchSuggestionParser::SuggestResults* list) {
803 for (size_t i = 0; i < list->size(); ++i) {
804 SearchSuggestionParser::SuggestResult& result = (*list)[i];
805 result.set_relevance(
806 result.CalculateRelevance(input_, providers_.has_keyword_provider()) +
807 (list->size() - i - 1));
808 result.set_relevance_from_server(false);
812 void SearchProvider::ApplyCalculatedNavigationRelevance(
813 SearchSuggestionParser::NavigationResults* list) {
814 for (size_t i = 0; i < list->size(); ++i) {
815 SearchSuggestionParser::NavigationResult& result = (*list)[i];
816 result.set_relevance(
817 result.CalculateRelevance(input_, providers_.has_keyword_provider()) +
818 (list->size() - i - 1));
819 result.set_relevance_from_server(false);
823 scoped_ptr<net::URLFetcher> SearchProvider::CreateSuggestFetcher(
824 int id,
825 const TemplateURL* template_url,
826 const AutocompleteInput& input) {
827 if (!template_url || template_url->suggestions_url().empty())
828 return NULL;
830 // Bail if the suggestion URL is invalid with the given replacements.
831 TemplateURLRef::SearchTermsArgs search_term_args(input.text());
832 search_term_args.input_type = input.type();
833 search_term_args.cursor_position = input.cursor_position();
834 search_term_args.page_classification = input.current_page_classification();
835 // Session token and prefetch data required for answers.
836 search_term_args.session_token = GetSessionToken();
837 if (!prefetch_data_.full_query_text.empty()) {
838 search_term_args.prefetch_query =
839 base::UTF16ToUTF8(prefetch_data_.full_query_text);
840 search_term_args.prefetch_query_type =
841 base::UTF16ToUTF8(prefetch_data_.query_type);
843 GURL suggest_url(template_url->suggestions_url_ref().ReplaceSearchTerms(
844 search_term_args,
845 client()->GetTemplateURLService()->search_terms_data()));
846 if (!suggest_url.is_valid())
847 return NULL;
849 // Send the current page URL if user setting and URL requirements are met and
850 // the user is in the field trial.
851 TemplateURLService* template_url_service = client()->GetTemplateURLService();
852 if (CanSendURL(input.current_url(), suggest_url, template_url,
853 input.current_page_classification(),
854 template_url_service->search_terms_data(), client()) &&
855 OmniboxFieldTrial::InZeroSuggestAfterTypingFieldTrial()) {
856 search_term_args.current_page_url = input.current_url().spec();
857 // Create the suggest URL again with the current page URL.
858 suggest_url = GURL(template_url->suggestions_url_ref().ReplaceSearchTerms(
859 search_term_args, template_url_service->search_terms_data()));
862 LogOmniboxSuggestRequest(REQUEST_SENT);
864 scoped_ptr<net::URLFetcher> fetcher =
865 net::URLFetcher::Create(id, suggest_url, net::URLFetcher::GET, this);
866 fetcher->SetRequestContext(client()->GetRequestContext());
867 fetcher->SetLoadFlags(net::LOAD_DO_NOT_SAVE_COOKIES);
868 // Add Chrome experiment state to the request headers.
869 net::HttpRequestHeaders headers;
870 variations::VariationsHttpHeaderProvider::GetInstance()->AppendHeaders(
871 fetcher->GetOriginalURL(), client()->IsOffTheRecord(), false, &headers);
872 fetcher->SetExtraRequestHeaders(headers.ToString());
873 fetcher->Start();
874 return fetcher;
877 void SearchProvider::ConvertResultsToAutocompleteMatches() {
878 // Convert all the results to matches and add them to a map, so we can keep
879 // the most relevant match for each result.
880 base::TimeTicks start_time(base::TimeTicks::Now());
881 MatchMap map;
882 const base::Time no_time;
883 int did_not_accept_keyword_suggestion =
884 keyword_results_.suggest_results.empty() ?
885 TemplateURLRef::NO_SUGGESTIONS_AVAILABLE :
886 TemplateURLRef::NO_SUGGESTION_CHOSEN;
888 bool relevance_from_server;
889 int verbatim_relevance = GetVerbatimRelevance(&relevance_from_server);
890 int did_not_accept_default_suggestion =
891 default_results_.suggest_results.empty() ?
892 TemplateURLRef::NO_SUGGESTIONS_AVAILABLE :
893 TemplateURLRef::NO_SUGGESTION_CHOSEN;
894 const TemplateURL* keyword_url = providers_.GetKeywordProviderURL();
895 if (verbatim_relevance > 0) {
896 const base::string16& trimmed_verbatim =
897 base::CollapseWhitespace(input_.text(), false);
899 // Verbatim results don't get suggestions and hence, answers.
900 // Scan previous matches if the last answer-bearing suggestion matches
901 // verbatim, and if so, copy over answer contents.
902 base::string16 answer_contents;
903 base::string16 answer_type;
904 scoped_ptr<SuggestionAnswer> answer;
905 for (ACMatches::iterator it = matches_.begin(); it != matches_.end();
906 ++it) {
907 if (it->answer && it->fill_into_edit == trimmed_verbatim) {
908 answer_contents = it->answer_contents;
909 answer_type = it->answer_type;
910 answer = SuggestionAnswer::copy(it->answer.get());
911 break;
915 SearchSuggestionParser::SuggestResult verbatim(
916 trimmed_verbatim, AutocompleteMatchType::SEARCH_WHAT_YOU_TYPED,
917 trimmed_verbatim, base::string16(), base::string16(), answer_contents,
918 answer_type, answer.Pass(), std::string(), std::string(), false,
919 verbatim_relevance, relevance_from_server, false, trimmed_verbatim);
920 AddMatchToMap(verbatim, std::string(), did_not_accept_default_suggestion,
921 false, keyword_url != NULL, &map);
923 if (!keyword_input_.text().empty()) {
924 // We only create the verbatim search query match for a keyword
925 // if it's not an extension keyword. Extension keywords are handled
926 // in KeywordProvider::Start(). (Extensions are complicated...)
927 // Note: in this provider, SEARCH_OTHER_ENGINE must correspond
928 // to the keyword verbatim search query. Do not create other matches
929 // of type SEARCH_OTHER_ENGINE.
930 if (keyword_url &&
931 (keyword_url->GetType() != TemplateURL::OMNIBOX_API_EXTENSION)) {
932 bool keyword_relevance_from_server;
933 const int keyword_verbatim_relevance =
934 GetKeywordVerbatimRelevance(&keyword_relevance_from_server);
935 if (keyword_verbatim_relevance > 0) {
936 const base::string16& trimmed_verbatim =
937 base::CollapseWhitespace(keyword_input_.text(), false);
938 SearchSuggestionParser::SuggestResult verbatim(
939 trimmed_verbatim, AutocompleteMatchType::SEARCH_OTHER_ENGINE,
940 trimmed_verbatim, base::string16(), base::string16(),
941 base::string16(), base::string16(), nullptr, std::string(),
942 std::string(), true, keyword_verbatim_relevance,
943 keyword_relevance_from_server, false, trimmed_verbatim);
944 AddMatchToMap(verbatim, std::string(),
945 did_not_accept_keyword_suggestion, false, true, &map);
949 AddRawHistoryResultsToMap(true, did_not_accept_keyword_suggestion, &map);
950 AddRawHistoryResultsToMap(false, did_not_accept_default_suggestion, &map);
952 AddSuggestResultsToMap(keyword_results_.suggest_results,
953 keyword_results_.metadata, &map);
954 AddSuggestResultsToMap(default_results_.suggest_results,
955 default_results_.metadata, &map);
957 ACMatches matches;
958 for (MatchMap::const_iterator i(map.begin()); i != map.end(); ++i)
959 matches.push_back(i->second);
961 AddNavigationResultsToMatches(keyword_results_.navigation_results, &matches);
962 AddNavigationResultsToMatches(default_results_.navigation_results, &matches);
964 // Now add the most relevant matches to |matches_|. We take up to kMaxMatches
965 // suggest/navsuggest matches, regardless of origin. We always include in
966 // that set a legal default match if possible. If Instant Extended is enabled
967 // and we have server-provided (and thus hopefully more accurate) scores for
968 // some suggestions, we allow more of those, until we reach
969 // AutocompleteResult::kMaxMatches total matches (that is, enough to fill the
970 // whole popup).
972 // We will always return any verbatim matches, no matter how we obtained their
973 // scores, unless we have already accepted AutocompleteResult::kMaxMatches
974 // higher-scoring matches under the conditions above.
975 std::sort(matches.begin(), matches.end(), &AutocompleteMatch::MoreRelevant);
977 // Guarantee that if there's a legal default match anywhere in the result
978 // set that it'll get returned. The rotate() call does this by moving the
979 // default match to the front of the list.
980 ACMatches::iterator default_match = FindTopMatch(&matches);
981 if (default_match != matches.end())
982 std::rotate(matches.begin(), default_match, default_match + 1);
984 // It's possible to get a copy of an answer from previous matches and get the
985 // same or a different answer to another server-provided suggestion. In the
986 // future we may decide that we want to have answers attached to multiple
987 // suggestions, but the current assumption is that there should only ever be
988 // one suggestion with an answer. To maintain this assumption, remove any
989 // answers after the first.
990 RemoveExtraAnswers(&matches);
992 matches_.clear();
993 size_t num_suggestions = 0;
994 for (ACMatches::const_iterator i(matches.begin());
995 (i != matches.end()) &&
996 (matches_.size() < AutocompleteResult::kMaxMatches);
997 ++i) {
998 // SEARCH_OTHER_ENGINE is only used in the SearchProvider for the keyword
999 // verbatim result, so this condition basically means "if this match is a
1000 // suggestion of some sort".
1001 if ((i->type != AutocompleteMatchType::SEARCH_WHAT_YOU_TYPED) &&
1002 (i->type != AutocompleteMatchType::SEARCH_OTHER_ENGINE)) {
1003 // If we've already hit the limit on non-server-scored suggestions, and
1004 // this isn't a server-scored suggestion we can add, skip it.
1005 if ((num_suggestions >= kMaxMatches) &&
1006 (!search::IsInstantExtendedAPIEnabled() ||
1007 (i->GetAdditionalInfo(kRelevanceFromServerKey) != kTrue))) {
1008 continue;
1011 ++num_suggestions;
1014 matches_.push_back(*i);
1016 UMA_HISTOGRAM_TIMES("Omnibox.SearchProvider.ConvertResultsTime",
1017 base::TimeTicks::Now() - start_time);
1020 void SearchProvider::RemoveExtraAnswers(ACMatches* matches) {
1021 bool answer_seen = false;
1022 for (ACMatches::iterator it = matches->begin(); it != matches->end(); ++it) {
1023 if (it->answer) {
1024 if (!answer_seen) {
1025 answer_seen = true;
1026 } else {
1027 it->answer_contents.clear();
1028 it->answer_type.clear();
1029 it->answer.reset();
1035 ACMatches::const_iterator SearchProvider::FindTopMatch() const {
1036 ACMatches::const_iterator it = matches_.begin();
1037 while ((it != matches_.end()) && !it->allowed_to_be_default_match)
1038 ++it;
1039 return it;
1042 bool SearchProvider::IsTopMatchSearchWithURLInput() const {
1043 ACMatches::const_iterator first_match = FindTopMatch();
1044 return (input_.type() == metrics::OmniboxInputType::URL) &&
1045 (first_match != matches_.end()) &&
1046 (first_match->relevance > CalculateRelevanceForVerbatim()) &&
1047 (first_match->type != AutocompleteMatchType::NAVSUGGEST) &&
1048 (first_match->type != AutocompleteMatchType::NAVSUGGEST_PERSONALIZED);
1051 void SearchProvider::AddNavigationResultsToMatches(
1052 const SearchSuggestionParser::NavigationResults& navigation_results,
1053 ACMatches* matches) {
1054 for (SearchSuggestionParser::NavigationResults::const_iterator it =
1055 navigation_results.begin(); it != navigation_results.end(); ++it) {
1056 matches->push_back(NavigationToMatch(*it));
1057 // In the absence of suggested relevance scores, use only the single
1058 // highest-scoring result. (The results are already sorted by relevance.)
1059 if (!it->relevance_from_server())
1060 return;
1064 void SearchProvider::AddRawHistoryResultsToMap(bool is_keyword,
1065 int did_not_accept_suggestion,
1066 MatchMap* map) {
1067 base::TimeTicks start_time(base::TimeTicks::Now());
1069 const SearchSuggestionParser::SuggestResults* transformed_results =
1070 is_keyword ? &transformed_keyword_history_results_
1071 : &transformed_default_history_results_;
1072 DCHECK(transformed_results);
1073 AddTransformedHistoryResultsToMap(
1074 *transformed_results, did_not_accept_suggestion, map);
1075 UMA_HISTOGRAM_TIMES("Omnibox.SearchProvider.AddHistoryResultsTime",
1076 base::TimeTicks::Now() - start_time);
1079 void SearchProvider::AddTransformedHistoryResultsToMap(
1080 const SearchSuggestionParser::SuggestResults& transformed_results,
1081 int did_not_accept_suggestion,
1082 MatchMap* map) {
1083 for (SearchSuggestionParser::SuggestResults::const_iterator i(
1084 transformed_results.begin());
1085 i != transformed_results.end();
1086 ++i) {
1087 AddMatchToMap(*i, std::string(), did_not_accept_suggestion, true,
1088 providers_.GetKeywordProviderURL() != NULL, map);
1092 SearchSuggestionParser::SuggestResults
1093 SearchProvider::ScoreHistoryResultsHelper(const HistoryResults& results,
1094 bool base_prevent_inline_autocomplete,
1095 bool input_multiple_words,
1096 const base::string16& input_text,
1097 bool is_keyword) {
1098 SearchSuggestionParser::SuggestResults scored_results;
1099 // True if the user has asked this exact query previously.
1100 bool found_what_you_typed_match = false;
1101 const bool prevent_search_history_inlining =
1102 OmniboxFieldTrial::SearchHistoryPreventInlining(
1103 input_.current_page_classification());
1104 const base::string16& trimmed_input =
1105 base::CollapseWhitespace(input_text, false);
1106 for (HistoryResults::const_iterator i(results.begin()); i != results.end();
1107 ++i) {
1108 const base::string16& trimmed_suggestion =
1109 base::CollapseWhitespace(i->term, false);
1111 // Don't autocomplete multi-word queries that have only been seen once
1112 // unless the user has typed more than one word.
1113 bool prevent_inline_autocomplete = base_prevent_inline_autocomplete ||
1114 (!input_multiple_words && (i->visits < 2) &&
1115 HasMultipleWords(trimmed_suggestion));
1117 int relevance = CalculateRelevanceForHistory(
1118 i->time, is_keyword, !prevent_inline_autocomplete,
1119 prevent_search_history_inlining);
1120 // Add the match to |scored_results| by putting the what-you-typed match
1121 // on the front and appending all other matches. We want the what-you-
1122 // typed match to always be first.
1123 SearchSuggestionParser::SuggestResults::iterator insertion_position =
1124 scored_results.end();
1125 if (trimmed_suggestion == trimmed_input) {
1126 found_what_you_typed_match = true;
1127 insertion_position = scored_results.begin();
1129 SearchSuggestionParser::SuggestResult history_suggestion(
1130 trimmed_suggestion, AutocompleteMatchType::SEARCH_HISTORY,
1131 trimmed_suggestion, base::string16(), base::string16(),
1132 base::string16(), base::string16(), nullptr, std::string(),
1133 std::string(), is_keyword, relevance, false, false, trimmed_input);
1134 // History results are synchronous; they are received on the last keystroke.
1135 history_suggestion.set_received_after_last_keystroke(false);
1136 scored_results.insert(insertion_position, history_suggestion);
1139 // History returns results sorted for us. However, we may have docked some
1140 // results' scores, so things are no longer in order. While keeping the
1141 // what-you-typed match at the front (if it exists), do a stable sort to get
1142 // things back in order without otherwise disturbing results with equal
1143 // scores, then force the scores to be unique, so that the order in which
1144 // they're shown is deterministic.
1145 std::stable_sort(scored_results.begin() +
1146 (found_what_you_typed_match ? 1 : 0),
1147 scored_results.end(),
1148 CompareScoredResults());
1150 // Don't autocomplete to search terms that would normally be treated as URLs
1151 // when typed. For example, if the user searched for "google.com" and types
1152 // "goog", don't autocomplete to the search term "google.com". Otherwise,
1153 // the input will look like a URL but act like a search, which is confusing.
1154 // The 1200 relevance score threshold in the test below is the lowest
1155 // possible score in CalculateRelevanceForHistory()'s aggressive-scoring
1156 // curve. This is an appropriate threshold to use to decide if we're overly
1157 // aggressively inlining because, if we decide the answer is yes, the
1158 // way we resolve it it to not use the aggressive-scoring curve.
1159 // NOTE: We don't check for autocompleting to URLs in the following cases:
1160 // * When inline autocomplete is disabled, we won't be inline autocompleting
1161 // this term, so we don't need to worry about confusion as much. This
1162 // also prevents calling Classify() again from inside the classifier
1163 // (which will corrupt state and likely crash), since the classifier
1164 // always disables inline autocomplete.
1165 // * When the user has typed the whole string before as a query, then it's
1166 // likely the user has no expectation that term should be interpreted as
1167 // as a URL, so we need not do anything special to preserve user
1168 // expectation.
1169 int last_relevance = 0;
1170 if (!base_prevent_inline_autocomplete && !found_what_you_typed_match &&
1171 scored_results.front().relevance() >= 1200) {
1172 AutocompleteMatch match;
1173 client()->Classify(scored_results.front().suggestion(), false, false,
1174 input_.current_page_classification(), &match, NULL);
1175 // Demote this match that would normally be interpreted as a URL to have
1176 // the highest score a previously-issued search query could have when
1177 // scoring with the non-aggressive method. A consequence of demoting
1178 // by revising |last_relevance| is that this match and all following
1179 // matches get demoted; the relative order of matches is preserved.
1180 // One could imagine demoting only those matches that might cause
1181 // confusion (which, by the way, might change the relative order of
1182 // matches. We have decided to go with the simple demote-all approach
1183 // because selective demotion requires multiple Classify() calls and
1184 // such calls can be expensive (as expensive as running the whole
1185 // autocomplete system).
1186 if (!AutocompleteMatch::IsSearchType(match.type)) {
1187 last_relevance = CalculateRelevanceForHistory(
1188 base::Time::Now(), is_keyword, false,
1189 prevent_search_history_inlining);
1193 for (SearchSuggestionParser::SuggestResults::iterator i(
1194 scored_results.begin()); i != scored_results.end(); ++i) {
1195 if ((last_relevance != 0) && (i->relevance() >= last_relevance))
1196 i->set_relevance(last_relevance - 1);
1197 last_relevance = i->relevance();
1200 return scored_results;
1203 void SearchProvider::ScoreHistoryResults(
1204 const HistoryResults& results,
1205 bool is_keyword,
1206 SearchSuggestionParser::SuggestResults* scored_results) {
1207 DCHECK(scored_results);
1208 scored_results->clear();
1210 if (results.empty()) {
1211 return;
1214 bool prevent_inline_autocomplete = input_.prevent_inline_autocomplete() ||
1215 (input_.type() == metrics::OmniboxInputType::URL);
1216 const base::string16 input_text = GetInput(is_keyword).text();
1217 bool input_multiple_words = HasMultipleWords(input_text);
1219 if (!prevent_inline_autocomplete && input_multiple_words) {
1220 // ScoreHistoryResultsHelper() allows autocompletion of multi-word, 1-visit
1221 // queries if the input also has multiple words. But if we were already
1222 // scoring a multi-word, multi-visit query aggressively, and the current
1223 // input is still a prefix of it, then changing the suggestion suddenly
1224 // feels wrong. To detect this case, first score as if only one word has
1225 // been typed, then check if the best result came from aggressive search
1226 // history scoring. If it did, then just keep that score set. This
1227 // 1200 the lowest possible score in CalculateRelevanceForHistory()'s
1228 // aggressive-scoring curve.
1229 *scored_results = ScoreHistoryResultsHelper(
1230 results, prevent_inline_autocomplete, false, input_text, is_keyword);
1231 if ((scored_results->front().relevance() < 1200) ||
1232 !HasMultipleWords(scored_results->front().suggestion()))
1233 scored_results->clear(); // Didn't detect the case above, score normally.
1235 if (scored_results->empty()) {
1236 *scored_results = ScoreHistoryResultsHelper(results,
1237 prevent_inline_autocomplete,
1238 input_multiple_words,
1239 input_text,
1240 is_keyword);
1244 void SearchProvider::AddSuggestResultsToMap(
1245 const SearchSuggestionParser::SuggestResults& results,
1246 const std::string& metadata,
1247 MatchMap* map) {
1248 for (size_t i = 0; i < results.size(); ++i) {
1249 AddMatchToMap(results[i], metadata, i, false,
1250 providers_.GetKeywordProviderURL() != NULL, map);
1254 int SearchProvider::GetVerbatimRelevance(bool* relevance_from_server) const {
1255 // Use the suggested verbatim relevance score if it is non-negative (valid),
1256 // if inline autocomplete isn't prevented (always show verbatim on backspace),
1257 // and if it won't suppress verbatim, leaving no default provider matches.
1258 // Otherwise, if the default provider returned no matches and was still able
1259 // to suppress verbatim, the user would have no search/nav matches and may be
1260 // left unable to search using their default provider from the omnibox.
1261 // Check for results on each verbatim calculation, as results from older
1262 // queries (on previous input) may be trimmed for failing to inline new input.
1263 bool use_server_relevance =
1264 (default_results_.verbatim_relevance >= 0) &&
1265 !input_.prevent_inline_autocomplete() &&
1266 ((default_results_.verbatim_relevance > 0) ||
1267 !default_results_.suggest_results.empty() ||
1268 !default_results_.navigation_results.empty());
1269 if (relevance_from_server)
1270 *relevance_from_server = use_server_relevance;
1271 return use_server_relevance ?
1272 default_results_.verbatim_relevance : CalculateRelevanceForVerbatim();
1275 int SearchProvider::CalculateRelevanceForVerbatim() const {
1276 if (!providers_.keyword_provider().empty())
1277 return 250;
1278 return CalculateRelevanceForVerbatimIgnoringKeywordModeState();
1281 int SearchProvider::
1282 CalculateRelevanceForVerbatimIgnoringKeywordModeState() const {
1283 switch (input_.type()) {
1284 case metrics::OmniboxInputType::UNKNOWN:
1285 case metrics::OmniboxInputType::QUERY:
1286 case metrics::OmniboxInputType::FORCED_QUERY:
1287 return kNonURLVerbatimRelevance;
1289 case metrics::OmniboxInputType::URL:
1290 return 850;
1292 default:
1293 NOTREACHED();
1294 return 0;
1298 int SearchProvider::GetKeywordVerbatimRelevance(
1299 bool* relevance_from_server) const {
1300 // Use the suggested verbatim relevance score if it is non-negative (valid),
1301 // if inline autocomplete isn't prevented (always show verbatim on backspace),
1302 // and if it won't suppress verbatim, leaving no keyword provider matches.
1303 // Otherwise, if the keyword provider returned no matches and was still able
1304 // to suppress verbatim, the user would have no search/nav matches and may be
1305 // left unable to search using their keyword provider from the omnibox.
1306 // Check for results on each verbatim calculation, as results from older
1307 // queries (on previous input) may be trimmed for failing to inline new input.
1308 bool use_server_relevance =
1309 (keyword_results_.verbatim_relevance >= 0) &&
1310 !input_.prevent_inline_autocomplete() &&
1311 ((keyword_results_.verbatim_relevance > 0) ||
1312 !keyword_results_.suggest_results.empty() ||
1313 !keyword_results_.navigation_results.empty());
1314 if (relevance_from_server)
1315 *relevance_from_server = use_server_relevance;
1316 return use_server_relevance ?
1317 keyword_results_.verbatim_relevance :
1318 CalculateRelevanceForKeywordVerbatim(keyword_input_.type(),
1319 keyword_input_.prefer_keyword());
1322 int SearchProvider::CalculateRelevanceForHistory(
1323 const base::Time& time,
1324 bool is_keyword,
1325 bool use_aggressive_method,
1326 bool prevent_search_history_inlining) const {
1327 // The relevance of past searches falls off over time. There are two distinct
1328 // equations used. If the first equation is used (searches to the primary
1329 // provider that we want to score aggressively), the score is in the range
1330 // 1300-1599 (unless |prevent_search_history_inlining|, in which case
1331 // it's in the range 1200-1299). If the second equation is used the
1332 // relevance of a search 15 minutes ago is discounted 50 points, while the
1333 // relevance of a search two weeks ago is discounted 450 points.
1334 double elapsed_time = std::max((base::Time::Now() - time).InSecondsF(), 0.0);
1335 bool is_primary_provider = is_keyword || !providers_.has_keyword_provider();
1336 if (is_primary_provider && use_aggressive_method) {
1337 // Searches with the past two days get a different curve.
1338 const double autocomplete_time = 2 * 24 * 60 * 60;
1339 if (elapsed_time < autocomplete_time) {
1340 int max_score = is_keyword ? 1599 : 1399;
1341 if (prevent_search_history_inlining)
1342 max_score = 1299;
1343 return max_score - static_cast<int>(99 *
1344 std::pow(elapsed_time / autocomplete_time, 2.5));
1346 elapsed_time -= autocomplete_time;
1349 const int score_discount =
1350 static_cast<int>(6.5 * std::pow(elapsed_time, 0.3));
1352 // Don't let scores go below 0. Negative relevance scores are meaningful in
1353 // a different way.
1354 int base_score;
1355 if (is_primary_provider)
1356 base_score = (input_.type() == metrics::OmniboxInputType::URL) ? 750 : 1050;
1357 else
1358 base_score = 200;
1359 return std::max(0, base_score - score_discount);
1362 AutocompleteMatch SearchProvider::NavigationToMatch(
1363 const SearchSuggestionParser::NavigationResult& navigation) {
1364 base::string16 input;
1365 const bool trimmed_whitespace = base::TrimWhitespace(
1366 navigation.from_keyword_provider() ?
1367 keyword_input_.text() : input_.text(),
1368 base::TRIM_TRAILING, &input) != base::TRIM_NONE;
1369 AutocompleteMatch match(this, navigation.relevance(), false,
1370 navigation.type());
1371 match.destination_url = navigation.url();
1372 BaseSearchProvider::SetDeletionURL(navigation.deletion_url(), &match);
1373 // First look for the user's input inside the formatted url as it would be
1374 // without trimming the scheme, so we can find matches at the beginning of the
1375 // scheme.
1376 const URLPrefix* prefix =
1377 URLPrefix::BestURLPrefix(navigation.formatted_url(), input);
1378 size_t match_start = (prefix == NULL) ?
1379 navigation.formatted_url().find(input) : prefix->prefix.length();
1380 bool trim_http = !AutocompleteInput::HasHTTPScheme(input) &&
1381 (!prefix || (match_start != 0));
1382 const url_formatter::FormatUrlTypes format_types =
1383 url_formatter::kFormatUrlOmitAll &
1384 ~(trim_http ? 0 : url_formatter::kFormatUrlOmitHTTP);
1386 const std::string languages(client()->GetAcceptLanguages());
1387 size_t inline_autocomplete_offset = (prefix == NULL) ?
1388 base::string16::npos : (match_start + input.length());
1389 match.fill_into_edit +=
1390 AutocompleteInput::FormattedStringWithEquivalentMeaning(
1391 navigation.url(),
1392 url_formatter::FormatUrl(navigation.url(), languages, format_types,
1393 net::UnescapeRule::SPACES, nullptr, nullptr,
1394 &inline_autocomplete_offset),
1395 client()->GetSchemeClassifier());
1396 // Preserve the forced query '?' prefix in |match.fill_into_edit|.
1397 // Otherwise, user edits to a suggestion would show non-Search results.
1398 if (input_.type() == metrics::OmniboxInputType::FORCED_QUERY) {
1399 match.fill_into_edit.insert(0, base::ASCIIToUTF16("?"));
1400 if (inline_autocomplete_offset != base::string16::npos)
1401 ++inline_autocomplete_offset;
1403 if (inline_autocomplete_offset != base::string16::npos) {
1404 DCHECK(inline_autocomplete_offset <= match.fill_into_edit.length());
1405 match.inline_autocompletion =
1406 match.fill_into_edit.substr(inline_autocomplete_offset);
1408 // An inlineable navsuggestion can only be the default match when there
1409 // is no keyword provider active, lest it appear first and break the user
1410 // out of keyword mode. We also must have received the navsuggestion before
1411 // the last keystroke, to prevent asynchronous inline autocompletions changes.
1412 // The navsuggestion can also only be default if either the inline
1413 // autocompletion is empty or we're not preventing inline autocompletion.
1414 // Finally, if we have an inlineable navsuggestion with an inline completion
1415 // that we're not preventing, make sure we didn't trim any whitespace.
1416 // We don't want to claim http://foo.com/bar is inlineable against the
1417 // input "foo.com/b ".
1418 match.allowed_to_be_default_match =
1419 (prefix != NULL) &&
1420 (providers_.GetKeywordProviderURL() == NULL) &&
1421 !navigation.received_after_last_keystroke() &&
1422 (match.inline_autocompletion.empty() ||
1423 (!input_.prevent_inline_autocomplete() && !trimmed_whitespace));
1424 match.EnsureUWYTIsAllowedToBeDefault(input_, client()->GetAcceptLanguages(),
1425 client()->GetTemplateURLService());
1427 match.contents = navigation.match_contents();
1428 match.contents_class = navigation.match_contents_class();
1429 match.description = navigation.description();
1430 AutocompleteMatch::ClassifyMatchInString(input, match.description,
1431 ACMatchClassification::NONE, &match.description_class);
1433 match.RecordAdditionalInfo(
1434 kRelevanceFromServerKey,
1435 navigation.relevance_from_server() ? kTrue : kFalse);
1436 match.RecordAdditionalInfo(kShouldPrefetchKey, kFalse);
1438 return match;
1441 void SearchProvider::UpdateDone() {
1442 // We're done when the timer isn't running and there are no suggest queries
1443 // pending.
1444 done_ = !timer_.IsRunning() && !default_fetcher_ && !keyword_fetcher_;
1447 std::string SearchProvider::GetSessionToken() {
1448 base::TimeTicks current_time(base::TimeTicks::Now());
1449 // Renew token if it expired.
1450 if (current_time > token_expiration_time_) {
1451 const size_t kTokenBytes = 12;
1452 std::string raw_data;
1453 base::RandBytes(base::WriteInto(&raw_data, kTokenBytes + 1), kTokenBytes);
1454 base::Base64Encode(raw_data, &current_token_);
1456 // Make the base64 encoded value URL and filename safe(see RFC 3548).
1457 std::replace(current_token_.begin(), current_token_.end(), '+', '-');
1458 std::replace(current_token_.begin(), current_token_.end(), '/', '_');
1461 // Extend expiration time another 60 seconds.
1462 token_expiration_time_ = current_time + base::TimeDelta::FromSeconds(60);
1464 return current_token_;
1467 void SearchProvider::RegisterDisplayedAnswers(
1468 const AutocompleteResult& result) {
1469 if (result.empty())
1470 return;
1472 // The answer must be in the first or second slot to be considered. It should
1473 // only be in the second slot if AutocompleteController ranked a local search
1474 // history or a verbatim item higher than the answer.
1475 AutocompleteResult::const_iterator match = result.begin();
1476 if (match->answer_contents.empty() && result.size() > 1)
1477 ++match;
1478 if (match->answer_contents.empty() || match->answer_type.empty() ||
1479 match->fill_into_edit.empty())
1480 return;
1482 // Valid answer encountered, cache it for further queries.
1483 answers_cache_.UpdateRecentAnswers(match->fill_into_edit, match->answer_type);
1486 AnswersQueryData SearchProvider::FindAnswersPrefetchData() {
1487 // Retrieve the top entry from scored history results.
1488 MatchMap map;
1489 AddTransformedHistoryResultsToMap(transformed_keyword_history_results_,
1490 TemplateURLRef::NO_SUGGESTIONS_AVAILABLE,
1491 &map);
1492 AddTransformedHistoryResultsToMap(transformed_default_history_results_,
1493 TemplateURLRef::NO_SUGGESTIONS_AVAILABLE,
1494 &map);
1496 ACMatches matches;
1497 for (MatchMap::const_iterator i(map.begin()); i != map.end(); ++i)
1498 matches.push_back(i->second);
1499 std::sort(matches.begin(), matches.end(), &AutocompleteMatch::MoreRelevant);
1501 // If there is a top scoring entry, find the corresponding answer.
1502 if (!matches.empty())
1503 return answers_cache_.GetTopAnswerEntry(matches[0].contents);
1505 return AnswersQueryData();