blob: 04b37a5a6092bfdf1c01e92a91d7a21963d3a863 [file] [log] [blame]
[email protected]e41982a72012-11-20 07:16:511// Copyright 2012 The Chromium Authors. All rights reserved.
license.botbf09a502008-08-24 00:55:552// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
initial.commit09911bf2008-07-26 23:55:294
5#include "chrome/browser/autocomplete/search_provider.h"
6
[email protected]1cb2dac2010-03-08 21:49:157#include <algorithm>
[email protected]c3a4bd992010-08-18 20:25:018#include <cmath>
[email protected]1cb2dac2010-03-08 21:49:159
[email protected]20184242014-05-14 02:57:4210#include "base/base64.h"
[email protected]2041cf342010-02-19 03:15:5911#include "base/callback.h"
[email protected]20184242014-05-14 02:57:4212#include "base/command_line.h"
[email protected]51124552011-07-16 01:37:1013#include "base/i18n/break_iterator.h"
[email protected]503d03872011-05-06 08:36:2614#include "base/i18n/case_conversion.h"
[email protected]ffbec692012-02-26 20:26:4215#include "base/json/json_string_value_serializer.h"
[email protected]fa1e0e12013-07-18 00:10:1416#include "base/message_loop/message_loop.h"
[email protected]f5b95ba92012-03-27 14:05:1917#include "base/metrics/histogram.h"
[email protected]f7f41c0e2014-08-11 04:22:2318#include "base/metrics/user_metrics.h"
[email protected]3853a4c2013-02-11 17:15:5719#include "base/prefs/pref_service.h"
[email protected]20184242014-05-14 02:57:4220#include "base/rand_util.h"
[email protected]5889bfb2014-03-19 00:26:4821#include "base/strings/string_util.h"
[email protected]135cb802013-06-09 16:44:2022#include "base/strings/utf_string_conversions.h"
[email protected]ea3b9a502011-04-04 14:19:3723#include "chrome/browser/autocomplete/autocomplete_classifier.h"
[email protected]810ffba2012-06-12 01:07:4824#include "chrome/browser/autocomplete/autocomplete_classifier_factory.h"
[email protected]73c2b1632012-07-02 22:51:3825#include "chrome/browser/autocomplete/autocomplete_result.h"
[email protected]a817ed392014-06-27 05:03:0026#include "chrome/browser/autocomplete/chrome_autocomplete_scheme_classifier.h"
[email protected]2c812ba02011-07-14 00:23:1527#include "chrome/browser/autocomplete/keyword_provider.h"
[email protected]6a2c09f2013-01-25 04:50:0728#include "chrome/browser/history/history_service.h"
[email protected]9d2db762012-06-19 00:01:1029#include "chrome/browser/history/history_service_factory.h"
[email protected]8ecad5e2010-12-02 21:18:3330#include "chrome/browser/profiles/profile.h"
initial.commit09911bf2008-07-26 23:55:2931#include "chrome/common/pref_names.h"
[email protected]8e44a5b02014-06-19 19:03:2432#include "components/google/core/browser/google_util.h"
[email protected]e3ce70ac2014-06-26 18:34:5633#include "components/history/core/browser/in_memory_database.h"
[email protected]73b2d1e72014-06-25 23:45:3634#include "components/history/core/browser/keyword_search_term.h"
[email protected]3dc75b12014-06-08 00:02:2235#include "components/metrics/proto/omnibox_input_type.pb.h"
[email protected]b1c5ab682014-08-07 11:53:1736#include "components/omnibox/autocomplete_provider_listener.h"
[email protected]4c583b62014-08-08 10:37:2337#include "components/omnibox/omnibox_field_trial.h"
[email protected]b1c5ab682014-08-07 11:53:1738#include "components/omnibox/url_prefix.h"
[email protected]720b10492014-07-23 08:48:4039#include "components/search/search.h"
[email protected]0915b352014-06-25 19:58:1440#include "components/search_engines/template_url_prepopulate_data.h"
[email protected]bf5c532d2014-07-05 00:29:5341#include "components/search_engines/template_url_service.h"
[email protected]71011c1682014-07-09 17:19:1642#include "components/variations/variations_http_header_provider.h"
[email protected]34ac8f32009-02-22 23:03:2743#include "grit/generated_resources.h"
initial.commit09911bf2008-07-26 23:55:2944#include "net/base/escape.h"
[email protected]d3cf8682f02012-02-29 23:29:3445#include "net/base/load_flags.h"
[email protected]371dab12012-06-01 03:23:5546#include "net/base/net_util.h"
[email protected]bd3b4712012-12-18 17:01:3047#include "net/http/http_request_headers.h"
[email protected]3dc1bc42012-06-19 08:20:5348#include "net/url_request/url_fetcher.h"
[email protected]319d9e6f2009-02-18 19:47:2149#include "net/url_request/url_request_status.h"
[email protected]c051a1b2011-01-21 23:30:1750#include "ui/base/l10n/l10n_util.h"
[email protected]cca6f392014-05-28 21:32:2651#include "url/url_constants.h"
[email protected]761fa4702013-07-02 15:25:1552#include "url/url_util.h"
initial.commit09911bf2008-07-26 23:55:2953
[email protected]bc8bb0cd2013-06-24 21:50:2354// Helpers --------------------------------------------------------------------
[email protected]e1acf6f2008-10-27 20:43:3355
[email protected]51124552011-07-16 01:37:1056namespace {
57
[email protected]7706a522012-08-16 17:42:2558// We keep track in a histogram how many suggest requests we send, how
59// many suggest requests we invalidate (e.g., due to a user typing
60// another character), and how many replies we receive.
61// *** ADD NEW ENUMS AFTER ALL PREVIOUSLY DEFINED ONES! ***
62// (excluding the end-of-list enum value)
63// We do not want values of existing enums to change or else it screws
64// up the statistics.
65enum SuggestRequestsHistogramValue {
66 REQUEST_SENT = 1,
67 REQUEST_INVALIDATED,
68 REPLY_RECEIVED,
69 MAX_SUGGEST_REQUEST_HISTOGRAM_VALUE
70};
71
[email protected]90fe2bb2013-01-15 03:42:1372// The verbatim score for an input which is not an URL.
73const int kNonURLVerbatimRelevance = 1300;
74
[email protected]7706a522012-08-16 17:42:2575// Increments the appropriate value in the histogram by one.
76void LogOmniboxSuggestRequest(
77 SuggestRequestsHistogramValue request_value) {
78 UMA_HISTOGRAM_ENUMERATION("Omnibox.SuggestRequests", request_value,
79 MAX_SUGGEST_REQUEST_HISTOGRAM_VALUE);
80}
81
[email protected]0085863a2013-12-06 21:19:0382bool HasMultipleWords(const base::string16& text) {
[email protected]51124552011-07-16 01:37:1083 base::i18n::BreakIterator i(text, base::i18n::BreakIterator::BREAK_WORD);
84 bool found_word = false;
85 if (i.Init()) {
86 while (i.Advance()) {
87 if (i.IsWord()) {
88 if (found_word)
89 return true;
90 found_word = true;
91 }
92 }
93 }
94 return false;
95}
96
[email protected]d1f0a7f2012-06-05 10:26:4297} // namespace
[email protected]51124552011-07-16 01:37:1098
[email protected]3954c3a2012-04-10 20:17:5599// SearchProvider::Providers --------------------------------------------------
[email protected]b547666d2009-04-23 16:37:58100
[email protected]85b8d6f2012-05-08 20:53:47101SearchProvider::Providers::Providers(TemplateURLService* template_url_service)
[email protected]02346202014-02-05 05:18:30102 : template_url_service_(template_url_service) {}
[email protected]85b8d6f2012-05-08 20:53:47103
104const TemplateURL* SearchProvider::Providers::GetDefaultProviderURL() const {
105 return default_provider_.empty() ? NULL :
106 template_url_service_->GetTemplateURLForKeyword(default_provider_);
107}
108
109const TemplateURL* SearchProvider::Providers::GetKeywordProviderURL() const {
110 return keyword_provider_.empty() ? NULL :
111 template_url_service_->GetTemplateURLForKeyword(keyword_provider_);
[email protected]257ab712009-04-14 17:16:24112}
113
[email protected]3954c3a2012-04-10 20:17:55114
[email protected]bc8bb0cd2013-06-24 21:50:23115// SearchProvider::CompareScoredResults ---------------------------------------
116
117class SearchProvider::CompareScoredResults {
118 public:
[email protected]0b9575f2014-07-30 11:58:37119 bool operator()(const SearchSuggestionParser::Result& a,
120 const SearchSuggestionParser::Result& b) {
[email protected]bc8bb0cd2013-06-24 21:50:23121 // Sort in descending relevance order.
122 return a.relevance() > b.relevance();
123 }
124};
125
126
[email protected]3954c3a2012-04-10 20:17:55127// SearchProvider -------------------------------------------------------------
128
129// static
[email protected]24dbf2302013-04-05 16:59:25130int SearchProvider::kMinimumTimeBetweenSuggestQueriesMs = 100;
[email protected]3954c3a2012-04-10 20:17:55131
[email protected]bc8bb0cd2013-06-24 21:50:23132SearchProvider::SearchProvider(AutocompleteProviderListener* listener,
[email protected]e6477f12014-08-05 07:59:54133 TemplateURLService* template_url_service,
[email protected]bc8bb0cd2013-06-24 21:50:23134 Profile* profile)
[email protected]776ee5902014-08-11 09:15:19135 : BaseSearchProvider(template_url_service, profile,
[email protected]e6477f12014-08-05 07:59:54136 AutocompleteProvider::TYPE_SEARCH),
[email protected]776ee5902014-08-11 09:15:19137 listener_(listener),
138 suggest_results_pending_(0),
[email protected]e6477f12014-08-05 07:59:54139 providers_(template_url_service) {
[email protected]bc8bb0cd2013-06-24 21:50:23140}
141
[email protected]cb86ee6f2013-04-28 16:58:15142// static
[email protected]987fad782013-08-28 06:23:18143std::string SearchProvider::GetSuggestMetadata(const AutocompleteMatch& match) {
144 return match.GetAdditionalInfo(kSuggestMetadataKey);
145}
146
[email protected]bc8bb0cd2013-06-24 21:50:23147void SearchProvider::ResetSession() {
148 field_trial_triggered_in_session_ = false;
[email protected]4ab4c7c2010-11-24 04:49:34149}
150
[email protected]bc8bb0cd2013-06-24 21:50:23151SearchProvider::~SearchProvider() {
152}
153
[email protected]ee6110b2014-01-09 22:26:31154// static
[email protected]bc8bb0cd2013-06-24 21:50:23155int SearchProvider::CalculateRelevanceForKeywordVerbatim(
[email protected]332d17d22014-06-20 16:56:03156 metrics::OmniboxInputType::Type type,
[email protected]bc8bb0cd2013-06-24 21:50:23157 bool prefer_keyword) {
158 // This function is responsible for scoring verbatim query matches
159 // for non-extension keywords. KeywordProvider::CalculateRelevance()
160 // scores verbatim query matches for extension keywords, as well as
161 // for keyword matches (i.e., suggestions of a keyword itself, not a
162 // suggestion of a query on a keyword search engine). These two
163 // functions are currently in sync, but there's no reason we
164 // couldn't decide in the future to score verbatim matches
165 // differently for extension and non-extension keywords. If you
166 // make such a change, however, you should update this comment to
167 // describe it, so it's clear why the functions diverge.
168 if (prefer_keyword)
169 return 1500;
[email protected]3dc75b12014-06-08 00:02:22170 return (type == metrics::OmniboxInputType::QUERY) ? 1450 : 1100;
[email protected]bc8bb0cd2013-06-24 21:50:23171}
172
initial.commit09911bf2008-07-26 23:55:29173void SearchProvider::Start(const AutocompleteInput& input,
[email protected]8deeb952008-10-09 18:21:27174 bool minimal_changes) {
[email protected]04504c242013-01-22 21:08:55175 // Do our best to load the model as early as possible. This will reduce
176 // odds of having the model not ready when really needed (a non-empty input).
177 TemplateURLService* model = providers_.template_url_service();
178 DCHECK(model);
179 model->Load();
180
initial.commit09911bf2008-07-26 23:55:29181 matches_.clear();
[email protected]618d6e62012-12-16 05:55:57182 field_trial_triggered_ = false;
initial.commit09911bf2008-07-26 23:55:29183
[email protected]6c85aa02009-02-27 12:08:09184 // Can't return search/suggest results for bogus input or without a profile.
[email protected]3dc75b12014-06-08 00:02:22185 if (!profile_ || (input.type() == metrics::OmniboxInputType::INVALID)) {
[email protected]9950e5d52014-02-25 23:34:19186 Stop(true);
initial.commit09911bf2008-07-26 23:55:29187 return;
188 }
189
[email protected]14710852013-02-05 23:45:41190 keyword_input_ = input;
[email protected]257ab712009-04-14 17:16:24191 const TemplateURL* keyword_provider =
[email protected]14710852013-02-05 23:45:41192 KeywordProvider::GetSubstitutingTemplateURLForInput(model,
193 &keyword_input_);
194 if (keyword_provider == NULL)
195 keyword_input_.Clear();
196 else if (keyword_input_.text().empty())
[email protected]257ab712009-04-14 17:16:24197 keyword_provider = NULL;
[email protected]257ab712009-04-14 17:16:24198
[email protected]85b8d6f2012-05-08 20:53:47199 const TemplateURL* default_provider = model->GetDefaultSearchProvider();
[email protected]ce7ee5f2014-06-16 23:41:19200 if (default_provider &&
201 !default_provider->SupportsReplacement(model->search_terms_data()))
[email protected]257ab712009-04-14 17:16:24202 default_provider = NULL;
203
204 if (keyword_provider == default_provider)
[email protected]e17511f2011-07-13 14:09:18205 default_provider = NULL; // No use in querying the same provider twice.
[email protected]257ab712009-04-14 17:16:24206
207 if (!default_provider && !keyword_provider) {
208 // No valid providers.
[email protected]9950e5d52014-02-25 23:34:19209 Stop(true);
initial.commit09911bf2008-07-26 23:55:29210 return;
211 }
212
213 // If we're still running an old query but have since changed the query text
[email protected]257ab712009-04-14 17:16:24214 // or the providers, abort the query.
[email protected]0085863a2013-12-06 21:19:03215 base::string16 default_provider_keyword(default_provider ?
216 default_provider->keyword() : base::string16());
217 base::string16 keyword_provider_keyword(keyword_provider ?
218 keyword_provider->keyword() : base::string16());
[email protected]9e789742011-01-10 23:27:32219 if (!minimal_changes ||
[email protected]85b8d6f2012-05-08 20:53:47220 !providers_.equal(default_provider_keyword, keyword_provider_keyword)) {
[email protected]bb900e02013-03-14 14:15:29221 // Cancel any in-flight suggest requests.
[email protected]e1290ee62013-06-26 18:31:15222 if (!done_)
[email protected]e29249dc52012-07-19 17:33:50223 Stop(false);
[email protected]257ab712009-04-14 17:16:24224 }
initial.commit09911bf2008-07-26 23:55:29225
[email protected]85b8d6f2012-05-08 20:53:47226 providers_.set(default_provider_keyword, keyword_provider_keyword);
initial.commit09911bf2008-07-26 23:55:29227
228 if (input.text().empty()) {
229 // User typed "?" alone. Give them a placeholder result indicating what
230 // this syntax does.
[email protected]257ab712009-04-14 17:16:24231 if (default_provider) {
[email protected]69c579e2010-04-23 20:01:00232 AutocompleteMatch match;
233 match.provider = this;
[email protected]a2fedb1e2011-01-25 15:23:36234 match.contents.assign(l10n_util::GetStringUTF16(IDS_EMPTY_KEYWORD_VALUE));
[email protected]257ab712009-04-14 17:16:24235 match.contents_class.push_back(
[email protected]2c33dd22010-02-11 21:46:35236 ACMatchClassification(0, ACMatchClassification::NONE));
[email protected]85b8d6f2012-05-08 20:53:47237 match.keyword = providers_.default_provider();
[email protected]45f89a92013-08-12 13:41:36238 match.allowed_to_be_default_match = true;
[email protected]257ab712009-04-14 17:16:24239 matches_.push_back(match);
240 }
[email protected]9950e5d52014-02-25 23:34:19241 Stop(true);
initial.commit09911bf2008-07-26 23:55:29242 return;
243 }
244
245 input_ = input;
246
[email protected]e1290ee62013-06-26 18:31:15247 DoHistoryQuery(minimal_changes);
[email protected]2ef2a6642014-07-30 05:50:29248 DoAnswersQuery(input);
[email protected]e1290ee62013-06-26 18:31:15249 StartOrStopSuggestQuery(minimal_changes);
[email protected]344946a12012-12-20 12:03:42250 UpdateMatches();
initial.commit09911bf2008-07-26 23:55:29251}
252
[email protected]776ee5902014-08-11 09:15:19253const TemplateURL* SearchProvider::GetTemplateURL(bool is_keyword) const {
254 return is_keyword ? providers_.GetKeywordProviderURL()
255 : providers_.GetDefaultProviderURL();
256}
257
258const AutocompleteInput SearchProvider::GetInput(bool is_keyword) const {
259 return is_keyword ? keyword_input_ : input_;
260}
261
262bool SearchProvider::ShouldAppendExtraParams(
263 const SearchSuggestionParser::SuggestResult& result) const {
264 return !result.from_keyword_provider() ||
265 providers_.default_provider().empty();
266}
267
268void SearchProvider::StopSuggest() {
269 // Increment the appropriate field in the histogram by the number of
270 // pending requests that were invalidated.
271 for (int i = 0; i < suggest_results_pending_; ++i)
272 LogOmniboxSuggestRequest(REQUEST_INVALIDATED);
273 suggest_results_pending_ = 0;
274 timer_.Stop();
275 // Stop any in-progress URL fetches.
276 keyword_fetcher_.reset();
277 default_fetcher_.reset();
278}
279
280void SearchProvider::ClearAllResults() {
281 keyword_results_.Clear();
282 default_results_.Clear();
283}
284
285void SearchProvider::RecordDeletionResult(bool success) {
286 if (success) {
287 base::RecordAction(
288 base::UserMetricsAction("Omnibox.ServerSuggestDelete.Success"));
289 } else {
290 base::RecordAction(
291 base::UserMetricsAction("Omnibox.ServerSuggestDelete.Failure"));
292 }
293}
294
295void SearchProvider::OnURLFetchComplete(const net::URLFetcher* source) {
296 DCHECK(!done_);
297 --suggest_results_pending_;
298 DCHECK_GE(suggest_results_pending_, 0); // Should never go negative.
299
300 const bool is_keyword = source == keyword_fetcher_.get();
301
302 // Ensure the request succeeded and that the provider used is still available.
303 // A verbatim match cannot be generated without this provider, causing errors.
304 const bool request_succeeded =
305 source->GetStatus().is_success() && (source->GetResponseCode() == 200) &&
306 GetTemplateURL(is_keyword);
307
308 LogFetchComplete(request_succeeded, is_keyword);
309
310 bool results_updated = false;
311 if (request_succeeded) {
312 scoped_ptr<base::Value> data(SearchSuggestionParser::DeserializeJsonData(
313 SearchSuggestionParser::ExtractJsonData(source)));
314 if (data) {
315 SearchSuggestionParser::Results* results =
316 is_keyword ? &keyword_results_ : &default_results_;
317 results_updated = ParseSuggestResults(*data, -1, is_keyword, results);
318 if (results_updated)
319 SortResults(is_keyword, results);
320 }
321 }
322 UpdateMatches();
323 if (done_ || results_updated)
324 listener_->OnProviderUpdate(results_updated);
325}
326
327void SearchProvider::UpdateMatchContentsClass(
328 const base::string16& input_text,
329 SearchSuggestionParser::Results* results) {
330 for (SearchSuggestionParser::SuggestResults::iterator sug_it =
331 results->suggest_results.begin();
332 sug_it != results->suggest_results.end(); ++sug_it) {
333 sug_it->ClassifyMatchContents(false, input_text);
334 }
335 const std::string languages(
336 profile_->GetPrefs()->GetString(prefs::kAcceptLanguages));
337 for (SearchSuggestionParser::NavigationResults::iterator nav_it =
338 results->navigation_results.begin();
339 nav_it != results->navigation_results.end(); ++nav_it) {
340 nav_it->CalculateAndClassifyMatchContents(false, input_text, languages);
341 }
342}
343
[email protected]d4a94b92014-03-04 01:35:22344void SearchProvider::SortResults(bool is_keyword,
[email protected]0b9575f2014-07-30 11:58:37345 SearchSuggestionParser::Results* results) {
[email protected]d4a94b92014-03-04 01:35:22346 // Ignore suggested scores for non-keyword matches in keyword mode; if the
347 // server is allowed to score these, it could interfere with the user's
348 // ability to get good keyword results.
349 const bool abandon_suggested_scores =
350 !is_keyword && !providers_.keyword_provider().empty();
[email protected]0b9575f2014-07-30 11:58:37351 // Apply calculated relevance scores to suggestions if valid relevances were
[email protected]d4a94b92014-03-04 01:35:22352 // not provided or we're abandoning suggested scores entirely.
[email protected]2c802d12014-07-31 12:57:14353 if (!results->relevances_from_server || abandon_suggested_scores) {
[email protected]d4a94b92014-03-04 01:35:22354 ApplyCalculatedSuggestRelevance(&results->suggest_results);
355 ApplyCalculatedNavigationRelevance(&results->navigation_results);
356 // If abandoning scores entirely, also abandon the verbatim score.
357 if (abandon_suggested_scores)
358 results->verbatim_relevance = -1;
359 }
360
361 // Keep the result lists sorted.
362 const CompareScoredResults comparator = CompareScoredResults();
363 std::stable_sort(results->suggest_results.begin(),
364 results->suggest_results.end(),
365 comparator);
366 std::stable_sort(results->navigation_results.begin(),
367 results->navigation_results.end(),
368 comparator);
369}
370
[email protected]cfa164bf2014-03-19 11:51:15371void SearchProvider::LogFetchComplete(bool success, bool is_keyword) {
372 LogOmniboxSuggestRequest(REPLY_RECEIVED);
373 // Record response time for suggest requests sent to Google. We care
374 // only about the common case: the Google default provider used in
375 // non-keyword mode.
376 const TemplateURL* default_url = providers_.GetDefaultProviderURL();
377 if (!is_keyword && default_url &&
[email protected]ce7ee5f2014-06-16 23:41:19378 (TemplateURLPrepopulateData::GetEngineType(
379 *default_url,
380 providers_.template_url_service()->search_terms_data()) ==
[email protected]cfa164bf2014-03-19 11:51:15381 SEARCH_ENGINE_GOOGLE)) {
382 const base::TimeDelta elapsed_time =
383 base::TimeTicks::Now() - time_suggest_request_sent_;
384 if (success) {
385 UMA_HISTOGRAM_TIMES("Omnibox.SuggestRequest.Success.GoogleResponseTime",
386 elapsed_time);
387 } else {
388 UMA_HISTOGRAM_TIMES("Omnibox.SuggestRequest.Failure.GoogleResponseTime",
389 elapsed_time);
390 }
391 }
392}
393
[email protected]cfa164bf2014-03-19 11:51:15394void SearchProvider::UpdateMatches() {
[email protected]cfa164bf2014-03-19 11:51:15395 ConvertResultsToAutocompleteMatches();
396
397 // Check constraints that may be violated by suggested relevances.
398 if (!matches_.empty() &&
399 (default_results_.HasServerProvidedScores() ||
400 keyword_results_.HasServerProvidedScores())) {
401 // These blocks attempt to repair undesirable behavior by suggested
402 // relevances with minimal impact, preserving other suggested relevances.
403
[email protected]cfa164bf2014-03-19 11:51:15404 if (!HasKeywordDefaultMatchInKeywordMode()) {
405 // In keyword mode, disregard the keyword verbatim suggested relevance
406 // if necessary so there at least one keyword match that's allowed to
407 // be the default match.
408 keyword_results_.verbatim_relevance = -1;
409 ConvertResultsToAutocompleteMatches();
410 }
[email protected]89bd27d12014-04-12 17:36:23411 if (IsTopMatchSearchWithURLInput()) {
[email protected]cfa164bf2014-03-19 11:51:15412 // Disregard the suggested search and verbatim relevances if the input
413 // type is URL and the top match is a highly-ranked search suggestion.
414 // For example, prevent a search for "foo.com" from outranking another
415 // provider's navigation for "foo.com" or "foo.com/url_from_history".
416 ApplyCalculatedSuggestRelevance(&keyword_results_.suggest_results);
417 ApplyCalculatedSuggestRelevance(&default_results_.suggest_results);
418 default_results_.verbatim_relevance = -1;
419 keyword_results_.verbatim_relevance = -1;
420 ConvertResultsToAutocompleteMatches();
421 }
[email protected]89bd27d12014-04-12 17:36:23422 if (FindTopMatch() == matches_.end()) {
423 // Guarantee that SearchProvider returns a legal default match. (The
424 // omnibox always needs at least one legal default match, and it relies
425 // on SearchProvider to always return one.)
[email protected]cfa164bf2014-03-19 11:51:15426 ApplyCalculatedRelevance();
427 ConvertResultsToAutocompleteMatches();
428 }
[email protected]cfa164bf2014-03-19 11:51:15429 DCHECK(HasKeywordDefaultMatchInKeywordMode());
[email protected]89bd27d12014-04-12 17:36:23430 DCHECK(!IsTopMatchSearchWithURLInput());
431 DCHECK(FindTopMatch() != matches_.end());
[email protected]cfa164bf2014-03-19 11:51:15432 }
433 UMA_HISTOGRAM_CUSTOM_COUNTS(
434 "Omnibox.SearchProviderMatches", matches_.size(), 1, 6, 7);
435
436 const TemplateURL* keyword_url = providers_.GetKeywordProviderURL();
437 if ((keyword_url != NULL) && HasKeywordDefaultMatchInKeywordMode()) {
438 // If there is a keyword match that is allowed to be the default match,
439 // then prohibit default provider matches from being the default match lest
440 // such matches cause the user to break out of keyword mode.
441 for (ACMatches::iterator it = matches_.begin(); it != matches_.end();
442 ++it) {
443 if (it->keyword != keyword_url->keyword())
444 it->allowed_to_be_default_match = false;
445 }
446 }
[email protected]cfa164bf2014-03-19 11:51:15447 UpdateDone();
[email protected]cfa164bf2014-03-19 11:51:15448}
449
[email protected]bc8bb0cd2013-06-24 21:50:23450void SearchProvider::Run() {
451 // Start a new request with the current input.
452 suggest_results_pending_ = 0;
453 time_suggest_request_sent_ = base::TimeTicks::Now();
[email protected]abe441e2013-05-06 12:35:05454
[email protected]bc8bb0cd2013-06-24 21:50:23455 default_fetcher_.reset(CreateSuggestFetcher(kDefaultProviderURLFetcherID,
456 providers_.GetDefaultProviderURL(), input_));
457 keyword_fetcher_.reset(CreateSuggestFetcher(kKeywordProviderURLFetcherID,
458 providers_.GetKeywordProviderURL(), keyword_input_));
459
460 // Both the above can fail if the providers have been modified or deleted
461 // since the query began.
462 if (suggest_results_pending_ == 0) {
463 UpdateDone();
464 // We only need to update the listener if we're actually done.
465 if (done_)
466 listener_->OnProviderUpdate(false);
467 }
[email protected]601858c02010-09-01 17:08:20468}
469
[email protected]8d457132010-11-04 18:13:40470void SearchProvider::DoHistoryQuery(bool minimal_changes) {
471 // The history query results are synchronous, so if minimal_changes is true,
472 // we still have the last results and don't need to do anything.
473 if (minimal_changes)
initial.commit09911bf2008-07-26 23:55:29474 return;
475
[email protected]8d457132010-11-04 18:13:40476 keyword_history_results_.clear();
477 default_history_results_.clear();
initial.commit09911bf2008-07-26 23:55:29478
[email protected]78e5e432013-08-03 02:10:10479 if (OmniboxFieldTrial::SearchHistoryDisable(
480 input_.current_page_classification()))
[email protected]d8cd76b2013-07-10 09:46:16481 return;
482
[email protected]8d457132010-11-04 18:13:40483 HistoryService* const history_service =
[email protected]9d2db762012-06-19 00:01:10484 HistoryServiceFactory::GetForProfile(profile_, Profile::EXPLICIT_ACCESS);
[email protected]8d457132010-11-04 18:13:40485 history::URLDatabase* url_db = history_service ?
486 history_service->InMemoryDatabase() : NULL;
487 if (!url_db)
initial.commit09911bf2008-07-26 23:55:29488 return;
489
[email protected]51124552011-07-16 01:37:10490 // Request history for both the keyword and default provider. We grab many
491 // more matches than we'll ultimately clamp to so that if there are several
492 // recent multi-word matches who scores are lowered (see
493 // AddHistoryResultsToMap()), they won't crowd out older, higher-scoring
494 // matches. Note that this doesn't fix the problem entirely, but merely
495 // limits it to cases with a very large number of such multi-word matches; for
496 // now, this seems OK compared with the complexity of a real fix, which would
497 // require multiple searches and tracking of "single- vs. multi-word" in the
498 // database.
499 int num_matches = kMaxMatches * 5;
[email protected]85b8d6f2012-05-08 20:53:47500 const TemplateURL* default_url = providers_.GetDefaultProviderURL();
501 if (default_url) {
[email protected]b4bec972014-04-05 18:07:15502 const base::TimeTicks start_time = base::TimeTicks::Now();
[email protected]85b8d6f2012-05-08 20:53:47503 url_db->GetMostRecentKeywordSearchTerms(default_url->id(), input_.text(),
504 num_matches, &default_history_results_);
[email protected]31afdf72013-09-26 04:29:36505 UMA_HISTOGRAM_TIMES(
506 "Omnibox.SearchProvider.GetMostRecentKeywordTermsDefaultProviderTime",
507 base::TimeTicks::Now() - start_time);
[email protected]257ab712009-04-14 17:16:24508 }
[email protected]85b8d6f2012-05-08 20:53:47509 const TemplateURL* keyword_url = providers_.GetKeywordProviderURL();
510 if (keyword_url) {
511 url_db->GetMostRecentKeywordSearchTerms(keyword_url->id(),
[email protected]14710852013-02-05 23:45:41512 keyword_input_.text(), num_matches, &keyword_history_results_);
[email protected]3954c3a2012-04-10 20:17:55513 }
initial.commit09911bf2008-07-26 23:55:29514}
515
[email protected]6dc950f2012-07-16 19:49:08516void SearchProvider::StartOrStopSuggestQuery(bool minimal_changes) {
[email protected]83c726482008-09-10 06:36:34517 if (!IsQuerySuitableForSuggest()) {
initial.commit09911bf2008-07-26 23:55:29518 StopSuggest();
[email protected]71b46152013-05-03 16:39:20519 ClearAllResults();
initial.commit09911bf2008-07-26 23:55:29520 return;
521 }
522
523 // For the minimal_changes case, if we finished the previous query and still
524 // have its results, or are allowed to keep running it, just do that, rather
525 // than starting a new query.
526 if (minimal_changes &&
[email protected]cc1526e2013-05-17 04:04:24527 (!default_results_.suggest_results.empty() ||
528 !default_results_.navigation_results.empty() ||
529 !keyword_results_.suggest_results.empty() ||
530 !keyword_results_.navigation_results.empty() ||
[email protected]a2770a7d2014-04-22 19:33:35531 (!done_ && input_.want_asynchronous_matches())))
initial.commit09911bf2008-07-26 23:55:29532 return;
533
534 // We can't keep running any previous query, so halt it.
535 StopSuggest();
[email protected]d1f0a7f2012-06-05 10:26:42536
537 // Remove existing results that cannot inline autocomplete the new input.
[email protected]71b46152013-05-03 16:39:20538 RemoveAllStaleResults();
initial.commit09911bf2008-07-26 23:55:29539
[email protected]ee6110b2014-01-09 22:26:31540 // Update the content classifications of remaining results so they look good
541 // against the current input.
[email protected]23db6492014-01-16 02:35:30542 UpdateMatchContentsClass(input_.text(), &default_results_);
543 if (!keyword_input_.text().empty())
544 UpdateMatchContentsClass(keyword_input_.text(), &keyword_results_);
[email protected]ee6110b2014-01-09 22:26:31545
initial.commit09911bf2008-07-26 23:55:29546 // We can't start a new query if we're only allowed synchronous results.
[email protected]a2770a7d2014-04-22 19:33:35547 if (!input_.want_asynchronous_matches())
initial.commit09911bf2008-07-26 23:55:29548 return;
549
[email protected]24dbf2302013-04-05 16:59:25550 // To avoid flooding the suggest server, don't send a query until at
551 // least 100 ms since the last query.
[email protected]515ffa942012-11-27 20:18:24552 base::TimeTicks next_suggest_time(time_suggest_request_sent_ +
[email protected]bc8bb0cd2013-06-24 21:50:23553 base::TimeDelta::FromMilliseconds(kMinimumTimeBetweenSuggestQueriesMs));
[email protected]515ffa942012-11-27 20:18:24554 base::TimeTicks now(base::TimeTicks::Now());
555 if (now >= next_suggest_time) {
556 Run();
557 return;
558 }
559 timer_.Start(FROM_HERE, next_suggest_time - now, this, &SearchProvider::Run);
initial.commit09911bf2008-07-26 23:55:29560}
561
[email protected]83c726482008-09-10 06:36:34562bool SearchProvider::IsQuerySuitableForSuggest() const {
[email protected]3954c3a2012-04-10 20:17:55563 // Don't run Suggest in incognito mode, if the engine doesn't support it, or
564 // if the user has disabled it.
[email protected]85b8d6f2012-05-08 20:53:47565 const TemplateURL* default_url = providers_.GetDefaultProviderURL();
566 const TemplateURL* keyword_url = providers_.GetKeywordProviderURL();
[email protected]83c726482008-09-10 06:36:34567 if (profile_->IsOffTheRecord() ||
[email protected]85b8d6f2012-05-08 20:53:47568 ((!default_url || default_url->suggestions_url().empty()) &&
569 (!keyword_url || keyword_url->suggestions_url().empty())) ||
[email protected]83c726482008-09-10 06:36:34570 !profile_->GetPrefs()->GetBoolean(prefs::kSearchSuggestEnabled))
571 return false;
572
[email protected]cac59d32010-08-09 23:23:14573 // If the input type might be a URL, we take extra care so that private data
[email protected]83c726482008-09-10 06:36:34574 // isn't sent to the server.
[email protected]83c726482008-09-10 06:36:34575
[email protected]cac59d32010-08-09 23:23:14576 // FORCED_QUERY means the user is explicitly asking us to search for this, so
577 // we assume it isn't a URL and/or there isn't private data.
[email protected]3dc75b12014-06-08 00:02:22578 if (input_.type() == metrics::OmniboxInputType::FORCED_QUERY)
[email protected]cac59d32010-08-09 23:23:14579 return true;
[email protected]83c726482008-09-10 06:36:34580
[email protected]f608ea102013-03-18 15:08:09581 // Next we check the scheme. If this is UNKNOWN/URL with a scheme that isn't
582 // http/https/ftp, we shouldn't send it. Sending things like file: and data:
583 // is both a waste of time and a disclosure of potentially private, local
584 // data. Other "schemes" may actually be usernames, and we don't want to send
585 // passwords. If the scheme is OK, we still need to check other cases below.
586 // If this is QUERY, then the presence of these schemes means the user
587 // explicitly typed one, and thus this is probably a URL that's being entered
588 // and happens to currently be invalid -- in which case we again want to run
589 // our checks below. Other QUERY cases are less likely to be URLs and thus we
590 // assume we're OK.
[email protected]df807042014-08-13 16:48:41591 if (!LowerCaseEqualsASCII(input_.scheme(), url::kHttpScheme) &&
592 !LowerCaseEqualsASCII(input_.scheme(), url::kHttpsScheme) &&
593 !LowerCaseEqualsASCII(input_.scheme(), url::kFtpScheme))
[email protected]3dc75b12014-06-08 00:02:22594 return (input_.type() == metrics::OmniboxInputType::QUERY);
[email protected]cac59d32010-08-09 23:23:14595
596 // Don't send URLs with usernames, queries or refs. Some of these are
597 // private, and the Suggest server is unlikely to have any useful results
598 // for any of them. Also don't send URLs with ports, as we may initially
599 // think that a username + password is a host + port (and we don't want to
600 // send usernames/passwords), and even if the port really is a port, the
601 // server is once again unlikely to have and useful results.
[email protected]825e16f2013-09-30 23:52:58602 // Note that we only block based on refs if the input is URL-typed, as search
603 // queries can legitimately have #s in them which the URL parser
604 // overaggressively categorizes as a url with a ref.
[email protected]b45334502014-04-30 19:44:05605 const url::Parsed& parts = input_.parts();
[email protected]cac59d32010-08-09 23:23:14606 if (parts.username.is_nonempty() || parts.port.is_nonempty() ||
[email protected]825e16f2013-09-30 23:52:58607 parts.query.is_nonempty() ||
[email protected]3dc75b12014-06-08 00:02:22608 (parts.ref.is_nonempty() &&
609 (input_.type() == metrics::OmniboxInputType::URL)))
[email protected]cac59d32010-08-09 23:23:14610 return false;
611
612 // Don't send anything for https except the hostname. Hostnames are OK
613 // because they are visible when the TCP connection is established, but the
614 // specific path may reveal private information.
[email protected]df807042014-08-13 16:48:41615 if (LowerCaseEqualsASCII(input_.scheme(), url::kHttpsScheme) &&
[email protected]a2fedb1e2011-01-25 15:23:36616 parts.path.is_nonempty())
[email protected]cac59d32010-08-09 23:23:14617 return false;
[email protected]83c726482008-09-10 06:36:34618
619 return true;
620}
621
[email protected]71b46152013-05-03 16:39:20622void SearchProvider::RemoveAllStaleResults() {
[email protected]dc735c02013-11-12 23:23:41623 if (keyword_input_.text().empty()) {
[email protected]1e1550e2013-05-02 17:37:51624 // User is either in keyword mode with a blank input or out of
625 // keyword mode entirely.
[email protected]cc1526e2013-05-17 04:04:24626 keyword_results_.Clear();
[email protected]1e1550e2013-05-02 17:37:51627 }
[email protected]d1f0a7f2012-06-05 10:26:42628}
629
[email protected]d1f0a7f2012-06-05 10:26:42630void SearchProvider::ApplyCalculatedRelevance() {
[email protected]cc1526e2013-05-17 04:04:24631 ApplyCalculatedSuggestRelevance(&keyword_results_.suggest_results);
632 ApplyCalculatedSuggestRelevance(&default_results_.suggest_results);
633 ApplyCalculatedNavigationRelevance(&keyword_results_.navigation_results);
634 ApplyCalculatedNavigationRelevance(&default_results_.navigation_results);
[email protected]cc1526e2013-05-17 04:04:24635 default_results_.verbatim_relevance = -1;
636 keyword_results_.verbatim_relevance = -1;
[email protected]d1f0a7f2012-06-05 10:26:42637}
638
[email protected]0b9575f2014-07-30 11:58:37639void SearchProvider::ApplyCalculatedSuggestRelevance(
640 SearchSuggestionParser::SuggestResults* list) {
[email protected]d1f0a7f2012-06-05 10:26:42641 for (size_t i = 0; i < list->size(); ++i) {
[email protected]0b9575f2014-07-30 11:58:37642 SearchSuggestionParser::SuggestResult& result = (*list)[i];
[email protected]188b50c2013-03-28 07:19:42643 result.set_relevance(
644 result.CalculateRelevance(input_, providers_.has_keyword_provider()) +
645 (list->size() - i - 1));
[email protected]d30268a2013-06-25 22:31:07646 result.set_relevance_from_server(false);
[email protected]d1f0a7f2012-06-05 10:26:42647 }
648}
649
[email protected]188b50c2013-03-28 07:19:42650void SearchProvider::ApplyCalculatedNavigationRelevance(
[email protected]0b9575f2014-07-30 11:58:37651 SearchSuggestionParser::NavigationResults* list) {
[email protected]d1f0a7f2012-06-05 10:26:42652 for (size_t i = 0; i < list->size(); ++i) {
[email protected]0b9575f2014-07-30 11:58:37653 SearchSuggestionParser::NavigationResult& result = (*list)[i];
[email protected]188b50c2013-03-28 07:19:42654 result.set_relevance(
655 result.CalculateRelevance(input_, providers_.has_keyword_provider()) +
656 (list->size() - i - 1));
[email protected]d30268a2013-06-25 22:31:07657 result.set_relevance_from_server(false);
[email protected]d1f0a7f2012-06-05 10:26:42658 }
659}
660
[email protected]15fb2aa2012-05-22 22:52:59661net::URLFetcher* SearchProvider::CreateSuggestFetcher(
[email protected]7cc6e5632011-10-25 17:56:12662 int id,
[email protected]9ff91722012-09-07 05:29:12663 const TemplateURL* template_url,
[email protected]14710852013-02-05 23:45:41664 const AutocompleteInput& input) {
[email protected]9ff91722012-09-07 05:29:12665 if (!template_url || template_url->suggestions_url().empty())
666 return NULL;
667
668 // Bail if the suggestion URL is invalid with the given replacements.
[email protected]14710852013-02-05 23:45:41669 TemplateURLRef::SearchTermsArgs search_term_args(input.text());
[email protected]420472b22014-06-10 13:34:43670 search_term_args.input_type = input.type();
[email protected]14710852013-02-05 23:45:41671 search_term_args.cursor_position = input.cursor_position();
[email protected]d5015ca2013-08-08 22:04:18672 search_term_args.page_classification = input.current_page_classification();
[email protected]2ef2a6642014-07-30 05:50:29673 if (OmniboxFieldTrial::EnableAnswersInSuggest()) {
[email protected]20184242014-05-14 02:57:42674 search_term_args.session_token = GetSessionToken();
[email protected]2ef2a6642014-07-30 05:50:29675 if (!prefetch_data_.full_query_text.empty()) {
676 search_term_args.prefetch_query =
677 base::UTF16ToUTF8(last_answer_seen_.full_query_text);
678 search_term_args.prefetch_query_type =
679 base::UTF16ToUTF8(last_answer_seen_.query_type);
680 }
681 }
[email protected]9ff91722012-09-07 05:29:12682 GURL suggest_url(template_url->suggestions_url_ref().ReplaceSearchTerms(
[email protected]ce7ee5f2014-06-16 23:41:19683 search_term_args,
684 providers_.template_url_service()->search_terms_data()));
[email protected]9ff91722012-09-07 05:29:12685 if (!suggest_url.is_valid())
686 return NULL;
[email protected]9b9fa672013-11-07 06:04:52687 // Send the current page URL if user setting and URL requirements are met and
688 // the user is in the field trial.
689 if (CanSendURL(current_page_url_, suggest_url, template_url,
[email protected]e6477f12014-08-05 07:59:54690 input.current_page_classification(),
691 template_url_service_->search_terms_data(), profile_) &&
[email protected]9b9fa672013-11-07 06:04:52692 OmniboxFieldTrial::InZeroSuggestAfterTypingFieldTrial()) {
693 search_term_args.current_page_url = current_page_url_.spec();
694 // Create the suggest URL again with the current page URL.
695 suggest_url = GURL(template_url->suggestions_url_ref().ReplaceSearchTerms(
[email protected]ce7ee5f2014-06-16 23:41:19696 search_term_args,
697 providers_.template_url_service()->search_terms_data()));
[email protected]9b9fa672013-11-07 06:04:52698 }
[email protected]9ff91722012-09-07 05:29:12699
700 suggest_results_pending_++;
701 LogOmniboxSuggestRequest(REQUEST_SENT);
702
703 net::URLFetcher* fetcher =
704 net::URLFetcher::Create(id, suggest_url, net::URLFetcher::GET, this);
[email protected]7cc6e5632011-10-25 17:56:12705 fetcher->SetRequestContext(profile_->GetRequestContext());
[email protected]d3cf8682f02012-02-29 23:29:34706 fetcher->SetLoadFlags(net::LOAD_DO_NOT_SAVE_COOKIES);
[email protected]bd3b4712012-12-18 17:01:30707 // Add Chrome experiment state to the request headers.
708 net::HttpRequestHeaders headers;
[email protected]71011c1682014-07-09 17:19:16709 variations::VariationsHttpHeaderProvider::GetInstance()->AppendHeaders(
[email protected]bd3b4712012-12-18 17:01:30710 fetcher->GetOriginalURL(), profile_->IsOffTheRecord(), false, &headers);
711 fetcher->SetExtraRequestHeaders(headers.ToString());
[email protected]257ab712009-04-14 17:16:24712 fetcher->Start();
713 return fetcher;
714}
715
[email protected]344946a12012-12-20 12:03:42716void SearchProvider::ConvertResultsToAutocompleteMatches() {
initial.commit09911bf2008-07-26 23:55:29717 // Convert all the results to matches and add them to a map, so we can keep
718 // the most relevant match for each result.
[email protected]31afdf72013-09-26 04:29:36719 base::TimeTicks start_time(base::TimeTicks::Now());
initial.commit09911bf2008-07-26 23:55:29720 MatchMap map;
[email protected]bc8bb0cd2013-06-24 21:50:23721 const base::Time no_time;
[email protected]cc1526e2013-05-17 04:04:24722 int did_not_accept_keyword_suggestion =
723 keyword_results_.suggest_results.empty() ?
initial.commit09911bf2008-07-26 23:55:29724 TemplateURLRef::NO_SUGGESTIONS_AVAILABLE :
725 TemplateURLRef::NO_SUGGESTION_CHOSEN;
initial.commit09911bf2008-07-26 23:55:29726
[email protected]d30268a2013-06-25 22:31:07727 bool relevance_from_server;
728 int verbatim_relevance = GetVerbatimRelevance(&relevance_from_server);
[email protected]cc1526e2013-05-17 04:04:24729 int did_not_accept_default_suggestion =
730 default_results_.suggest_results.empty() ?
[email protected]55ce8f12012-05-09 04:44:08731 TemplateURLRef::NO_SUGGESTIONS_AVAILABLE :
732 TemplateURLRef::NO_SUGGESTION_CHOSEN;
[email protected]d1f0a7f2012-06-05 10:26:42733 if (verbatim_relevance > 0) {
[email protected]c2ca3fd2014-03-22 03:07:44734 const base::string16& trimmed_verbatim =
735 base::CollapseWhitespace(input_.text(), false);
[email protected]0b9575f2014-07-30 11:58:37736 SearchSuggestionParser::SuggestResult verbatim(
[email protected]c2ca3fd2014-03-22 03:07:44737 trimmed_verbatim, AutocompleteMatchType::SEARCH_WHAT_YOU_TYPED,
[email protected]7ec287e2014-05-16 02:50:08738 trimmed_verbatim, base::string16(), base::string16(), base::string16(),
739 base::string16(), std::string(), std::string(), false,
740 verbatim_relevance, relevance_from_server, false,
[email protected]c2ca3fd2014-03-22 03:07:44741 trimmed_verbatim);
[email protected]57482a72014-03-14 22:27:37742 AddMatchToMap(verbatim, std::string(), did_not_accept_default_suggestion,
743 false, &map);
[email protected]d1f0a7f2012-06-05 10:26:42744 }
[email protected]5423e562013-02-07 03:58:45745 if (!keyword_input_.text().empty()) {
746 const TemplateURL* keyword_url = providers_.GetKeywordProviderURL();
747 // We only create the verbatim search query match for a keyword
748 // if it's not an extension keyword. Extension keywords are handled
749 // in KeywordProvider::Start(). (Extensions are complicated...)
750 // Note: in this provider, SEARCH_OTHER_ENGINE must correspond
751 // to the keyword verbatim search query. Do not create other matches
752 // of type SEARCH_OTHER_ENGINE.
[email protected]bdcbcd82013-10-28 13:40:25753 if (keyword_url &&
754 (keyword_url->GetType() != TemplateURL::OMNIBOX_API_EXTENSION)) {
[email protected]d30268a2013-06-25 22:31:07755 bool keyword_relevance_from_server;
756 const int keyword_verbatim_relevance =
757 GetKeywordVerbatimRelevance(&keyword_relevance_from_server);
[email protected]dab8d52d2013-03-05 07:35:28758 if (keyword_verbatim_relevance > 0) {
[email protected]c2ca3fd2014-03-22 03:07:44759 const base::string16& trimmed_verbatim =
760 base::CollapseWhitespace(keyword_input_.text(), false);
[email protected]0b9575f2014-07-30 11:58:37761 SearchSuggestionParser::SuggestResult verbatim(
[email protected]c2ca3fd2014-03-22 03:07:44762 trimmed_verbatim, AutocompleteMatchType::SEARCH_OTHER_ENGINE,
763 trimmed_verbatim, base::string16(), base::string16(),
[email protected]7ec287e2014-05-16 02:50:08764 base::string16(), base::string16(), std::string(), std::string(),
765 true, keyword_verbatim_relevance, keyword_relevance_from_server,
766 false, trimmed_verbatim);
[email protected]57482a72014-03-14 22:27:37767 AddMatchToMap(verbatim, std::string(),
768 did_not_accept_keyword_suggestion, false, &map);
[email protected]dab8d52d2013-03-05 07:35:28769 }
[email protected]5423e562013-02-07 03:58:45770 }
771 }
[email protected]257ab712009-04-14 17:16:24772 AddHistoryResultsToMap(keyword_history_results_, true,
773 did_not_accept_keyword_suggestion, &map);
774 AddHistoryResultsToMap(default_history_results_, false,
775 did_not_accept_default_suggestion, &map);
776
[email protected]d1cb6a822013-09-18 19:43:00777 AddSuggestResultsToMap(keyword_results_.suggest_results,
778 keyword_results_.metadata, &map);
[email protected]987fad782013-08-28 06:23:18779 AddSuggestResultsToMap(default_results_.suggest_results,
780 default_results_.metadata, &map);
initial.commit09911bf2008-07-26 23:55:29781
[email protected]d30268a2013-06-25 22:31:07782 ACMatches matches;
initial.commit09911bf2008-07-26 23:55:29783 for (MatchMap::const_iterator i(map.begin()); i != map.end(); ++i)
[email protected]d30268a2013-06-25 22:31:07784 matches.push_back(i->second);
initial.commit09911bf2008-07-26 23:55:29785
[email protected]d30268a2013-06-25 22:31:07786 AddNavigationResultsToMatches(keyword_results_.navigation_results, &matches);
787 AddNavigationResultsToMatches(default_results_.navigation_results, &matches);
initial.commit09911bf2008-07-26 23:55:29788
[email protected]d30268a2013-06-25 22:31:07789 // Now add the most relevant matches to |matches_|. We take up to kMaxMatches
790 // suggest/navsuggest matches, regardless of origin. If Instant Extended is
791 // enabled and we have server-provided (and thus hopefully more accurate)
792 // scores for some suggestions, we allow more of those, until we reach
793 // AutocompleteResult::kMaxMatches total matches (that is, enough to fill the
794 // whole popup).
795 //
796 // We will always return any verbatim matches, no matter how we obtained their
797 // scores, unless we have already accepted AutocompleteResult::kMaxMatches
798 // higher-scoring matches under the conditions above.
799 std::sort(matches.begin(), matches.end(), &AutocompleteMatch::MoreRelevant);
800 matches_.clear();
[email protected]3723e6e2012-06-11 21:06:56801
[email protected]d30268a2013-06-25 22:31:07802 size_t num_suggestions = 0;
803 for (ACMatches::const_iterator i(matches.begin());
804 (i != matches.end()) &&
805 (matches_.size() < AutocompleteResult::kMaxMatches);
806 ++i) {
807 // SEARCH_OTHER_ENGINE is only used in the SearchProvider for the keyword
808 // verbatim result, so this condition basically means "if this match is a
809 // suggestion of some sort".
810 if ((i->type != AutocompleteMatchType::SEARCH_WHAT_YOU_TYPED) &&
811 (i->type != AutocompleteMatchType::SEARCH_OTHER_ENGINE)) {
812 // If we've already hit the limit on non-server-scored suggestions, and
813 // this isn't a server-scored suggestion we can add, skip it.
814 if ((num_suggestions >= kMaxMatches) &&
815 (!chrome::IsInstantExtendedAPIEnabled() ||
816 (i->GetAdditionalInfo(kRelevanceFromServerKey) != kTrue))) {
817 continue;
818 }
819
820 ++num_suggestions;
821 }
822
823 matches_.push_back(*i);
824 }
[email protected]31afdf72013-09-26 04:29:36825 UMA_HISTOGRAM_TIMES("Omnibox.SearchProvider.ConvertResultsTime",
826 base::TimeTicks::Now() - start_time);
[email protected]344946a12012-12-20 12:03:42827}
828
[email protected]89bd27d12014-04-12 17:36:23829ACMatches::const_iterator SearchProvider::FindTopMatch() const {
[email protected]0a8718b12013-11-13 18:41:31830 ACMatches::const_iterator it = matches_.begin();
831 while ((it != matches_.end()) && !it->allowed_to_be_default_match)
832 ++it;
833 return it;
[email protected]9dfb4d362013-04-05 02:15:12834}
835
[email protected]1c1e7842013-11-22 16:28:16836bool SearchProvider::HasKeywordDefaultMatchInKeywordMode() const {
837 const TemplateURL* keyword_url = providers_.GetKeywordProviderURL();
838 // If the user is not in keyword mode, return true to say that this
839 // constraint is not violated.
840 if (keyword_url == NULL)
841 return true;
842 for (ACMatches::const_iterator it = matches_.begin(); it != matches_.end();
843 ++it) {
844 if ((it->keyword == keyword_url->keyword()) &&
845 it->allowed_to_be_default_match)
846 return true;
847 }
848 return false;
849}
850
[email protected]89bd27d12014-04-12 17:36:23851bool SearchProvider::IsTopMatchSearchWithURLInput() const {
852 ACMatches::const_iterator first_match = FindTopMatch();
[email protected]3dc75b12014-06-08 00:02:22853 return (input_.type() == metrics::OmniboxInputType::URL) &&
[email protected]0a8718b12013-11-13 18:41:31854 (first_match != matches_.end()) &&
855 (first_match->relevance > CalculateRelevanceForVerbatim()) &&
[email protected]78981d8c2014-05-09 15:05:47856 (first_match->type != AutocompleteMatchType::NAVSUGGEST) &&
857 (first_match->type != AutocompleteMatchType::NAVSUGGEST_PERSONALIZED);
[email protected]344946a12012-12-20 12:03:42858}
859
[email protected]257ab712009-04-14 17:16:24860void SearchProvider::AddNavigationResultsToMatches(
[email protected]0b9575f2014-07-30 11:58:37861 const SearchSuggestionParser::NavigationResults& navigation_results,
[email protected]d30268a2013-06-25 22:31:07862 ACMatches* matches) {
[email protected]0b9575f2014-07-30 11:58:37863 for (SearchSuggestionParser::NavigationResults::const_iterator it =
864 navigation_results.begin(); it != navigation_results.end(); ++it) {
[email protected]d30268a2013-06-25 22:31:07865 matches->push_back(NavigationToMatch(*it));
[email protected]bc8bb0cd2013-06-24 21:50:23866 // In the absence of suggested relevance scores, use only the single
867 // highest-scoring result. (The results are already sorted by relevance.)
[email protected]d30268a2013-06-25 22:31:07868 if (!it->relevance_from_server())
[email protected]bc8bb0cd2013-06-24 21:50:23869 return;
[email protected]257ab712009-04-14 17:16:24870 }
871}
872
873void SearchProvider::AddHistoryResultsToMap(const HistoryResults& results,
874 bool is_keyword,
875 int did_not_accept_suggestion,
876 MatchMap* map) {
[email protected]51124552011-07-16 01:37:10877 if (results.empty())
878 return;
879
[email protected]31afdf72013-09-26 04:29:36880 base::TimeTicks start_time(base::TimeTicks::Now());
[email protected]d7ad4772012-06-01 03:12:54881 bool prevent_inline_autocomplete = input_.prevent_inline_autocomplete() ||
[email protected]3dc75b12014-06-08 00:02:22882 (input_.type() == metrics::OmniboxInputType::URL);
[email protected]0085863a2013-12-06 21:19:03883 const base::string16& input_text =
[email protected]14710852013-02-05 23:45:41884 is_keyword ? keyword_input_.text() : input_.text();
[email protected]51124552011-07-16 01:37:10885 bool input_multiple_words = HasMultipleWords(input_text);
886
[email protected]0b9575f2014-07-30 11:58:37887 SearchSuggestionParser::SuggestResults scored_results;
[email protected]55ce8f12012-05-09 04:44:08888 if (!prevent_inline_autocomplete && input_multiple_words) {
889 // ScoreHistoryResults() allows autocompletion of multi-word, 1-visit
890 // queries if the input also has multiple words. But if we were already
[email protected]f13a2132014-04-22 08:13:52891 // scoring a multi-word, multi-visit query aggressively, and the current
892 // input is still a prefix of it, then changing the suggestion suddenly
893 // feels wrong. To detect this case, first score as if only one word has
894 // been typed, then check if the best result came from aggressive search
895 // history scoring. If it did, then just keep that score set. This
896 // 1200 the lowest possible score in CalculateRelevanceForHistory()'s
897 // aggressive-scoring curve.
[email protected]55ce8f12012-05-09 04:44:08898 scored_results = ScoreHistoryResults(results, prevent_inline_autocomplete,
899 false, input_text, is_keyword);
[email protected]f13a2132014-04-22 08:13:52900 if ((scored_results.front().relevance() < 1200) ||
[email protected]9dfb4d362013-04-05 02:15:12901 !HasMultipleWords(scored_results.front().suggestion()))
[email protected]55ce8f12012-05-09 04:44:08902 scored_results.clear(); // Didn't detect the case above, score normally.
[email protected]51124552011-07-16 01:37:10903 }
[email protected]55ce8f12012-05-09 04:44:08904 if (scored_results.empty())
905 scored_results = ScoreHistoryResults(results, prevent_inline_autocomplete,
906 input_multiple_words, input_text,
907 is_keyword);
[email protected]0b9575f2014-07-30 11:58:37908 for (SearchSuggestionParser::SuggestResults::const_iterator i(
909 scored_results.begin()); i != scored_results.end(); ++i) {
[email protected]57482a72014-03-14 22:27:37910 AddMatchToMap(*i, std::string(), did_not_accept_suggestion, true, map);
[email protected]51124552011-07-16 01:37:10911 }
[email protected]31afdf72013-09-26 04:29:36912 UMA_HISTOGRAM_TIMES("Omnibox.SearchProvider.AddHistoryResultsTime",
913 base::TimeTicks::Now() - start_time);
[email protected]51124552011-07-16 01:37:10914}
915
[email protected]0b9575f2014-07-30 11:58:37916SearchSuggestionParser::SuggestResults SearchProvider::ScoreHistoryResults(
[email protected]51124552011-07-16 01:37:10917 const HistoryResults& results,
918 bool base_prevent_inline_autocomplete,
919 bool input_multiple_words,
[email protected]0085863a2013-12-06 21:19:03920 const base::string16& input_text,
[email protected]51124552011-07-16 01:37:10921 bool is_keyword) {
[email protected]0b9575f2014-07-30 11:58:37922 SearchSuggestionParser::SuggestResults scored_results;
[email protected]ab5fd2f2014-07-17 19:18:52923 // True if the user has asked this exact query previously.
924 bool found_what_you_typed_match = false;
[email protected]78e5e432013-08-03 02:10:10925 const bool prevent_search_history_inlining =
926 OmniboxFieldTrial::SearchHistoryPreventInlining(
927 input_.current_page_classification());
[email protected]c2ca3fd2014-03-22 03:07:44928 const base::string16& trimmed_input =
929 base::CollapseWhitespace(input_text, false);
[email protected]257ab712009-04-14 17:16:24930 for (HistoryResults::const_iterator i(results.begin()); i != results.end();
931 ++i) {
[email protected]c2ca3fd2014-03-22 03:07:44932 const base::string16& trimmed_suggestion =
933 base::CollapseWhitespace(i->term, false);
934
[email protected]51124552011-07-16 01:37:10935 // Don't autocomplete multi-word queries that have only been seen once
936 // unless the user has typed more than one word.
937 bool prevent_inline_autocomplete = base_prevent_inline_autocomplete ||
[email protected]c2ca3fd2014-03-22 03:07:44938 (!input_multiple_words && (i->visits < 2) &&
939 HasMultipleWords(trimmed_suggestion));
[email protected]51124552011-07-16 01:37:10940
[email protected]78e5e432013-08-03 02:10:10941 int relevance = CalculateRelevanceForHistory(
942 i->time, is_keyword, !prevent_inline_autocomplete,
943 prevent_search_history_inlining);
[email protected]ab5fd2f2014-07-17 19:18:52944 // Add the match to |scored_results| by putting the what-you-typed match
945 // on the front and appending all other matches. We want the what-you-
946 // typed match to always be first.
[email protected]0b9575f2014-07-30 11:58:37947 SearchSuggestionParser::SuggestResults::iterator insertion_position =
948 scored_results.end();
[email protected]ab5fd2f2014-07-17 19:18:52949 if (trimmed_suggestion == trimmed_input) {
950 found_what_you_typed_match = true;
951 insertion_position = scored_results.begin();
952 }
[email protected]0b9575f2014-07-30 11:58:37953 scored_results.insert(
954 insertion_position,
955 SearchSuggestionParser::SuggestResult(
956 trimmed_suggestion, AutocompleteMatchType::SEARCH_HISTORY,
957 trimmed_suggestion, base::string16(), base::string16(),
958 base::string16(), base::string16(), std::string(), std::string(),
959 is_keyword, relevance, false, false, trimmed_input));
[email protected]257ab712009-04-14 17:16:24960 }
[email protected]51124552011-07-16 01:37:10961
962 // History returns results sorted for us. However, we may have docked some
[email protected]ab5fd2f2014-07-17 19:18:52963 // results' scores, so things are no longer in order. While keeping the
964 // what-you-typed match at the front (if it exists), do a stable sort to get
[email protected]51124552011-07-16 01:37:10965 // things back in order without otherwise disturbing results with equal
966 // scores, then force the scores to be unique, so that the order in which
967 // they're shown is deterministic.
[email protected]ab5fd2f2014-07-17 19:18:52968 std::stable_sort(scored_results.begin() +
969 (found_what_you_typed_match ? 1 : 0),
970 scored_results.end(),
[email protected]55ce8f12012-05-09 04:44:08971 CompareScoredResults());
[email protected]7e3b77f2014-07-25 02:29:44972
973 // Don't autocomplete to search terms that would normally be treated as URLs
974 // when typed. For example, if the user searched for "google.com" and types
975 // "goog", don't autocomplete to the search term "google.com". Otherwise,
976 // the input will look like a URL but act like a search, which is confusing.
977 // The 1200 relevance score threshold in the test below is the lowest
978 // possible score in CalculateRelevanceForHistory()'s aggressive-scoring
979 // curve. This is an appropriate threshold to use to decide if we're overly
980 // aggressively inlining because, if we decide the answer is yes, the
981 // way we resolve it it to not use the aggressive-scoring curve.
982 // NOTE: We don't check for autocompleting to URLs in the following cases:
983 // * When inline autocomplete is disabled, we won't be inline autocompleting
984 // this term, so we don't need to worry about confusion as much. This
985 // also prevents calling Classify() again from inside the classifier
986 // (which will corrupt state and likely crash), since the classifier
987 // always disables inline autocomplete.
988 // * When the user has typed the whole string before as a query, then it's
989 // likely the user has no expectation that term should be interpreted as
990 // as a URL, so we need not do anything special to preserve user
991 // expectation.
992 AutocompleteClassifier* classifier =
993 AutocompleteClassifierFactory::GetForProfile(profile_);
[email protected]51124552011-07-16 01:37:10994 int last_relevance = 0;
[email protected]7e3b77f2014-07-25 02:29:44995 if (!base_prevent_inline_autocomplete && !found_what_you_typed_match &&
996 classifier && (scored_results.front().relevance() >= 1200)) {
997 AutocompleteMatch match;
998 classifier->Classify(scored_results.front().suggestion(), false, false,
999 input_.current_page_classification(), &match, NULL);
1000 // Demote this match that would normally be interpreted as a URL to have
1001 // the highest score a previously-issued search query could have when
1002 // scoring with the non-aggressive method. A consequence of demoting
1003 // by revising |last_relevance| is that this match and all following
1004 // matches get demoted; the relative order of matches is preserved.
1005 // One could imagine demoting only those matches that might cause
1006 // confusion (which, by the way, might change the relative order of
1007 // matches. We have decided to go with the simple demote-all approach
1008 // because selective demotion requires multiple Classify() calls and
1009 // such calls can be expensive (as expensive as running the whole
1010 // autocomplete system).
1011 if (!AutocompleteMatch::IsSearchType(match.type)) {
1012 last_relevance = CalculateRelevanceForHistory(
1013 base::Time::Now(), is_keyword, false,
1014 prevent_search_history_inlining);
1015 }
1016 }
1017
[email protected]0b9575f2014-07-30 11:58:371018 for (SearchSuggestionParser::SuggestResults::iterator i(
1019 scored_results.begin()); i != scored_results.end(); ++i) {
[email protected]7e3b77f2014-07-25 02:29:441020 if ((last_relevance != 0) && (i->relevance() >= last_relevance))
[email protected]55ce8f12012-05-09 04:44:081021 i->set_relevance(last_relevance - 1);
1022 last_relevance = i->relevance();
[email protected]51124552011-07-16 01:37:101023 }
1024
[email protected]55ce8f12012-05-09 04:44:081025 return scored_results;
[email protected]257ab712009-04-14 17:16:241026}
1027
[email protected]0b9575f2014-07-30 11:58:371028void SearchProvider::AddSuggestResultsToMap(
1029 const SearchSuggestionParser::SuggestResults& results,
1030 const std::string& metadata,
1031 MatchMap* map) {
[email protected]9487b392014-02-14 02:48:181032 for (size_t i = 0; i < results.size(); ++i)
[email protected]57482a72014-03-14 22:27:371033 AddMatchToMap(results[i], metadata, i, false, map);
initial.commit09911bf2008-07-26 23:55:291034}
1035
[email protected]d30268a2013-06-25 22:31:071036int SearchProvider::GetVerbatimRelevance(bool* relevance_from_server) const {
[email protected]dc6943b2012-06-19 06:39:561037 // Use the suggested verbatim relevance score if it is non-negative (valid),
1038 // if inline autocomplete isn't prevented (always show verbatim on backspace),
[email protected]1beee342012-06-19 22:22:281039 // and if it won't suppress verbatim, leaving no default provider matches.
1040 // Otherwise, if the default provider returned no matches and was still able
[email protected]dc6943b2012-06-19 06:39:561041 // to suppress verbatim, the user would have no search/nav matches and may be
[email protected]1beee342012-06-19 22:22:281042 // left unable to search using their default provider from the omnibox.
[email protected]dc6943b2012-06-19 06:39:561043 // Check for results on each verbatim calculation, as results from older
1044 // queries (on previous input) may be trimmed for failing to inline new input.
[email protected]bc8bb0cd2013-06-24 21:50:231045 bool use_server_relevance =
1046 (default_results_.verbatim_relevance >= 0) &&
[email protected]dab8d52d2013-03-05 07:35:281047 !input_.prevent_inline_autocomplete() &&
[email protected]bc8bb0cd2013-06-24 21:50:231048 ((default_results_.verbatim_relevance > 0) ||
[email protected]cc1526e2013-05-17 04:04:241049 !default_results_.suggest_results.empty() ||
[email protected]bc8bb0cd2013-06-24 21:50:231050 !default_results_.navigation_results.empty());
[email protected]d30268a2013-06-25 22:31:071051 if (relevance_from_server)
1052 *relevance_from_server = use_server_relevance;
[email protected]bc8bb0cd2013-06-24 21:50:231053 return use_server_relevance ?
1054 default_results_.verbatim_relevance : CalculateRelevanceForVerbatim();
[email protected]382a0642012-06-06 06:13:521055}
[email protected]d1f0a7f2012-06-05 10:26:421056
[email protected]382a0642012-06-06 06:13:521057int SearchProvider::CalculateRelevanceForVerbatim() const {
[email protected]85b8d6f2012-05-08 20:53:471058 if (!providers_.keyword_provider().empty())
[email protected]52d08b12009-10-19 18:42:361059 return 250;
[email protected]dab8d52d2013-03-05 07:35:281060 return CalculateRelevanceForVerbatimIgnoringKeywordModeState();
1061}
[email protected]52d08b12009-10-19 18:42:361062
[email protected]dab8d52d2013-03-05 07:35:281063int SearchProvider::
1064 CalculateRelevanceForVerbatimIgnoringKeywordModeState() const {
initial.commit09911bf2008-07-26 23:55:291065 switch (input_.type()) {
[email protected]3dc75b12014-06-08 00:02:221066 case metrics::OmniboxInputType::UNKNOWN:
1067 case metrics::OmniboxInputType::QUERY:
1068 case metrics::OmniboxInputType::FORCED_QUERY:
[email protected]90fe2bb2013-01-15 03:42:131069 return kNonURLVerbatimRelevance;
initial.commit09911bf2008-07-26 23:55:291070
[email protected]3dc75b12014-06-08 00:02:221071 case metrics::OmniboxInputType::URL:
[email protected]52d08b12009-10-19 18:42:361072 return 850;
initial.commit09911bf2008-07-26 23:55:291073
1074 default:
1075 NOTREACHED();
1076 return 0;
1077 }
1078}
1079
[email protected]d30268a2013-06-25 22:31:071080int SearchProvider::GetKeywordVerbatimRelevance(
1081 bool* relevance_from_server) const {
[email protected]dab8d52d2013-03-05 07:35:281082 // Use the suggested verbatim relevance score if it is non-negative (valid),
1083 // if inline autocomplete isn't prevented (always show verbatim on backspace),
1084 // and if it won't suppress verbatim, leaving no keyword provider matches.
1085 // Otherwise, if the keyword provider returned no matches and was still able
1086 // to suppress verbatim, the user would have no search/nav matches and may be
1087 // left unable to search using their keyword provider from the omnibox.
1088 // Check for results on each verbatim calculation, as results from older
1089 // queries (on previous input) may be trimmed for failing to inline new input.
[email protected]bc8bb0cd2013-06-24 21:50:231090 bool use_server_relevance =
1091 (keyword_results_.verbatim_relevance >= 0) &&
[email protected]dab8d52d2013-03-05 07:35:281092 !input_.prevent_inline_autocomplete() &&
[email protected]bc8bb0cd2013-06-24 21:50:231093 ((keyword_results_.verbatim_relevance > 0) ||
[email protected]cc1526e2013-05-17 04:04:241094 !keyword_results_.suggest_results.empty() ||
[email protected]bc8bb0cd2013-06-24 21:50:231095 !keyword_results_.navigation_results.empty());
[email protected]d30268a2013-06-25 22:31:071096 if (relevance_from_server)
1097 *relevance_from_server = use_server_relevance;
[email protected]bc8bb0cd2013-06-24 21:50:231098 return use_server_relevance ?
1099 keyword_results_.verbatim_relevance :
1100 CalculateRelevanceForKeywordVerbatim(keyword_input_.type(),
1101 keyword_input_.prefer_keyword());
[email protected]5423e562013-02-07 03:58:451102}
1103
[email protected]51124552011-07-16 01:37:101104int SearchProvider::CalculateRelevanceForHistory(
[email protected]bc8bb0cd2013-06-24 21:50:231105 const base::Time& time,
[email protected]51124552011-07-16 01:37:101106 bool is_keyword,
[email protected]78e5e432013-08-03 02:10:101107 bool use_aggressive_method,
1108 bool prevent_search_history_inlining) const {
[email protected]aa613d62010-11-09 20:40:181109 // The relevance of past searches falls off over time. There are two distinct
1110 // equations used. If the first equation is used (searches to the primary
[email protected]78e5e432013-08-03 02:10:101111 // provider that we want to score aggressively), the score is in the range
1112 // 1300-1599 (unless |prevent_search_history_inlining|, in which case
[email protected]d8cd76b2013-07-10 09:46:161113 // it's in the range 1200-1299). If the second equation is used the
1114 // relevance of a search 15 minutes ago is discounted 50 points, while the
1115 // relevance of a search two weeks ago is discounted 450 points.
[email protected]bc8bb0cd2013-06-24 21:50:231116 double elapsed_time = std::max((base::Time::Now() - time).InSecondsF(), 0.0);
[email protected]188b50c2013-03-28 07:19:421117 bool is_primary_provider = is_keyword || !providers_.has_keyword_provider();
[email protected]78e5e432013-08-03 02:10:101118 if (is_primary_provider && use_aggressive_method) {
[email protected]aa613d62010-11-09 20:40:181119 // Searches with the past two days get a different curve.
[email protected]51124552011-07-16 01:37:101120 const double autocomplete_time = 2 * 24 * 60 * 60;
[email protected]aa613d62010-11-09 20:40:181121 if (elapsed_time < autocomplete_time) {
[email protected]d8cd76b2013-07-10 09:46:161122 int max_score = is_keyword ? 1599 : 1399;
[email protected]78e5e432013-08-03 02:10:101123 if (prevent_search_history_inlining)
[email protected]d8cd76b2013-07-10 09:46:161124 max_score = 1299;
1125 return max_score - static_cast<int>(99 *
[email protected]aa613d62010-11-09 20:40:181126 std::pow(elapsed_time / autocomplete_time, 2.5));
1127 }
1128 elapsed_time -= autocomplete_time;
1129 }
1130
[email protected]c3a4bd992010-08-18 20:25:011131 const int score_discount =
1132 static_cast<int>(6.5 * std::pow(elapsed_time, 0.3));
initial.commit09911bf2008-07-26 23:55:291133
[email protected]6c85aa02009-02-27 12:08:091134 // Don't let scores go below 0. Negative relevance scores are meaningful in
1135 // a different way.
initial.commit09911bf2008-07-26 23:55:291136 int base_score;
[email protected]51124552011-07-16 01:37:101137 if (is_primary_provider)
[email protected]3dc75b12014-06-08 00:02:221138 base_score = (input_.type() == metrics::OmniboxInputType::URL) ? 750 : 1050;
[email protected]51124552011-07-16 01:37:101139 else
1140 base_score = 200;
initial.commit09911bf2008-07-26 23:55:291141 return std::max(0, base_score - score_discount);
1142}
1143
initial.commit09911bf2008-07-26 23:55:291144AutocompleteMatch SearchProvider::NavigationToMatch(
[email protected]0b9575f2014-07-30 11:58:371145 const SearchSuggestionParser::NavigationResult& navigation) {
[email protected]5889bfb2014-03-19 00:26:481146 base::string16 input;
1147 const bool trimmed_whitespace = base::TrimWhitespace(
1148 navigation.from_keyword_provider() ?
1149 keyword_input_.text() : input_.text(),
1150 base::TRIM_TRAILING, &input) != base::TRIM_NONE;
[email protected]55ce8f12012-05-09 04:44:081151 AutocompleteMatch match(this, navigation.relevance(), false,
[email protected]78981d8c2014-05-09 15:05:471152 navigation.type());
[email protected]55ce8f12012-05-09 04:44:081153 match.destination_url = navigation.url();
[email protected]78981d8c2014-05-09 15:05:471154 BaseSearchProvider::SetDeletionURL(navigation.deletion_url(), &match);
[email protected]23db6492014-01-16 02:35:301155 // First look for the user's input inside the formatted url as it would be
[email protected]371dab12012-06-01 03:23:551156 // without trimming the scheme, so we can find matches at the beginning of the
1157 // scheme.
[email protected]371dab12012-06-01 03:23:551158 const URLPrefix* prefix =
[email protected]23db6492014-01-16 02:35:301159 URLPrefix::BestURLPrefix(navigation.formatted_url(), input);
[email protected]371dab12012-06-01 03:23:551160 size_t match_start = (prefix == NULL) ?
[email protected]23db6492014-01-16 02:35:301161 navigation.formatted_url().find(input) : prefix->prefix.length();
[email protected]d2445c82013-11-04 22:28:351162 bool trim_http = !AutocompleteInput::HasHTTPScheme(input) &&
1163 (!prefix || (match_start != 0));
[email protected]23db6492014-01-16 02:35:301164 const net::FormatUrlTypes format_types =
1165 net::kFormatUrlOmitAll & ~(trim_http ? 0 : net::kFormatUrlOmitHTTP);
[email protected]371dab12012-06-01 03:23:551166
[email protected]371dab12012-06-01 03:23:551167 const std::string languages(
1168 profile_->GetPrefs()->GetString(prefs::kAcceptLanguages));
[email protected]23db6492014-01-16 02:35:301169 size_t inline_autocomplete_offset = (prefix == NULL) ?
1170 base::string16::npos : (match_start + input.length());
[email protected]371dab12012-06-01 03:23:551171 match.fill_into_edit +=
[email protected]5655ea32014-06-21 05:28:081172 AutocompleteInput::FormattedStringWithEquivalentMeaning(
1173 navigation.url(),
[email protected]371dab12012-06-01 03:23:551174 net::FormatUrl(navigation.url(), languages, format_types,
1175 net::UnescapeRule::SPACES, NULL, NULL,
[email protected]5655ea32014-06-21 05:28:081176 &inline_autocomplete_offset),
[email protected]a817ed392014-06-27 05:03:001177 ChromeAutocompleteSchemeClassifier(profile_));
[email protected]14119032013-11-07 08:14:261178 // Preserve the forced query '?' prefix in |match.fill_into_edit|.
1179 // Otherwise, user edits to a suggestion would show non-Search results.
[email protected]3dc75b12014-06-08 00:02:221180 if (input_.type() == metrics::OmniboxInputType::FORCED_QUERY) {
[email protected]670d3232013-12-24 17:58:581181 match.fill_into_edit.insert(0, base::ASCIIToUTF16("?"));
[email protected]0085863a2013-12-06 21:19:031182 if (inline_autocomplete_offset != base::string16::npos)
[email protected]14119032013-11-07 08:14:261183 ++inline_autocomplete_offset;
1184 }
[email protected]6c94a1022014-02-21 03:48:041185 if (inline_autocomplete_offset != base::string16::npos) {
[email protected]518024c2013-07-19 23:40:251186 DCHECK(inline_autocomplete_offset <= match.fill_into_edit.length());
1187 match.inline_autocompletion =
1188 match.fill_into_edit.substr(inline_autocomplete_offset);
1189 }
[email protected]6c94a1022014-02-21 03:48:041190 // An inlineable navsuggestion can only be the default match when there
1191 // is no keyword provider active, lest it appear first and break the user
[email protected]5889bfb2014-03-19 00:26:481192 // out of keyword mode. It can also only be default if either the inline
1193 // autocompletion is empty or we're not preventing inline autocompletion.
1194 // Finally, if we have an inlineable navsuggestion with an inline completion
1195 // that we're not preventing, make sure we didn't trim any whitespace.
1196 // We don't want to claim http://foo.com/bar is inlineable against the
1197 // input "foo.com/b ".
[email protected]c7b8be02014-07-11 19:46:341198 match.allowed_to_be_default_match = (prefix != NULL) &&
[email protected]6c94a1022014-02-21 03:48:041199 (providers_.GetKeywordProviderURL() == NULL) &&
[email protected]5889bfb2014-03-19 00:26:481200 (match.inline_autocompletion.empty() ||
[email protected]78981d8c2014-05-09 15:05:471201 (!input_.prevent_inline_autocomplete() && !trimmed_whitespace));
[email protected]c7b8be02014-07-11 19:46:341202 match.EnsureUWYTIsAllowedToBeDefault(
1203 input_.canonicalized_url(), providers_.template_url_service());
[email protected]371dab12012-06-01 03:23:551204
[email protected]23db6492014-01-16 02:35:301205 match.contents = navigation.match_contents();
1206 match.contents_class = navigation.match_contents_class();
[email protected]55ce8f12012-05-09 04:44:081207 match.description = navigation.description();
[email protected]371dab12012-06-01 03:23:551208 AutocompleteMatch::ClassifyMatchInString(input, match.description,
1209 ACMatchClassification::NONE, &match.description_class);
[email protected]d30268a2013-06-25 22:31:071210
1211 match.RecordAdditionalInfo(
1212 kRelevanceFromServerKey,
1213 navigation.relevance_from_server() ? kTrue : kFalse);
[email protected]987fad782013-08-28 06:23:181214 match.RecordAdditionalInfo(kShouldPrefetchKey, kFalse);
[email protected]d30268a2013-06-25 22:31:071215
initial.commit09911bf2008-07-26 23:55:291216 return match;
1217}
[email protected]4ab4c7c2010-11-24 04:49:341218
1219void SearchProvider::UpdateDone() {
[email protected]2cdf1172012-08-26 12:21:331220 // We're done when the timer isn't running, there are no suggest queries
[email protected]5fac3782013-03-06 09:32:311221 // pending, and we're not waiting on Instant.
[email protected]e1290ee62013-06-26 18:31:151222 done_ = !timer_.IsRunning() && (suggest_results_pending_ == 0);
[email protected]4ab4c7c2010-11-24 04:49:341223}
[email protected]20184242014-05-14 02:57:421224
1225std::string SearchProvider::GetSessionToken() {
1226 base::TimeTicks current_time(base::TimeTicks::Now());
1227 // Renew token if it expired.
1228 if (current_time > token_expiration_time_) {
1229 const size_t kTokenBytes = 12;
1230 std::string raw_data;
1231 base::RandBytes(WriteInto(&raw_data, kTokenBytes + 1), kTokenBytes);
1232 base::Base64Encode(raw_data, &current_token_);
[email protected]ab2c31f72014-05-17 17:03:531233
1234 // Make the base64 encoded value URL and filename safe(see RFC 3548).
1235 std::replace(current_token_.begin(), current_token_.end(), '+', '-');
1236 std::replace(current_token_.begin(), current_token_.end(), '/', '_');
[email protected]20184242014-05-14 02:57:421237 }
1238
1239 // Extend expiration time another 60 seconds.
1240 token_expiration_time_ = current_time + base::TimeDelta::FromSeconds(60);
1241
1242 return current_token_;
1243}
[email protected]2ef2a6642014-07-30 05:50:291244
1245void SearchProvider::RegisterDisplayedAnswers(
1246 const AutocompleteResult& result) {
1247 if (result.empty())
1248 return;
1249
1250 // The answer must be in the first or second slot to be considered. It should
1251 // only be in the second slot if AutocompleteController ranked a local search
1252 // history or a verbatim item higher than the answer.
1253 AutocompleteResult::const_iterator match = result.begin();
1254 if (match->answer_contents.empty() && result.size() > 1)
1255 ++match;
1256 if (match->answer_contents.empty() || match->answer_type.empty() ||
1257 match->fill_into_edit.empty())
1258 return;
1259
1260 // Valid answer encountered, cache it for further queries.
1261 last_answer_seen_.full_query_text = match->fill_into_edit;
1262 last_answer_seen_.query_type = match->answer_type;
1263}
1264
1265void SearchProvider::DoAnswersQuery(const AutocompleteInput& input) {
1266 // If the query text starts with trimmed input, this is valid prefetch data.
1267 prefetch_data_ = StartsWith(last_answer_seen_.full_query_text,
1268 base::CollapseWhitespace(input.text(), false),
1269 false) ?
1270 last_answer_seen_ : AnswersQueryData();
1271}