Omnibox: Send Input Type to Suggest Server
[chromium-blink-merge.git] / chrome / browser / autocomplete / search_provider.cc
blob164d730a518a4e5193bf08821dabfc01a834ffe8
1 // Copyright 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "chrome/browser/autocomplete/search_provider.h"
7 #include <algorithm>
8 #include <cmath>
10 #include "base/base64.h"
11 #include "base/callback.h"
12 #include "base/command_line.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/message_loop/message_loop.h"
17 #include "base/metrics/histogram.h"
18 #include "base/prefs/pref_service.h"
19 #include "base/rand_util.h"
20 #include "base/strings/string_util.h"
21 #include "base/strings/utf_string_conversions.h"
22 #include "chrome/browser/autocomplete/autocomplete_classifier.h"
23 #include "chrome/browser/autocomplete/autocomplete_classifier_factory.h"
24 #include "chrome/browser/autocomplete/autocomplete_provider_listener.h"
25 #include "chrome/browser/autocomplete/autocomplete_result.h"
26 #include "chrome/browser/autocomplete/keyword_provider.h"
27 #include "chrome/browser/autocomplete/url_prefix.h"
28 #include "chrome/browser/google/google_util.h"
29 #include "chrome/browser/history/history_service.h"
30 #include "chrome/browser/history/history_service_factory.h"
31 #include "chrome/browser/history/in_memory_database.h"
32 #include "chrome/browser/metrics/variations/variations_http_header_provider.h"
33 #include "chrome/browser/omnibox/omnibox_field_trial.h"
34 #include "chrome/browser/profiles/profile.h"
35 #include "chrome/browser/search/search.h"
36 #include "chrome/browser/search_engines/template_url_prepopulate_data.h"
37 #include "chrome/browser/search_engines/template_url_service.h"
38 #include "chrome/browser/search_engines/template_url_service_factory.h"
39 #include "chrome/browser/ui/search/instant_controller.h"
40 #include "chrome/common/chrome_switches.h"
41 #include "chrome/common/pref_names.h"
42 #include "components/metrics/proto/omnibox_input_type.pb.h"
43 #include "content/public/browser/user_metrics.h"
44 #include "grit/generated_resources.h"
45 #include "net/base/escape.h"
46 #include "net/base/load_flags.h"
47 #include "net/base/net_util.h"
48 #include "net/http/http_request_headers.h"
49 #include "net/url_request/url_fetcher.h"
50 #include "net/url_request/url_request_status.h"
51 #include "ui/base/l10n/l10n_util.h"
52 #include "url/url_constants.h"
53 #include "url/url_util.h"
55 // Helpers --------------------------------------------------------------------
57 namespace {
59 // We keep track in a histogram how many suggest requests we send, how
60 // many suggest requests we invalidate (e.g., due to a user typing
61 // another character), and how many replies we receive.
62 // *** ADD NEW ENUMS AFTER ALL PREVIOUSLY DEFINED ONES! ***
63 // (excluding the end-of-list enum value)
64 // We do not want values of existing enums to change or else it screws
65 // up the statistics.
66 enum SuggestRequestsHistogramValue {
67 REQUEST_SENT = 1,
68 REQUEST_INVALIDATED,
69 REPLY_RECEIVED,
70 MAX_SUGGEST_REQUEST_HISTOGRAM_VALUE
73 // The verbatim score for an input which is not an URL.
74 const int kNonURLVerbatimRelevance = 1300;
76 // Increments the appropriate value in the histogram by one.
77 void LogOmniboxSuggestRequest(
78 SuggestRequestsHistogramValue request_value) {
79 UMA_HISTOGRAM_ENUMERATION("Omnibox.SuggestRequests", request_value,
80 MAX_SUGGEST_REQUEST_HISTOGRAM_VALUE);
83 bool HasMultipleWords(const base::string16& text) {
84 base::i18n::BreakIterator i(text, base::i18n::BreakIterator::BREAK_WORD);
85 bool found_word = false;
86 if (i.Init()) {
87 while (i.Advance()) {
88 if (i.IsWord()) {
89 if (found_word)
90 return true;
91 found_word = true;
95 return false;
98 } // namespace
100 // SearchProvider::Providers --------------------------------------------------
102 SearchProvider::Providers::Providers(TemplateURLService* template_url_service)
103 : template_url_service_(template_url_service) {}
105 const TemplateURL* SearchProvider::Providers::GetDefaultProviderURL() const {
106 return default_provider_.empty() ? NULL :
107 template_url_service_->GetTemplateURLForKeyword(default_provider_);
110 const TemplateURL* SearchProvider::Providers::GetKeywordProviderURL() const {
111 return keyword_provider_.empty() ? NULL :
112 template_url_service_->GetTemplateURLForKeyword(keyword_provider_);
116 // SearchProvider::CompareScoredResults ---------------------------------------
118 class SearchProvider::CompareScoredResults {
119 public:
120 bool operator()(const Result& a, const Result& b) {
121 // Sort in descending relevance order.
122 return a.relevance() > b.relevance();
127 // SearchProvider -------------------------------------------------------------
129 // static
130 int SearchProvider::kMinimumTimeBetweenSuggestQueriesMs = 100;
132 SearchProvider::SearchProvider(AutocompleteProviderListener* listener,
133 Profile* profile)
134 : BaseSearchProvider(listener, profile, AutocompleteProvider::TYPE_SEARCH),
135 providers_(TemplateURLServiceFactory::GetForProfile(profile)) {
138 // static
139 std::string SearchProvider::GetSuggestMetadata(const AutocompleteMatch& match) {
140 return match.GetAdditionalInfo(kSuggestMetadataKey);
143 void SearchProvider::ResetSession() {
144 field_trial_triggered_in_session_ = false;
147 SearchProvider::~SearchProvider() {
150 void SearchProvider::UpdateMatchContentsClass(const base::string16& input_text,
151 Results* results) {
152 for (SuggestResults::iterator sug_it = results->suggest_results.begin();
153 sug_it != results->suggest_results.end(); ++sug_it) {
154 sug_it->ClassifyMatchContents(false, input_text);
156 const std::string languages(
157 profile_->GetPrefs()->GetString(prefs::kAcceptLanguages));
158 for (NavigationResults::iterator nav_it = results->navigation_results.begin();
159 nav_it != results->navigation_results.end(); ++nav_it) {
160 nav_it->CalculateAndClassifyMatchContents(false, input_text, languages);
164 // static
165 int SearchProvider::CalculateRelevanceForKeywordVerbatim(
166 AutocompleteInput::Type type,
167 bool prefer_keyword) {
168 // This function is responsible for scoring verbatim query matches
169 // for non-extension keywords. KeywordProvider::CalculateRelevance()
170 // scores verbatim query matches for extension keywords, as well as
171 // for keyword matches (i.e., suggestions of a keyword itself, not a
172 // suggestion of a query on a keyword search engine). These two
173 // functions are currently in sync, but there's no reason we
174 // couldn't decide in the future to score verbatim matches
175 // differently for extension and non-extension keywords. If you
176 // make such a change, however, you should update this comment to
177 // describe it, so it's clear why the functions diverge.
178 if (prefer_keyword)
179 return 1500;
180 return (type == metrics::OmniboxInputType::QUERY) ? 1450 : 1100;
183 void SearchProvider::Start(const AutocompleteInput& input,
184 bool minimal_changes) {
185 // Do our best to load the model as early as possible. This will reduce
186 // odds of having the model not ready when really needed (a non-empty input).
187 TemplateURLService* model = providers_.template_url_service();
188 DCHECK(model);
189 model->Load();
191 matches_.clear();
192 field_trial_triggered_ = false;
194 // Can't return search/suggest results for bogus input or without a profile.
195 if (!profile_ || (input.type() == metrics::OmniboxInputType::INVALID)) {
196 Stop(true);
197 return;
200 keyword_input_ = input;
201 const TemplateURL* keyword_provider =
202 KeywordProvider::GetSubstitutingTemplateURLForInput(model,
203 &keyword_input_);
204 if (keyword_provider == NULL)
205 keyword_input_.Clear();
206 else if (keyword_input_.text().empty())
207 keyword_provider = NULL;
209 const TemplateURL* default_provider = model->GetDefaultSearchProvider();
210 if (default_provider && !default_provider->SupportsReplacement())
211 default_provider = NULL;
213 if (keyword_provider == default_provider)
214 default_provider = NULL; // No use in querying the same provider twice.
216 if (!default_provider && !keyword_provider) {
217 // No valid providers.
218 Stop(true);
219 return;
222 // If we're still running an old query but have since changed the query text
223 // or the providers, abort the query.
224 base::string16 default_provider_keyword(default_provider ?
225 default_provider->keyword() : base::string16());
226 base::string16 keyword_provider_keyword(keyword_provider ?
227 keyword_provider->keyword() : base::string16());
228 if (!minimal_changes ||
229 !providers_.equal(default_provider_keyword, keyword_provider_keyword)) {
230 // Cancel any in-flight suggest requests.
231 if (!done_)
232 Stop(false);
235 providers_.set(default_provider_keyword, keyword_provider_keyword);
237 if (input.text().empty()) {
238 // User typed "?" alone. Give them a placeholder result indicating what
239 // this syntax does.
240 if (default_provider) {
241 AutocompleteMatch match;
242 match.provider = this;
243 match.contents.assign(l10n_util::GetStringUTF16(IDS_EMPTY_KEYWORD_VALUE));
244 match.contents_class.push_back(
245 ACMatchClassification(0, ACMatchClassification::NONE));
246 match.keyword = providers_.default_provider();
247 match.allowed_to_be_default_match = true;
248 matches_.push_back(match);
250 Stop(true);
251 return;
254 input_ = input;
256 DoHistoryQuery(minimal_changes);
257 StartOrStopSuggestQuery(minimal_changes);
258 UpdateMatches();
261 void SearchProvider::SortResults(bool is_keyword,
262 const base::ListValue* relevances,
263 Results* results) {
264 // Ignore suggested scores for non-keyword matches in keyword mode; if the
265 // server is allowed to score these, it could interfere with the user's
266 // ability to get good keyword results.
267 const bool abandon_suggested_scores =
268 !is_keyword && !providers_.keyword_provider().empty();
269 // Apply calculated relevance scores to suggestions if a valid list was
270 // not provided or we're abandoning suggested scores entirely.
271 if ((relevances == NULL) || abandon_suggested_scores) {
272 ApplyCalculatedSuggestRelevance(&results->suggest_results);
273 ApplyCalculatedNavigationRelevance(&results->navigation_results);
274 // If abandoning scores entirely, also abandon the verbatim score.
275 if (abandon_suggested_scores)
276 results->verbatim_relevance = -1;
279 // Keep the result lists sorted.
280 const CompareScoredResults comparator = CompareScoredResults();
281 std::stable_sort(results->suggest_results.begin(),
282 results->suggest_results.end(),
283 comparator);
284 std::stable_sort(results->navigation_results.begin(),
285 results->navigation_results.end(),
286 comparator);
289 const TemplateURL* SearchProvider::GetTemplateURL(bool is_keyword) const {
290 return is_keyword ? providers_.GetKeywordProviderURL()
291 : providers_.GetDefaultProviderURL();
294 const AutocompleteInput SearchProvider::GetInput(bool is_keyword) const {
295 return is_keyword ? keyword_input_ : input_;
298 BaseSearchProvider::Results* SearchProvider::GetResultsToFill(bool is_keyword) {
299 return is_keyword ? &keyword_results_ : &default_results_;
302 bool SearchProvider::ShouldAppendExtraParams(
303 const SuggestResult& result) const {
304 return !result.from_keyword_provider() ||
305 providers_.default_provider().empty();
308 void SearchProvider::StopSuggest() {
309 // Increment the appropriate field in the histogram by the number of
310 // pending requests that were invalidated.
311 for (int i = 0; i < suggest_results_pending_; ++i)
312 LogOmniboxSuggestRequest(REQUEST_INVALIDATED);
313 suggest_results_pending_ = 0;
314 timer_.Stop();
315 // Stop any in-progress URL fetches.
316 keyword_fetcher_.reset();
317 default_fetcher_.reset();
320 void SearchProvider::ClearAllResults() {
321 keyword_results_.Clear();
322 default_results_.Clear();
325 int SearchProvider::GetDefaultResultRelevance() const {
326 return -1;
329 void SearchProvider::RecordDeletionResult(bool success) {
330 if (success) {
331 content::RecordAction(
332 base::UserMetricsAction("Omnibox.ServerSuggestDelete.Success"));
333 } else {
334 content::RecordAction(
335 base::UserMetricsAction("Omnibox.ServerSuggestDelete.Failure"));
339 void SearchProvider::LogFetchComplete(bool success, bool is_keyword) {
340 LogOmniboxSuggestRequest(REPLY_RECEIVED);
341 // Record response time for suggest requests sent to Google. We care
342 // only about the common case: the Google default provider used in
343 // non-keyword mode.
344 const TemplateURL* default_url = providers_.GetDefaultProviderURL();
345 if (!is_keyword && default_url &&
346 (TemplateURLPrepopulateData::GetEngineType(*default_url) ==
347 SEARCH_ENGINE_GOOGLE)) {
348 const base::TimeDelta elapsed_time =
349 base::TimeTicks::Now() - time_suggest_request_sent_;
350 if (success) {
351 UMA_HISTOGRAM_TIMES("Omnibox.SuggestRequest.Success.GoogleResponseTime",
352 elapsed_time);
353 } else {
354 UMA_HISTOGRAM_TIMES("Omnibox.SuggestRequest.Failure.GoogleResponseTime",
355 elapsed_time);
360 bool SearchProvider::IsKeywordFetcher(const net::URLFetcher* fetcher) const {
361 return fetcher == keyword_fetcher_.get();
364 void SearchProvider::UpdateMatches() {
365 ConvertResultsToAutocompleteMatches();
367 // Check constraints that may be violated by suggested relevances.
368 if (!matches_.empty() &&
369 (default_results_.HasServerProvidedScores() ||
370 keyword_results_.HasServerProvidedScores())) {
371 // These blocks attempt to repair undesirable behavior by suggested
372 // relevances with minimal impact, preserving other suggested relevances.
374 if (!HasKeywordDefaultMatchInKeywordMode()) {
375 // In keyword mode, disregard the keyword verbatim suggested relevance
376 // if necessary so there at least one keyword match that's allowed to
377 // be the default match.
378 keyword_results_.verbatim_relevance = -1;
379 ConvertResultsToAutocompleteMatches();
381 if (IsTopMatchSearchWithURLInput()) {
382 // Disregard the suggested search and verbatim relevances if the input
383 // type is URL and the top match is a highly-ranked search suggestion.
384 // For example, prevent a search for "foo.com" from outranking another
385 // provider's navigation for "foo.com" or "foo.com/url_from_history".
386 ApplyCalculatedSuggestRelevance(&keyword_results_.suggest_results);
387 ApplyCalculatedSuggestRelevance(&default_results_.suggest_results);
388 default_results_.verbatim_relevance = -1;
389 keyword_results_.verbatim_relevance = -1;
390 ConvertResultsToAutocompleteMatches();
392 if (FindTopMatch() == matches_.end()) {
393 // Guarantee that SearchProvider returns a legal default match. (The
394 // omnibox always needs at least one legal default match, and it relies
395 // on SearchProvider to always return one.)
396 ApplyCalculatedRelevance();
397 ConvertResultsToAutocompleteMatches();
399 DCHECK(HasKeywordDefaultMatchInKeywordMode());
400 DCHECK(!IsTopMatchSearchWithURLInput());
401 DCHECK(FindTopMatch() != matches_.end());
403 UMA_HISTOGRAM_CUSTOM_COUNTS(
404 "Omnibox.SearchProviderMatches", matches_.size(), 1, 6, 7);
406 const TemplateURL* keyword_url = providers_.GetKeywordProviderURL();
407 if ((keyword_url != NULL) && HasKeywordDefaultMatchInKeywordMode()) {
408 // If there is a keyword match that is allowed to be the default match,
409 // then prohibit default provider matches from being the default match lest
410 // such matches cause the user to break out of keyword mode.
411 for (ACMatches::iterator it = matches_.begin(); it != matches_.end();
412 ++it) {
413 if (it->keyword != keyword_url->keyword())
414 it->allowed_to_be_default_match = false;
418 base::TimeTicks update_starred_start_time(base::TimeTicks::Now());
419 UpdateStarredStateOfMatches();
420 UMA_HISTOGRAM_TIMES("Omnibox.SearchProvider.UpdateStarredTime",
421 base::TimeTicks::Now() - update_starred_start_time);
422 UpdateDone();
425 void SearchProvider::Run() {
426 // Start a new request with the current input.
427 suggest_results_pending_ = 0;
428 time_suggest_request_sent_ = base::TimeTicks::Now();
430 default_fetcher_.reset(CreateSuggestFetcher(kDefaultProviderURLFetcherID,
431 providers_.GetDefaultProviderURL(), input_));
432 keyword_fetcher_.reset(CreateSuggestFetcher(kKeywordProviderURLFetcherID,
433 providers_.GetKeywordProviderURL(), keyword_input_));
435 // Both the above can fail if the providers have been modified or deleted
436 // since the query began.
437 if (suggest_results_pending_ == 0) {
438 UpdateDone();
439 // We only need to update the listener if we're actually done.
440 if (done_)
441 listener_->OnProviderUpdate(false);
445 void SearchProvider::DoHistoryQuery(bool minimal_changes) {
446 // The history query results are synchronous, so if minimal_changes is true,
447 // we still have the last results and don't need to do anything.
448 if (minimal_changes)
449 return;
451 keyword_history_results_.clear();
452 default_history_results_.clear();
454 if (OmniboxFieldTrial::SearchHistoryDisable(
455 input_.current_page_classification()))
456 return;
458 HistoryService* const history_service =
459 HistoryServiceFactory::GetForProfile(profile_, Profile::EXPLICIT_ACCESS);
460 history::URLDatabase* url_db = history_service ?
461 history_service->InMemoryDatabase() : NULL;
462 if (!url_db)
463 return;
465 // Request history for both the keyword and default provider. We grab many
466 // more matches than we'll ultimately clamp to so that if there are several
467 // recent multi-word matches who scores are lowered (see
468 // AddHistoryResultsToMap()), they won't crowd out older, higher-scoring
469 // matches. Note that this doesn't fix the problem entirely, but merely
470 // limits it to cases with a very large number of such multi-word matches; for
471 // now, this seems OK compared with the complexity of a real fix, which would
472 // require multiple searches and tracking of "single- vs. multi-word" in the
473 // database.
474 int num_matches = kMaxMatches * 5;
475 const TemplateURL* default_url = providers_.GetDefaultProviderURL();
476 if (default_url) {
477 const base::TimeTicks start_time = base::TimeTicks::Now();
478 url_db->GetMostRecentKeywordSearchTerms(default_url->id(), input_.text(),
479 num_matches, &default_history_results_);
480 UMA_HISTOGRAM_TIMES(
481 "Omnibox.SearchProvider.GetMostRecentKeywordTermsDefaultProviderTime",
482 base::TimeTicks::Now() - start_time);
484 const TemplateURL* keyword_url = providers_.GetKeywordProviderURL();
485 if (keyword_url) {
486 url_db->GetMostRecentKeywordSearchTerms(keyword_url->id(),
487 keyword_input_.text(), num_matches, &keyword_history_results_);
491 void SearchProvider::StartOrStopSuggestQuery(bool minimal_changes) {
492 if (!IsQuerySuitableForSuggest()) {
493 StopSuggest();
494 ClearAllResults();
495 return;
498 // For the minimal_changes case, if we finished the previous query and still
499 // have its results, or are allowed to keep running it, just do that, rather
500 // than starting a new query.
501 if (minimal_changes &&
502 (!default_results_.suggest_results.empty() ||
503 !default_results_.navigation_results.empty() ||
504 !keyword_results_.suggest_results.empty() ||
505 !keyword_results_.navigation_results.empty() ||
506 (!done_ && input_.want_asynchronous_matches())))
507 return;
509 // We can't keep running any previous query, so halt it.
510 StopSuggest();
512 // Remove existing results that cannot inline autocomplete the new input.
513 RemoveAllStaleResults();
515 // Update the content classifications of remaining results so they look good
516 // against the current input.
517 UpdateMatchContentsClass(input_.text(), &default_results_);
518 if (!keyword_input_.text().empty())
519 UpdateMatchContentsClass(keyword_input_.text(), &keyword_results_);
521 // We can't start a new query if we're only allowed synchronous results.
522 if (!input_.want_asynchronous_matches())
523 return;
525 // To avoid flooding the suggest server, don't send a query until at
526 // least 100 ms since the last query.
527 base::TimeTicks next_suggest_time(time_suggest_request_sent_ +
528 base::TimeDelta::FromMilliseconds(kMinimumTimeBetweenSuggestQueriesMs));
529 base::TimeTicks now(base::TimeTicks::Now());
530 if (now >= next_suggest_time) {
531 Run();
532 return;
534 timer_.Start(FROM_HERE, next_suggest_time - now, this, &SearchProvider::Run);
537 bool SearchProvider::IsQuerySuitableForSuggest() const {
538 // Don't run Suggest in incognito mode, if the engine doesn't support it, or
539 // if the user has disabled it.
540 const TemplateURL* default_url = providers_.GetDefaultProviderURL();
541 const TemplateURL* keyword_url = providers_.GetKeywordProviderURL();
542 if (profile_->IsOffTheRecord() ||
543 ((!default_url || default_url->suggestions_url().empty()) &&
544 (!keyword_url || keyword_url->suggestions_url().empty())) ||
545 !profile_->GetPrefs()->GetBoolean(prefs::kSearchSuggestEnabled))
546 return false;
548 // If the input type might be a URL, we take extra care so that private data
549 // isn't sent to the server.
551 // FORCED_QUERY means the user is explicitly asking us to search for this, so
552 // we assume it isn't a URL and/or there isn't private data.
553 if (input_.type() == metrics::OmniboxInputType::FORCED_QUERY)
554 return true;
556 // Next we check the scheme. If this is UNKNOWN/URL with a scheme that isn't
557 // http/https/ftp, we shouldn't send it. Sending things like file: and data:
558 // is both a waste of time and a disclosure of potentially private, local
559 // data. Other "schemes" may actually be usernames, and we don't want to send
560 // passwords. If the scheme is OK, we still need to check other cases below.
561 // If this is QUERY, then the presence of these schemes means the user
562 // explicitly typed one, and thus this is probably a URL that's being entered
563 // and happens to currently be invalid -- in which case we again want to run
564 // our checks below. Other QUERY cases are less likely to be URLs and thus we
565 // assume we're OK.
566 if (!LowerCaseEqualsASCII(input_.scheme(), url::kHttpScheme) &&
567 !LowerCaseEqualsASCII(input_.scheme(), url::kHttpsScheme) &&
568 !LowerCaseEqualsASCII(input_.scheme(), url::kFtpScheme))
569 return (input_.type() == metrics::OmniboxInputType::QUERY);
571 // Don't send URLs with usernames, queries or refs. Some of these are
572 // private, and the Suggest server is unlikely to have any useful results
573 // for any of them. Also don't send URLs with ports, as we may initially
574 // think that a username + password is a host + port (and we don't want to
575 // send usernames/passwords), and even if the port really is a port, the
576 // server is once again unlikely to have and useful results.
577 // Note that we only block based on refs if the input is URL-typed, as search
578 // queries can legitimately have #s in them which the URL parser
579 // overaggressively categorizes as a url with a ref.
580 const url::Parsed& parts = input_.parts();
581 if (parts.username.is_nonempty() || parts.port.is_nonempty() ||
582 parts.query.is_nonempty() ||
583 (parts.ref.is_nonempty() &&
584 (input_.type() == metrics::OmniboxInputType::URL)))
585 return false;
587 // Don't send anything for https except the hostname. Hostnames are OK
588 // because they are visible when the TCP connection is established, but the
589 // specific path may reveal private information.
590 if (LowerCaseEqualsASCII(input_.scheme(), url::kHttpsScheme) &&
591 parts.path.is_nonempty())
592 return false;
594 return true;
597 void SearchProvider::RemoveAllStaleResults() {
598 if (keyword_input_.text().empty()) {
599 // User is either in keyword mode with a blank input or out of
600 // keyword mode entirely.
601 keyword_results_.Clear();
605 void SearchProvider::ApplyCalculatedRelevance() {
606 ApplyCalculatedSuggestRelevance(&keyword_results_.suggest_results);
607 ApplyCalculatedSuggestRelevance(&default_results_.suggest_results);
608 ApplyCalculatedNavigationRelevance(&keyword_results_.navigation_results);
609 ApplyCalculatedNavigationRelevance(&default_results_.navigation_results);
610 default_results_.verbatim_relevance = -1;
611 keyword_results_.verbatim_relevance = -1;
614 void SearchProvider::ApplyCalculatedSuggestRelevance(SuggestResults* list) {
615 for (size_t i = 0; i < list->size(); ++i) {
616 SuggestResult& result = (*list)[i];
617 result.set_relevance(
618 result.CalculateRelevance(input_, providers_.has_keyword_provider()) +
619 (list->size() - i - 1));
620 result.set_relevance_from_server(false);
624 void SearchProvider::ApplyCalculatedNavigationRelevance(
625 NavigationResults* list) {
626 for (size_t i = 0; i < list->size(); ++i) {
627 NavigationResult& result = (*list)[i];
628 result.set_relevance(
629 result.CalculateRelevance(input_, providers_.has_keyword_provider()) +
630 (list->size() - i - 1));
631 result.set_relevance_from_server(false);
635 net::URLFetcher* SearchProvider::CreateSuggestFetcher(
636 int id,
637 const TemplateURL* template_url,
638 const AutocompleteInput& input) {
639 if (!template_url || template_url->suggestions_url().empty())
640 return NULL;
642 // Bail if the suggestion URL is invalid with the given replacements.
643 TemplateURLRef::SearchTermsArgs search_term_args(input.text());
644 search_term_args.input_type = input.type();
645 search_term_args.cursor_position = input.cursor_position();
646 search_term_args.page_classification = input.current_page_classification();
647 if (CommandLine::ForCurrentProcess()->HasSwitch(
648 switches::kEnableAnswersInSuggest))
649 search_term_args.session_token = GetSessionToken();
650 GURL suggest_url(template_url->suggestions_url_ref().ReplaceSearchTerms(
651 search_term_args));
652 if (!suggest_url.is_valid())
653 return NULL;
654 // Send the current page URL if user setting and URL requirements are met and
655 // the user is in the field trial.
656 if (CanSendURL(current_page_url_, suggest_url, template_url,
657 input.current_page_classification(), profile_) &&
658 OmniboxFieldTrial::InZeroSuggestAfterTypingFieldTrial()) {
659 search_term_args.current_page_url = current_page_url_.spec();
660 // Create the suggest URL again with the current page URL.
661 suggest_url = GURL(template_url->suggestions_url_ref().ReplaceSearchTerms(
662 search_term_args));
665 suggest_results_pending_++;
666 LogOmniboxSuggestRequest(REQUEST_SENT);
668 net::URLFetcher* fetcher =
669 net::URLFetcher::Create(id, suggest_url, net::URLFetcher::GET, this);
670 fetcher->SetRequestContext(profile_->GetRequestContext());
671 fetcher->SetLoadFlags(net::LOAD_DO_NOT_SAVE_COOKIES);
672 // Add Chrome experiment state to the request headers.
673 net::HttpRequestHeaders headers;
674 chrome_variations::VariationsHttpHeaderProvider::GetInstance()->AppendHeaders(
675 fetcher->GetOriginalURL(), profile_->IsOffTheRecord(), false, &headers);
676 fetcher->SetExtraRequestHeaders(headers.ToString());
677 fetcher->Start();
678 return fetcher;
681 void SearchProvider::ConvertResultsToAutocompleteMatches() {
682 // Convert all the results to matches and add them to a map, so we can keep
683 // the most relevant match for each result.
684 base::TimeTicks start_time(base::TimeTicks::Now());
685 MatchMap map;
686 const base::Time no_time;
687 int did_not_accept_keyword_suggestion =
688 keyword_results_.suggest_results.empty() ?
689 TemplateURLRef::NO_SUGGESTIONS_AVAILABLE :
690 TemplateURLRef::NO_SUGGESTION_CHOSEN;
692 bool relevance_from_server;
693 int verbatim_relevance = GetVerbatimRelevance(&relevance_from_server);
694 int did_not_accept_default_suggestion =
695 default_results_.suggest_results.empty() ?
696 TemplateURLRef::NO_SUGGESTIONS_AVAILABLE :
697 TemplateURLRef::NO_SUGGESTION_CHOSEN;
698 if (verbatim_relevance > 0) {
699 const base::string16& trimmed_verbatim =
700 base::CollapseWhitespace(input_.text(), false);
701 SuggestResult verbatim(
702 trimmed_verbatim, AutocompleteMatchType::SEARCH_WHAT_YOU_TYPED,
703 trimmed_verbatim, base::string16(), base::string16(), base::string16(),
704 base::string16(), std::string(), std::string(), false,
705 verbatim_relevance, relevance_from_server, false,
706 trimmed_verbatim);
707 AddMatchToMap(verbatim, std::string(), did_not_accept_default_suggestion,
708 false, &map);
710 if (!keyword_input_.text().empty()) {
711 const TemplateURL* keyword_url = providers_.GetKeywordProviderURL();
712 // We only create the verbatim search query match for a keyword
713 // if it's not an extension keyword. Extension keywords are handled
714 // in KeywordProvider::Start(). (Extensions are complicated...)
715 // Note: in this provider, SEARCH_OTHER_ENGINE must correspond
716 // to the keyword verbatim search query. Do not create other matches
717 // of type SEARCH_OTHER_ENGINE.
718 if (keyword_url &&
719 (keyword_url->GetType() != TemplateURL::OMNIBOX_API_EXTENSION)) {
720 bool keyword_relevance_from_server;
721 const int keyword_verbatim_relevance =
722 GetKeywordVerbatimRelevance(&keyword_relevance_from_server);
723 if (keyword_verbatim_relevance > 0) {
724 const base::string16& trimmed_verbatim =
725 base::CollapseWhitespace(keyword_input_.text(), false);
726 SuggestResult verbatim(
727 trimmed_verbatim, AutocompleteMatchType::SEARCH_OTHER_ENGINE,
728 trimmed_verbatim, base::string16(), base::string16(),
729 base::string16(), base::string16(), std::string(), std::string(),
730 true, keyword_verbatim_relevance, keyword_relevance_from_server,
731 false, trimmed_verbatim);
732 AddMatchToMap(verbatim, std::string(),
733 did_not_accept_keyword_suggestion, false, &map);
737 AddHistoryResultsToMap(keyword_history_results_, true,
738 did_not_accept_keyword_suggestion, &map);
739 AddHistoryResultsToMap(default_history_results_, false,
740 did_not_accept_default_suggestion, &map);
742 AddSuggestResultsToMap(keyword_results_.suggest_results,
743 keyword_results_.metadata, &map);
744 AddSuggestResultsToMap(default_results_.suggest_results,
745 default_results_.metadata, &map);
747 ACMatches matches;
748 for (MatchMap::const_iterator i(map.begin()); i != map.end(); ++i)
749 matches.push_back(i->second);
751 AddNavigationResultsToMatches(keyword_results_.navigation_results, &matches);
752 AddNavigationResultsToMatches(default_results_.navigation_results, &matches);
754 // Now add the most relevant matches to |matches_|. We take up to kMaxMatches
755 // suggest/navsuggest matches, regardless of origin. If Instant Extended is
756 // enabled and we have server-provided (and thus hopefully more accurate)
757 // scores for some suggestions, we allow more of those, until we reach
758 // AutocompleteResult::kMaxMatches total matches (that is, enough to fill the
759 // whole popup).
761 // We will always return any verbatim matches, no matter how we obtained their
762 // scores, unless we have already accepted AutocompleteResult::kMaxMatches
763 // higher-scoring matches under the conditions above.
764 std::sort(matches.begin(), matches.end(), &AutocompleteMatch::MoreRelevant);
765 matches_.clear();
767 size_t num_suggestions = 0;
768 for (ACMatches::const_iterator i(matches.begin());
769 (i != matches.end()) &&
770 (matches_.size() < AutocompleteResult::kMaxMatches);
771 ++i) {
772 // SEARCH_OTHER_ENGINE is only used in the SearchProvider for the keyword
773 // verbatim result, so this condition basically means "if this match is a
774 // suggestion of some sort".
775 if ((i->type != AutocompleteMatchType::SEARCH_WHAT_YOU_TYPED) &&
776 (i->type != AutocompleteMatchType::SEARCH_OTHER_ENGINE)) {
777 // If we've already hit the limit on non-server-scored suggestions, and
778 // this isn't a server-scored suggestion we can add, skip it.
779 if ((num_suggestions >= kMaxMatches) &&
780 (!chrome::IsInstantExtendedAPIEnabled() ||
781 (i->GetAdditionalInfo(kRelevanceFromServerKey) != kTrue))) {
782 continue;
785 ++num_suggestions;
788 matches_.push_back(*i);
790 UMA_HISTOGRAM_TIMES("Omnibox.SearchProvider.ConvertResultsTime",
791 base::TimeTicks::Now() - start_time);
794 ACMatches::const_iterator SearchProvider::FindTopMatch() const {
795 ACMatches::const_iterator it = matches_.begin();
796 while ((it != matches_.end()) && !it->allowed_to_be_default_match)
797 ++it;
798 return it;
801 bool SearchProvider::HasKeywordDefaultMatchInKeywordMode() const {
802 const TemplateURL* keyword_url = providers_.GetKeywordProviderURL();
803 // If the user is not in keyword mode, return true to say that this
804 // constraint is not violated.
805 if (keyword_url == NULL)
806 return true;
807 for (ACMatches::const_iterator it = matches_.begin(); it != matches_.end();
808 ++it) {
809 if ((it->keyword == keyword_url->keyword()) &&
810 it->allowed_to_be_default_match)
811 return true;
813 return false;
816 bool SearchProvider::IsTopMatchSearchWithURLInput() const {
817 ACMatches::const_iterator first_match = FindTopMatch();
818 return (input_.type() == metrics::OmniboxInputType::URL) &&
819 (first_match != matches_.end()) &&
820 (first_match->relevance > CalculateRelevanceForVerbatim()) &&
821 (first_match->type != AutocompleteMatchType::NAVSUGGEST) &&
822 (first_match->type != AutocompleteMatchType::NAVSUGGEST_PERSONALIZED);
825 void SearchProvider::AddNavigationResultsToMatches(
826 const NavigationResults& navigation_results,
827 ACMatches* matches) {
828 for (NavigationResults::const_iterator it = navigation_results.begin();
829 it != navigation_results.end(); ++it) {
830 matches->push_back(NavigationToMatch(*it));
831 // In the absence of suggested relevance scores, use only the single
832 // highest-scoring result. (The results are already sorted by relevance.)
833 if (!it->relevance_from_server())
834 return;
838 void SearchProvider::AddHistoryResultsToMap(const HistoryResults& results,
839 bool is_keyword,
840 int did_not_accept_suggestion,
841 MatchMap* map) {
842 if (results.empty())
843 return;
845 base::TimeTicks start_time(base::TimeTicks::Now());
846 bool prevent_inline_autocomplete = input_.prevent_inline_autocomplete() ||
847 (input_.type() == metrics::OmniboxInputType::URL);
848 const base::string16& input_text =
849 is_keyword ? keyword_input_.text() : input_.text();
850 bool input_multiple_words = HasMultipleWords(input_text);
852 SuggestResults scored_results;
853 if (!prevent_inline_autocomplete && input_multiple_words) {
854 // ScoreHistoryResults() allows autocompletion of multi-word, 1-visit
855 // queries if the input also has multiple words. But if we were already
856 // scoring a multi-word, multi-visit query aggressively, and the current
857 // input is still a prefix of it, then changing the suggestion suddenly
858 // feels wrong. To detect this case, first score as if only one word has
859 // been typed, then check if the best result came from aggressive search
860 // history scoring. If it did, then just keep that score set. This
861 // 1200 the lowest possible score in CalculateRelevanceForHistory()'s
862 // aggressive-scoring curve.
863 scored_results = ScoreHistoryResults(results, prevent_inline_autocomplete,
864 false, input_text, is_keyword);
865 if ((scored_results.front().relevance() < 1200) ||
866 !HasMultipleWords(scored_results.front().suggestion()))
867 scored_results.clear(); // Didn't detect the case above, score normally.
869 if (scored_results.empty())
870 scored_results = ScoreHistoryResults(results, prevent_inline_autocomplete,
871 input_multiple_words, input_text,
872 is_keyword);
873 for (SuggestResults::const_iterator i(scored_results.begin());
874 i != scored_results.end(); ++i) {
875 AddMatchToMap(*i, std::string(), did_not_accept_suggestion, true, map);
877 UMA_HISTOGRAM_TIMES("Omnibox.SearchProvider.AddHistoryResultsTime",
878 base::TimeTicks::Now() - start_time);
881 SearchProvider::SuggestResults SearchProvider::ScoreHistoryResults(
882 const HistoryResults& results,
883 bool base_prevent_inline_autocomplete,
884 bool input_multiple_words,
885 const base::string16& input_text,
886 bool is_keyword) {
887 AutocompleteClassifier* classifier =
888 AutocompleteClassifierFactory::GetForProfile(profile_);
889 SuggestResults scored_results;
890 const bool prevent_search_history_inlining =
891 OmniboxFieldTrial::SearchHistoryPreventInlining(
892 input_.current_page_classification());
893 const base::string16& trimmed_input =
894 base::CollapseWhitespace(input_text, false);
895 for (HistoryResults::const_iterator i(results.begin()); i != results.end();
896 ++i) {
897 const base::string16& trimmed_suggestion =
898 base::CollapseWhitespace(i->term, false);
900 // Don't autocomplete multi-word queries that have only been seen once
901 // unless the user has typed more than one word.
902 bool prevent_inline_autocomplete = base_prevent_inline_autocomplete ||
903 (!input_multiple_words && (i->visits < 2) &&
904 HasMultipleWords(trimmed_suggestion));
906 // Don't autocomplete search terms that would normally be treated as URLs
907 // when typed. For example, if the user searched for "google.com" and types
908 // "goog", don't autocomplete to the search term "google.com". Otherwise,
909 // the input will look like a URL but act like a search, which is confusing.
910 // NOTE: We don't check this in the following cases:
911 // * When inline autocomplete is disabled, we won't be inline
912 // autocompleting this term, so we don't need to worry about confusion as
913 // much. This also prevents calling Classify() again from inside the
914 // classifier (which will corrupt state and likely crash), since the
915 // classifier always disables inline autocomplete.
916 // * When the user has typed the whole term, the "what you typed" history
917 // match will outrank us for URL-like inputs anyway, so we need not do
918 // anything special.
919 if (!prevent_inline_autocomplete && classifier &&
920 (trimmed_suggestion != trimmed_input)) {
921 AutocompleteMatch match;
922 classifier->Classify(trimmed_suggestion, false, false,
923 input_.current_page_classification(), &match, NULL);
924 prevent_inline_autocomplete =
925 !AutocompleteMatch::IsSearchType(match.type);
928 int relevance = CalculateRelevanceForHistory(
929 i->time, is_keyword, !prevent_inline_autocomplete,
930 prevent_search_history_inlining);
931 scored_results.push_back(SuggestResult(
932 trimmed_suggestion, AutocompleteMatchType::SEARCH_HISTORY,
933 trimmed_suggestion, base::string16(), base::string16(),
934 base::string16(), base::string16(), std::string(), std::string(),
935 is_keyword, relevance, false, false, trimmed_input));
938 // History returns results sorted for us. However, we may have docked some
939 // results' scores, so things are no longer in order. Do a stable sort to get
940 // things back in order without otherwise disturbing results with equal
941 // scores, then force the scores to be unique, so that the order in which
942 // they're shown is deterministic.
943 std::stable_sort(scored_results.begin(), scored_results.end(),
944 CompareScoredResults());
945 int last_relevance = 0;
946 for (SuggestResults::iterator i(scored_results.begin());
947 i != scored_results.end(); ++i) {
948 if ((i != scored_results.begin()) && (i->relevance() >= last_relevance))
949 i->set_relevance(last_relevance - 1);
950 last_relevance = i->relevance();
953 return scored_results;
956 void SearchProvider::AddSuggestResultsToMap(const SuggestResults& results,
957 const std::string& metadata,
958 MatchMap* map) {
959 for (size_t i = 0; i < results.size(); ++i)
960 AddMatchToMap(results[i], metadata, i, false, map);
963 int SearchProvider::GetVerbatimRelevance(bool* relevance_from_server) const {
964 // Use the suggested verbatim relevance score if it is non-negative (valid),
965 // if inline autocomplete isn't prevented (always show verbatim on backspace),
966 // and if it won't suppress verbatim, leaving no default provider matches.
967 // Otherwise, if the default provider returned no matches and was still able
968 // to suppress verbatim, the user would have no search/nav matches and may be
969 // left unable to search using their default provider from the omnibox.
970 // Check for results on each verbatim calculation, as results from older
971 // queries (on previous input) may be trimmed for failing to inline new input.
972 bool use_server_relevance =
973 (default_results_.verbatim_relevance >= 0) &&
974 !input_.prevent_inline_autocomplete() &&
975 ((default_results_.verbatim_relevance > 0) ||
976 !default_results_.suggest_results.empty() ||
977 !default_results_.navigation_results.empty());
978 if (relevance_from_server)
979 *relevance_from_server = use_server_relevance;
980 return use_server_relevance ?
981 default_results_.verbatim_relevance : CalculateRelevanceForVerbatim();
984 int SearchProvider::CalculateRelevanceForVerbatim() const {
985 if (!providers_.keyword_provider().empty())
986 return 250;
987 return CalculateRelevanceForVerbatimIgnoringKeywordModeState();
990 int SearchProvider::
991 CalculateRelevanceForVerbatimIgnoringKeywordModeState() const {
992 switch (input_.type()) {
993 case metrics::OmniboxInputType::UNKNOWN:
994 case metrics::OmniboxInputType::QUERY:
995 case metrics::OmniboxInputType::FORCED_QUERY:
996 return kNonURLVerbatimRelevance;
998 case metrics::OmniboxInputType::URL:
999 return 850;
1001 default:
1002 NOTREACHED();
1003 return 0;
1007 int SearchProvider::GetKeywordVerbatimRelevance(
1008 bool* relevance_from_server) const {
1009 // Use the suggested verbatim relevance score if it is non-negative (valid),
1010 // if inline autocomplete isn't prevented (always show verbatim on backspace),
1011 // and if it won't suppress verbatim, leaving no keyword provider matches.
1012 // Otherwise, if the keyword provider returned no matches and was still able
1013 // to suppress verbatim, the user would have no search/nav matches and may be
1014 // left unable to search using their keyword provider from the omnibox.
1015 // Check for results on each verbatim calculation, as results from older
1016 // queries (on previous input) may be trimmed for failing to inline new input.
1017 bool use_server_relevance =
1018 (keyword_results_.verbatim_relevance >= 0) &&
1019 !input_.prevent_inline_autocomplete() &&
1020 ((keyword_results_.verbatim_relevance > 0) ||
1021 !keyword_results_.suggest_results.empty() ||
1022 !keyword_results_.navigation_results.empty());
1023 if (relevance_from_server)
1024 *relevance_from_server = use_server_relevance;
1025 return use_server_relevance ?
1026 keyword_results_.verbatim_relevance :
1027 CalculateRelevanceForKeywordVerbatim(keyword_input_.type(),
1028 keyword_input_.prefer_keyword());
1031 int SearchProvider::CalculateRelevanceForHistory(
1032 const base::Time& time,
1033 bool is_keyword,
1034 bool use_aggressive_method,
1035 bool prevent_search_history_inlining) const {
1036 // The relevance of past searches falls off over time. There are two distinct
1037 // equations used. If the first equation is used (searches to the primary
1038 // provider that we want to score aggressively), the score is in the range
1039 // 1300-1599 (unless |prevent_search_history_inlining|, in which case
1040 // it's in the range 1200-1299). If the second equation is used the
1041 // relevance of a search 15 minutes ago is discounted 50 points, while the
1042 // relevance of a search two weeks ago is discounted 450 points.
1043 double elapsed_time = std::max((base::Time::Now() - time).InSecondsF(), 0.0);
1044 bool is_primary_provider = is_keyword || !providers_.has_keyword_provider();
1045 if (is_primary_provider && use_aggressive_method) {
1046 // Searches with the past two days get a different curve.
1047 const double autocomplete_time = 2 * 24 * 60 * 60;
1048 if (elapsed_time < autocomplete_time) {
1049 int max_score = is_keyword ? 1599 : 1399;
1050 if (prevent_search_history_inlining)
1051 max_score = 1299;
1052 return max_score - static_cast<int>(99 *
1053 std::pow(elapsed_time / autocomplete_time, 2.5));
1055 elapsed_time -= autocomplete_time;
1058 const int score_discount =
1059 static_cast<int>(6.5 * std::pow(elapsed_time, 0.3));
1061 // Don't let scores go below 0. Negative relevance scores are meaningful in
1062 // a different way.
1063 int base_score;
1064 if (is_primary_provider)
1065 base_score = (input_.type() == metrics::OmniboxInputType::URL) ? 750 : 1050;
1066 else
1067 base_score = 200;
1068 return std::max(0, base_score - score_discount);
1071 AutocompleteMatch SearchProvider::NavigationToMatch(
1072 const NavigationResult& navigation) {
1073 base::string16 input;
1074 const bool trimmed_whitespace = base::TrimWhitespace(
1075 navigation.from_keyword_provider() ?
1076 keyword_input_.text() : input_.text(),
1077 base::TRIM_TRAILING, &input) != base::TRIM_NONE;
1078 AutocompleteMatch match(this, navigation.relevance(), false,
1079 navigation.type());
1080 match.destination_url = navigation.url();
1081 BaseSearchProvider::SetDeletionURL(navigation.deletion_url(), &match);
1082 // First look for the user's input inside the formatted url as it would be
1083 // without trimming the scheme, so we can find matches at the beginning of the
1084 // scheme.
1085 const URLPrefix* prefix =
1086 URLPrefix::BestURLPrefix(navigation.formatted_url(), input);
1087 size_t match_start = (prefix == NULL) ?
1088 navigation.formatted_url().find(input) : prefix->prefix.length();
1089 bool trim_http = !AutocompleteInput::HasHTTPScheme(input) &&
1090 (!prefix || (match_start != 0));
1091 const net::FormatUrlTypes format_types =
1092 net::kFormatUrlOmitAll & ~(trim_http ? 0 : net::kFormatUrlOmitHTTP);
1094 const std::string languages(
1095 profile_->GetPrefs()->GetString(prefs::kAcceptLanguages));
1096 size_t inline_autocomplete_offset = (prefix == NULL) ?
1097 base::string16::npos : (match_start + input.length());
1098 match.fill_into_edit +=
1099 AutocompleteInput::FormattedStringWithEquivalentMeaning(navigation.url(),
1100 net::FormatUrl(navigation.url(), languages, format_types,
1101 net::UnescapeRule::SPACES, NULL, NULL,
1102 &inline_autocomplete_offset));
1103 // Preserve the forced query '?' prefix in |match.fill_into_edit|.
1104 // Otherwise, user edits to a suggestion would show non-Search results.
1105 if (input_.type() == metrics::OmniboxInputType::FORCED_QUERY) {
1106 match.fill_into_edit.insert(0, base::ASCIIToUTF16("?"));
1107 if (inline_autocomplete_offset != base::string16::npos)
1108 ++inline_autocomplete_offset;
1110 if (inline_autocomplete_offset != base::string16::npos) {
1111 DCHECK(inline_autocomplete_offset <= match.fill_into_edit.length());
1112 match.inline_autocompletion =
1113 match.fill_into_edit.substr(inline_autocomplete_offset);
1115 // An inlineable navsuggestion can only be the default match when there
1116 // is no keyword provider active, lest it appear first and break the user
1117 // out of keyword mode. It can also only be default if either the inline
1118 // autocompletion is empty or we're not preventing inline autocompletion.
1119 // Finally, if we have an inlineable navsuggestion with an inline completion
1120 // that we're not preventing, make sure we didn't trim any whitespace.
1121 // We don't want to claim http://foo.com/bar is inlineable against the
1122 // input "foo.com/b ".
1123 match.allowed_to_be_default_match = navigation.IsInlineable(input) &&
1124 (providers_.GetKeywordProviderURL() == NULL) &&
1125 (match.inline_autocompletion.empty() ||
1126 (!input_.prevent_inline_autocomplete() && !trimmed_whitespace));
1128 match.contents = navigation.match_contents();
1129 match.contents_class = navigation.match_contents_class();
1130 match.description = navigation.description();
1131 AutocompleteMatch::ClassifyMatchInString(input, match.description,
1132 ACMatchClassification::NONE, &match.description_class);
1134 match.RecordAdditionalInfo(
1135 kRelevanceFromServerKey,
1136 navigation.relevance_from_server() ? kTrue : kFalse);
1137 match.RecordAdditionalInfo(kShouldPrefetchKey, kFalse);
1139 return match;
1142 void SearchProvider::UpdateDone() {
1143 // We're done when the timer isn't running, there are no suggest queries
1144 // pending, and we're not waiting on Instant.
1145 done_ = !timer_.IsRunning() && (suggest_results_pending_ == 0);
1148 std::string SearchProvider::GetSessionToken() {
1149 base::TimeTicks current_time(base::TimeTicks::Now());
1150 // Renew token if it expired.
1151 if (current_time > token_expiration_time_) {
1152 const size_t kTokenBytes = 12;
1153 std::string raw_data;
1154 base::RandBytes(WriteInto(&raw_data, kTokenBytes + 1), kTokenBytes);
1155 base::Base64Encode(raw_data, &current_token_);
1157 // Make the base64 encoded value URL and filename safe(see RFC 3548).
1158 std::replace(current_token_.begin(), current_token_.end(), '+', '-');
1159 std::replace(current_token_.begin(), current_token_.end(), '/', '_');
1162 // Extend expiration time another 60 seconds.
1163 token_expiration_time_ = current_time + base::TimeDelta::FromSeconds(60);
1165 return current_token_;