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