blob: bf49576093038dd465cd265dc23fb206c6212e35 [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]3853a4c2013-02-11 17:15:5718#include "base/prefs/pref_service.h"
[email protected]20184242014-05-14 02:57:4219#include "base/rand_util.h"
[email protected]5889bfb2014-03-19 00:26:4820#include "base/strings/string_util.h"
[email protected]135cb802013-06-09 16:44:2021#include "base/strings/utf_string_conversions.h"
[email protected]ea3b9a502011-04-04 14:19:3722#include "chrome/browser/autocomplete/autocomplete_classifier.h"
[email protected]810ffba2012-06-12 01:07:4823#include "chrome/browser/autocomplete/autocomplete_classifier_factory.h"
[email protected]5af9bc82012-06-29 00:53:4824#include "chrome/browser/autocomplete/autocomplete_provider_listener.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]684fcc12013-03-08 22:50:0230#include "chrome/browser/omnibox/omnibox_field_trial.h"
[email protected]8ecad5e2010-12-02 21:18:3331#include "chrome/browser/profiles/profile.h"
[email protected]8e5c89a2011-06-07 18:13:3332#include "chrome/browser/search_engines/template_url_service_factory.h"
[email protected]c4a9d4c2013-08-10 07:06:2733#include "chrome/browser/ui/search/instant_controller.h"
[email protected]20184242014-05-14 02:57:4234#include "chrome/common/chrome_switches.h"
initial.commit09911bf2008-07-26 23:55:2935#include "chrome/common/pref_names.h"
[email protected]ebeb8612014-06-17 01:54:5036#include "components/autocomplete/url_prefix.h"
[email protected]8e44a5b02014-06-19 19:03:2437#include "components/google/core/browser/google_util.h"
[email protected]e3ce70ac2014-06-26 18:34:5638#include "components/history/core/browser/in_memory_database.h"
[email protected]73b2d1e72014-06-25 23:45:3639#include "components/history/core/browser/keyword_search_term.h"
[email protected]3dc75b12014-06-08 00:02:2240#include "components/metrics/proto/omnibox_input_type.pb.h"
[email protected]720b10492014-07-23 08:48:4041#include "components/search/search.h"
[email protected]0915b352014-06-25 19:58:1442#include "components/search_engines/template_url_prepopulate_data.h"
[email protected]bf5c532d2014-07-05 00:29:5343#include "components/search_engines/template_url_service.h"
[email protected]71011c1682014-07-09 17:19:1644#include "components/variations/variations_http_header_provider.h"
[email protected]7267ff82013-12-03 17:20:3045#include "content/public/browser/user_metrics.h"
[email protected]34ac8f32009-02-22 23:03:2746#include "grit/generated_resources.h"
initial.commit09911bf2008-07-26 23:55:2947#include "net/base/escape.h"
[email protected]d3cf8682f02012-02-29 23:29:3448#include "net/base/load_flags.h"
[email protected]371dab12012-06-01 03:23:5549#include "net/base/net_util.h"
[email protected]bd3b4712012-12-18 17:01:3050#include "net/http/http_request_headers.h"
[email protected]3dc1bc42012-06-19 08:20:5351#include "net/url_request/url_fetcher.h"
[email protected]319d9e6f2009-02-18 19:47:2152#include "net/url_request/url_request_status.h"
[email protected]c051a1b2011-01-21 23:30:1753#include "ui/base/l10n/l10n_util.h"
[email protected]cca6f392014-05-28 21:32:2654#include "url/url_constants.h"
[email protected]761fa4702013-07-02 15:25:1555#include "url/url_util.h"
initial.commit09911bf2008-07-26 23:55:2956
[email protected]bc8bb0cd2013-06-24 21:50:2357// Helpers --------------------------------------------------------------------
[email protected]e1acf6f2008-10-27 20:43:3358
[email protected]51124552011-07-16 01:37:1059namespace {
60
[email protected]7706a522012-08-16 17:42:2561// We keep track in a histogram how many suggest requests we send, how
62// many suggest requests we invalidate (e.g., due to a user typing
63// another character), and how many replies we receive.
64// *** ADD NEW ENUMS AFTER ALL PREVIOUSLY DEFINED ONES! ***
65// (excluding the end-of-list enum value)
66// We do not want values of existing enums to change or else it screws
67// up the statistics.
68enum SuggestRequestsHistogramValue {
69 REQUEST_SENT = 1,
70 REQUEST_INVALIDATED,
71 REPLY_RECEIVED,
72 MAX_SUGGEST_REQUEST_HISTOGRAM_VALUE
73};
74
[email protected]90fe2bb2013-01-15 03:42:1375// The verbatim score for an input which is not an URL.
76const int kNonURLVerbatimRelevance = 1300;
77
[email protected]7706a522012-08-16 17:42:2578// Increments the appropriate value in the histogram by one.
79void LogOmniboxSuggestRequest(
80 SuggestRequestsHistogramValue request_value) {
81 UMA_HISTOGRAM_ENUMERATION("Omnibox.SuggestRequests", request_value,
82 MAX_SUGGEST_REQUEST_HISTOGRAM_VALUE);
83}
84
[email protected]0085863a2013-12-06 21:19:0385bool HasMultipleWords(const base::string16& text) {
[email protected]51124552011-07-16 01:37:1086 base::i18n::BreakIterator i(text, base::i18n::BreakIterator::BREAK_WORD);
87 bool found_word = false;
88 if (i.Init()) {
89 while (i.Advance()) {
90 if (i.IsWord()) {
91 if (found_word)
92 return true;
93 found_word = true;
94 }
95 }
96 }
97 return false;
98}
99
[email protected]d1f0a7f2012-06-05 10:26:42100} // namespace
[email protected]51124552011-07-16 01:37:10101
[email protected]3954c3a2012-04-10 20:17:55102// SearchProvider::Providers --------------------------------------------------
[email protected]b547666d2009-04-23 16:37:58103
[email protected]85b8d6f2012-05-08 20:53:47104SearchProvider::Providers::Providers(TemplateURLService* template_url_service)
[email protected]02346202014-02-05 05:18:30105 : template_url_service_(template_url_service) {}
[email protected]85b8d6f2012-05-08 20:53:47106
107const TemplateURL* SearchProvider::Providers::GetDefaultProviderURL() const {
108 return default_provider_.empty() ? NULL :
109 template_url_service_->GetTemplateURLForKeyword(default_provider_);
110}
111
112const TemplateURL* SearchProvider::Providers::GetKeywordProviderURL() const {
113 return keyword_provider_.empty() ? NULL :
114 template_url_service_->GetTemplateURLForKeyword(keyword_provider_);
[email protected]257ab712009-04-14 17:16:24115}
116
[email protected]3954c3a2012-04-10 20:17:55117
[email protected]bc8bb0cd2013-06-24 21:50:23118// SearchProvider::CompareScoredResults ---------------------------------------
119
120class SearchProvider::CompareScoredResults {
121 public:
[email protected]0b9575f2014-07-30 11:58:37122 bool operator()(const SearchSuggestionParser::Result& a,
123 const SearchSuggestionParser::Result& b) {
[email protected]bc8bb0cd2013-06-24 21:50:23124 // Sort in descending relevance order.
125 return a.relevance() > b.relevance();
126 }
127};
128
129
[email protected]3954c3a2012-04-10 20:17:55130// SearchProvider -------------------------------------------------------------
131
132// static
[email protected]24dbf2302013-04-05 16:59:25133int SearchProvider::kMinimumTimeBetweenSuggestQueriesMs = 100;
[email protected]3954c3a2012-04-10 20:17:55134
[email protected]bc8bb0cd2013-06-24 21:50:23135SearchProvider::SearchProvider(AutocompleteProviderListener* listener,
136 Profile* profile)
[email protected]02346202014-02-05 05:18:30137 : BaseSearchProvider(listener, profile, AutocompleteProvider::TYPE_SEARCH),
[email protected]cfa164bf2014-03-19 11:51:15138 providers_(TemplateURLServiceFactory::GetForProfile(profile)) {
[email protected]bc8bb0cd2013-06-24 21:50:23139}
140
[email protected]cb86ee6f2013-04-28 16:58:15141// static
[email protected]987fad782013-08-28 06:23:18142std::string SearchProvider::GetSuggestMetadata(const AutocompleteMatch& match) {
143 return match.GetAdditionalInfo(kSuggestMetadataKey);
144}
145
[email protected]bc8bb0cd2013-06-24 21:50:23146void SearchProvider::ResetSession() {
147 field_trial_triggered_in_session_ = false;
[email protected]4ab4c7c2010-11-24 04:49:34148}
149
[email protected]bc8bb0cd2013-06-24 21:50:23150SearchProvider::~SearchProvider() {
151}
152
[email protected]0b9575f2014-07-30 11:58:37153void SearchProvider::UpdateMatchContentsClass(
154 const base::string16& input_text,
155 SearchSuggestionParser::Results* results) {
156 for (SearchSuggestionParser::SuggestResults::iterator sug_it =
157 results->suggest_results.begin();
[email protected]23db6492014-01-16 02:35:30158 sug_it != results->suggest_results.end(); ++sug_it) {
[email protected]ee6110b2014-01-09 22:26:31159 sug_it->ClassifyMatchContents(false, input_text);
160 }
[email protected]23db6492014-01-16 02:35:30161 const std::string languages(
162 profile_->GetPrefs()->GetString(prefs::kAcceptLanguages));
[email protected]0b9575f2014-07-30 11:58:37163 for (SearchSuggestionParser::NavigationResults::iterator nav_it =
164 results->navigation_results.begin();
[email protected]23db6492014-01-16 02:35:30165 nav_it != results->navigation_results.end(); ++nav_it) {
166 nav_it->CalculateAndClassifyMatchContents(false, input_text, languages);
167 }
[email protected]ee6110b2014-01-09 22:26:31168}
169
170// static
[email protected]bc8bb0cd2013-06-24 21:50:23171int SearchProvider::CalculateRelevanceForKeywordVerbatim(
[email protected]332d17d22014-06-20 16:56:03172 metrics::OmniboxInputType::Type type,
[email protected]bc8bb0cd2013-06-24 21:50:23173 bool prefer_keyword) {
174 // This function is responsible for scoring verbatim query matches
175 // for non-extension keywords. KeywordProvider::CalculateRelevance()
176 // scores verbatim query matches for extension keywords, as well as
177 // for keyword matches (i.e., suggestions of a keyword itself, not a
178 // suggestion of a query on a keyword search engine). These two
179 // functions are currently in sync, but there's no reason we
180 // couldn't decide in the future to score verbatim matches
181 // differently for extension and non-extension keywords. If you
182 // make such a change, however, you should update this comment to
183 // describe it, so it's clear why the functions diverge.
184 if (prefer_keyword)
185 return 1500;
[email protected]3dc75b12014-06-08 00:02:22186 return (type == metrics::OmniboxInputType::QUERY) ? 1450 : 1100;
[email protected]bc8bb0cd2013-06-24 21:50:23187}
188
initial.commit09911bf2008-07-26 23:55:29189void SearchProvider::Start(const AutocompleteInput& input,
[email protected]8deeb952008-10-09 18:21:27190 bool minimal_changes) {
[email protected]04504c242013-01-22 21:08:55191 // Do our best to load the model as early as possible. This will reduce
192 // odds of having the model not ready when really needed (a non-empty input).
193 TemplateURLService* model = providers_.template_url_service();
194 DCHECK(model);
195 model->Load();
196
initial.commit09911bf2008-07-26 23:55:29197 matches_.clear();
[email protected]618d6e62012-12-16 05:55:57198 field_trial_triggered_ = false;
initial.commit09911bf2008-07-26 23:55:29199
[email protected]6c85aa02009-02-27 12:08:09200 // Can't return search/suggest results for bogus input or without a profile.
[email protected]3dc75b12014-06-08 00:02:22201 if (!profile_ || (input.type() == metrics::OmniboxInputType::INVALID)) {
[email protected]9950e5d52014-02-25 23:34:19202 Stop(true);
initial.commit09911bf2008-07-26 23:55:29203 return;
204 }
205
[email protected]14710852013-02-05 23:45:41206 keyword_input_ = input;
[email protected]257ab712009-04-14 17:16:24207 const TemplateURL* keyword_provider =
[email protected]14710852013-02-05 23:45:41208 KeywordProvider::GetSubstitutingTemplateURLForInput(model,
209 &keyword_input_);
210 if (keyword_provider == NULL)
211 keyword_input_.Clear();
212 else if (keyword_input_.text().empty())
[email protected]257ab712009-04-14 17:16:24213 keyword_provider = NULL;
[email protected]257ab712009-04-14 17:16:24214
[email protected]85b8d6f2012-05-08 20:53:47215 const TemplateURL* default_provider = model->GetDefaultSearchProvider();
[email protected]ce7ee5f2014-06-16 23:41:19216 if (default_provider &&
217 !default_provider->SupportsReplacement(model->search_terms_data()))
[email protected]257ab712009-04-14 17:16:24218 default_provider = NULL;
219
220 if (keyword_provider == default_provider)
[email protected]e17511f2011-07-13 14:09:18221 default_provider = NULL; // No use in querying the same provider twice.
[email protected]257ab712009-04-14 17:16:24222
223 if (!default_provider && !keyword_provider) {
224 // No valid providers.
[email protected]9950e5d52014-02-25 23:34:19225 Stop(true);
initial.commit09911bf2008-07-26 23:55:29226 return;
227 }
228
229 // If we're still running an old query but have since changed the query text
[email protected]257ab712009-04-14 17:16:24230 // or the providers, abort the query.
[email protected]0085863a2013-12-06 21:19:03231 base::string16 default_provider_keyword(default_provider ?
232 default_provider->keyword() : base::string16());
233 base::string16 keyword_provider_keyword(keyword_provider ?
234 keyword_provider->keyword() : base::string16());
[email protected]9e789742011-01-10 23:27:32235 if (!minimal_changes ||
[email protected]85b8d6f2012-05-08 20:53:47236 !providers_.equal(default_provider_keyword, keyword_provider_keyword)) {
[email protected]bb900e02013-03-14 14:15:29237 // Cancel any in-flight suggest requests.
[email protected]e1290ee62013-06-26 18:31:15238 if (!done_)
[email protected]e29249dc52012-07-19 17:33:50239 Stop(false);
[email protected]257ab712009-04-14 17:16:24240 }
initial.commit09911bf2008-07-26 23:55:29241
[email protected]85b8d6f2012-05-08 20:53:47242 providers_.set(default_provider_keyword, keyword_provider_keyword);
initial.commit09911bf2008-07-26 23:55:29243
244 if (input.text().empty()) {
245 // User typed "?" alone. Give them a placeholder result indicating what
246 // this syntax does.
[email protected]257ab712009-04-14 17:16:24247 if (default_provider) {
[email protected]69c579e2010-04-23 20:01:00248 AutocompleteMatch match;
249 match.provider = this;
[email protected]a2fedb1e2011-01-25 15:23:36250 match.contents.assign(l10n_util::GetStringUTF16(IDS_EMPTY_KEYWORD_VALUE));
[email protected]257ab712009-04-14 17:16:24251 match.contents_class.push_back(
[email protected]2c33dd22010-02-11 21:46:35252 ACMatchClassification(0, ACMatchClassification::NONE));
[email protected]85b8d6f2012-05-08 20:53:47253 match.keyword = providers_.default_provider();
[email protected]45f89a92013-08-12 13:41:36254 match.allowed_to_be_default_match = true;
[email protected]257ab712009-04-14 17:16:24255 matches_.push_back(match);
256 }
[email protected]9950e5d52014-02-25 23:34:19257 Stop(true);
initial.commit09911bf2008-07-26 23:55:29258 return;
259 }
260
261 input_ = input;
262
[email protected]e1290ee62013-06-26 18:31:15263 DoHistoryQuery(minimal_changes);
[email protected]2ef2a6642014-07-30 05:50:29264 DoAnswersQuery(input);
[email protected]e1290ee62013-06-26 18:31:15265 StartOrStopSuggestQuery(minimal_changes);
[email protected]344946a12012-12-20 12:03:42266 UpdateMatches();
initial.commit09911bf2008-07-26 23:55:29267}
268
[email protected]d4a94b92014-03-04 01:35:22269void SearchProvider::SortResults(bool is_keyword,
[email protected]0b9575f2014-07-30 11:58:37270 SearchSuggestionParser::Results* results) {
[email protected]d4a94b92014-03-04 01:35:22271 // Ignore suggested scores for non-keyword matches in keyword mode; if the
272 // server is allowed to score these, it could interfere with the user's
273 // ability to get good keyword results.
274 const bool abandon_suggested_scores =
275 !is_keyword && !providers_.keyword_provider().empty();
[email protected]0b9575f2014-07-30 11:58:37276 // Apply calculated relevance scores to suggestions if valid relevances were
[email protected]d4a94b92014-03-04 01:35:22277 // not provided or we're abandoning suggested scores entirely.
[email protected]2c802d12014-07-31 12:57:14278 if (!results->relevances_from_server || abandon_suggested_scores) {
[email protected]d4a94b92014-03-04 01:35:22279 ApplyCalculatedSuggestRelevance(&results->suggest_results);
280 ApplyCalculatedNavigationRelevance(&results->navigation_results);
281 // If abandoning scores entirely, also abandon the verbatim score.
282 if (abandon_suggested_scores)
283 results->verbatim_relevance = -1;
284 }
285
286 // Keep the result lists sorted.
287 const CompareScoredResults comparator = CompareScoredResults();
288 std::stable_sort(results->suggest_results.begin(),
289 results->suggest_results.end(),
290 comparator);
291 std::stable_sort(results->navigation_results.begin(),
292 results->navigation_results.end(),
293 comparator);
294}
295
[email protected]cfa164bf2014-03-19 11:51:15296const TemplateURL* SearchProvider::GetTemplateURL(bool is_keyword) const {
297 return is_keyword ? providers_.GetKeywordProviderURL()
298 : providers_.GetDefaultProviderURL();
[email protected]9487b392014-02-14 02:48:18299}
300
[email protected]d4a94b92014-03-04 01:35:22301const AutocompleteInput SearchProvider::GetInput(bool is_keyword) const {
302 return is_keyword ? keyword_input_ : input_;
[email protected]9487b392014-02-14 02:48:18303}
304
[email protected]0b9575f2014-07-30 11:58:37305SearchSuggestionParser::Results* SearchProvider::GetResultsToFill(
306 bool is_keyword) {
[email protected]cfa164bf2014-03-19 11:51:15307 return is_keyword ? &keyword_results_ : &default_results_;
308}
309
[email protected]9487b392014-02-14 02:48:18310bool SearchProvider::ShouldAppendExtraParams(
[email protected]0b9575f2014-07-30 11:58:37311 const SearchSuggestionParser::SuggestResult& result) const {
[email protected]9487b392014-02-14 02:48:18312 return !result.from_keyword_provider() ||
313 providers_.default_provider().empty();
314}
315
[email protected]ef6866f2014-02-18 08:26:34316void SearchProvider::StopSuggest() {
317 // Increment the appropriate field in the histogram by the number of
318 // pending requests that were invalidated.
319 for (int i = 0; i < suggest_results_pending_; ++i)
320 LogOmniboxSuggestRequest(REQUEST_INVALIDATED);
321 suggest_results_pending_ = 0;
322 timer_.Stop();
323 // Stop any in-progress URL fetches.
324 keyword_fetcher_.reset();
325 default_fetcher_.reset();
326}
327
328void SearchProvider::ClearAllResults() {
329 keyword_results_.Clear();
330 default_results_.Clear();
331}
332
[email protected]d4a94b92014-03-04 01:35:22333int SearchProvider::GetDefaultResultRelevance() const {
334 return -1;
335}
336
[email protected]7267ff82013-12-03 17:20:30337void SearchProvider::RecordDeletionResult(bool success) {
338 if (success) {
339 content::RecordAction(
[email protected]e6e30ac2014-01-13 21:24:39340 base::UserMetricsAction("Omnibox.ServerSuggestDelete.Success"));
[email protected]7267ff82013-12-03 17:20:30341 } else {
342 content::RecordAction(
[email protected]e6e30ac2014-01-13 21:24:39343 base::UserMetricsAction("Omnibox.ServerSuggestDelete.Failure"));
[email protected]7267ff82013-12-03 17:20:30344 }
345}
346
[email protected]cfa164bf2014-03-19 11:51:15347void SearchProvider::LogFetchComplete(bool success, bool is_keyword) {
348 LogOmniboxSuggestRequest(REPLY_RECEIVED);
349 // Record response time for suggest requests sent to Google. We care
350 // only about the common case: the Google default provider used in
351 // non-keyword mode.
352 const TemplateURL* default_url = providers_.GetDefaultProviderURL();
353 if (!is_keyword && default_url &&
[email protected]ce7ee5f2014-06-16 23:41:19354 (TemplateURLPrepopulateData::GetEngineType(
355 *default_url,
356 providers_.template_url_service()->search_terms_data()) ==
[email protected]cfa164bf2014-03-19 11:51:15357 SEARCH_ENGINE_GOOGLE)) {
358 const base::TimeDelta elapsed_time =
359 base::TimeTicks::Now() - time_suggest_request_sent_;
360 if (success) {
361 UMA_HISTOGRAM_TIMES("Omnibox.SuggestRequest.Success.GoogleResponseTime",
362 elapsed_time);
363 } else {
364 UMA_HISTOGRAM_TIMES("Omnibox.SuggestRequest.Failure.GoogleResponseTime",
365 elapsed_time);
366 }
367 }
368}
369
370bool SearchProvider::IsKeywordFetcher(const net::URLFetcher* fetcher) const {
371 return fetcher == keyword_fetcher_.get();
372}
373
374void SearchProvider::UpdateMatches() {
[email protected]cfa164bf2014-03-19 11:51:15375 ConvertResultsToAutocompleteMatches();
376
377 // Check constraints that may be violated by suggested relevances.
378 if (!matches_.empty() &&
379 (default_results_.HasServerProvidedScores() ||
380 keyword_results_.HasServerProvidedScores())) {
381 // These blocks attempt to repair undesirable behavior by suggested
382 // relevances with minimal impact, preserving other suggested relevances.
383
[email protected]cfa164bf2014-03-19 11:51:15384 if (!HasKeywordDefaultMatchInKeywordMode()) {
385 // In keyword mode, disregard the keyword verbatim suggested relevance
386 // if necessary so there at least one keyword match that's allowed to
387 // be the default match.
388 keyword_results_.verbatim_relevance = -1;
389 ConvertResultsToAutocompleteMatches();
390 }
[email protected]89bd27d12014-04-12 17:36:23391 if (IsTopMatchSearchWithURLInput()) {
[email protected]cfa164bf2014-03-19 11:51:15392 // Disregard the suggested search and verbatim relevances if the input
393 // type is URL and the top match is a highly-ranked search suggestion.
394 // For example, prevent a search for "foo.com" from outranking another
395 // provider's navigation for "foo.com" or "foo.com/url_from_history".
396 ApplyCalculatedSuggestRelevance(&keyword_results_.suggest_results);
397 ApplyCalculatedSuggestRelevance(&default_results_.suggest_results);
398 default_results_.verbatim_relevance = -1;
399 keyword_results_.verbatim_relevance = -1;
400 ConvertResultsToAutocompleteMatches();
401 }
[email protected]89bd27d12014-04-12 17:36:23402 if (FindTopMatch() == matches_.end()) {
403 // Guarantee that SearchProvider returns a legal default match. (The
404 // omnibox always needs at least one legal default match, and it relies
405 // on SearchProvider to always return one.)
[email protected]cfa164bf2014-03-19 11:51:15406 ApplyCalculatedRelevance();
407 ConvertResultsToAutocompleteMatches();
408 }
[email protected]cfa164bf2014-03-19 11:51:15409 DCHECK(HasKeywordDefaultMatchInKeywordMode());
[email protected]89bd27d12014-04-12 17:36:23410 DCHECK(!IsTopMatchSearchWithURLInput());
411 DCHECK(FindTopMatch() != matches_.end());
[email protected]cfa164bf2014-03-19 11:51:15412 }
413 UMA_HISTOGRAM_CUSTOM_COUNTS(
414 "Omnibox.SearchProviderMatches", matches_.size(), 1, 6, 7);
415
416 const TemplateURL* keyword_url = providers_.GetKeywordProviderURL();
417 if ((keyword_url != NULL) && HasKeywordDefaultMatchInKeywordMode()) {
418 // If there is a keyword match that is allowed to be the default match,
419 // then prohibit default provider matches from being the default match lest
420 // such matches cause the user to break out of keyword mode.
421 for (ACMatches::iterator it = matches_.begin(); it != matches_.end();
422 ++it) {
423 if (it->keyword != keyword_url->keyword())
424 it->allowed_to_be_default_match = false;
425 }
426 }
[email protected]cfa164bf2014-03-19 11:51:15427 UpdateDone();
[email protected]cfa164bf2014-03-19 11:51:15428}
429
[email protected]bc8bb0cd2013-06-24 21:50:23430void SearchProvider::Run() {
431 // Start a new request with the current input.
432 suggest_results_pending_ = 0;
433 time_suggest_request_sent_ = base::TimeTicks::Now();
[email protected]abe441e2013-05-06 12:35:05434
[email protected]bc8bb0cd2013-06-24 21:50:23435 default_fetcher_.reset(CreateSuggestFetcher(kDefaultProviderURLFetcherID,
436 providers_.GetDefaultProviderURL(), input_));
437 keyword_fetcher_.reset(CreateSuggestFetcher(kKeywordProviderURLFetcherID,
438 providers_.GetKeywordProviderURL(), keyword_input_));
439
440 // Both the above can fail if the providers have been modified or deleted
441 // since the query began.
442 if (suggest_results_pending_ == 0) {
443 UpdateDone();
444 // We only need to update the listener if we're actually done.
445 if (done_)
446 listener_->OnProviderUpdate(false);
447 }
[email protected]601858c02010-09-01 17:08:20448}
449
[email protected]8d457132010-11-04 18:13:40450void SearchProvider::DoHistoryQuery(bool minimal_changes) {
451 // The history query results are synchronous, so if minimal_changes is true,
452 // we still have the last results and don't need to do anything.
453 if (minimal_changes)
initial.commit09911bf2008-07-26 23:55:29454 return;
455
[email protected]8d457132010-11-04 18:13:40456 keyword_history_results_.clear();
457 default_history_results_.clear();
initial.commit09911bf2008-07-26 23:55:29458
[email protected]78e5e432013-08-03 02:10:10459 if (OmniboxFieldTrial::SearchHistoryDisable(
460 input_.current_page_classification()))
[email protected]d8cd76b2013-07-10 09:46:16461 return;
462
[email protected]8d457132010-11-04 18:13:40463 HistoryService* const history_service =
[email protected]9d2db762012-06-19 00:01:10464 HistoryServiceFactory::GetForProfile(profile_, Profile::EXPLICIT_ACCESS);
[email protected]8d457132010-11-04 18:13:40465 history::URLDatabase* url_db = history_service ?
466 history_service->InMemoryDatabase() : NULL;
467 if (!url_db)
initial.commit09911bf2008-07-26 23:55:29468 return;
469
[email protected]51124552011-07-16 01:37:10470 // Request history for both the keyword and default provider. We grab many
471 // more matches than we'll ultimately clamp to so that if there are several
472 // recent multi-word matches who scores are lowered (see
473 // AddHistoryResultsToMap()), they won't crowd out older, higher-scoring
474 // matches. Note that this doesn't fix the problem entirely, but merely
475 // limits it to cases with a very large number of such multi-word matches; for
476 // now, this seems OK compared with the complexity of a real fix, which would
477 // require multiple searches and tracking of "single- vs. multi-word" in the
478 // database.
479 int num_matches = kMaxMatches * 5;
[email protected]85b8d6f2012-05-08 20:53:47480 const TemplateURL* default_url = providers_.GetDefaultProviderURL();
481 if (default_url) {
[email protected]b4bec972014-04-05 18:07:15482 const base::TimeTicks start_time = base::TimeTicks::Now();
[email protected]85b8d6f2012-05-08 20:53:47483 url_db->GetMostRecentKeywordSearchTerms(default_url->id(), input_.text(),
484 num_matches, &default_history_results_);
[email protected]31afdf72013-09-26 04:29:36485 UMA_HISTOGRAM_TIMES(
486 "Omnibox.SearchProvider.GetMostRecentKeywordTermsDefaultProviderTime",
487 base::TimeTicks::Now() - start_time);
[email protected]257ab712009-04-14 17:16:24488 }
[email protected]85b8d6f2012-05-08 20:53:47489 const TemplateURL* keyword_url = providers_.GetKeywordProviderURL();
490 if (keyword_url) {
491 url_db->GetMostRecentKeywordSearchTerms(keyword_url->id(),
[email protected]14710852013-02-05 23:45:41492 keyword_input_.text(), num_matches, &keyword_history_results_);
[email protected]3954c3a2012-04-10 20:17:55493 }
initial.commit09911bf2008-07-26 23:55:29494}
495
[email protected]6dc950f2012-07-16 19:49:08496void SearchProvider::StartOrStopSuggestQuery(bool minimal_changes) {
[email protected]83c726482008-09-10 06:36:34497 if (!IsQuerySuitableForSuggest()) {
initial.commit09911bf2008-07-26 23:55:29498 StopSuggest();
[email protected]71b46152013-05-03 16:39:20499 ClearAllResults();
initial.commit09911bf2008-07-26 23:55:29500 return;
501 }
502
503 // For the minimal_changes case, if we finished the previous query and still
504 // have its results, or are allowed to keep running it, just do that, rather
505 // than starting a new query.
506 if (minimal_changes &&
[email protected]cc1526e2013-05-17 04:04:24507 (!default_results_.suggest_results.empty() ||
508 !default_results_.navigation_results.empty() ||
509 !keyword_results_.suggest_results.empty() ||
510 !keyword_results_.navigation_results.empty() ||
[email protected]a2770a7d2014-04-22 19:33:35511 (!done_ && input_.want_asynchronous_matches())))
initial.commit09911bf2008-07-26 23:55:29512 return;
513
514 // We can't keep running any previous query, so halt it.
515 StopSuggest();
[email protected]d1f0a7f2012-06-05 10:26:42516
517 // Remove existing results that cannot inline autocomplete the new input.
[email protected]71b46152013-05-03 16:39:20518 RemoveAllStaleResults();
initial.commit09911bf2008-07-26 23:55:29519
[email protected]ee6110b2014-01-09 22:26:31520 // Update the content classifications of remaining results so they look good
521 // against the current input.
[email protected]23db6492014-01-16 02:35:30522 UpdateMatchContentsClass(input_.text(), &default_results_);
523 if (!keyword_input_.text().empty())
524 UpdateMatchContentsClass(keyword_input_.text(), &keyword_results_);
[email protected]ee6110b2014-01-09 22:26:31525
initial.commit09911bf2008-07-26 23:55:29526 // We can't start a new query if we're only allowed synchronous results.
[email protected]a2770a7d2014-04-22 19:33:35527 if (!input_.want_asynchronous_matches())
initial.commit09911bf2008-07-26 23:55:29528 return;
529
[email protected]24dbf2302013-04-05 16:59:25530 // To avoid flooding the suggest server, don't send a query until at
531 // least 100 ms since the last query.
[email protected]515ffa942012-11-27 20:18:24532 base::TimeTicks next_suggest_time(time_suggest_request_sent_ +
[email protected]bc8bb0cd2013-06-24 21:50:23533 base::TimeDelta::FromMilliseconds(kMinimumTimeBetweenSuggestQueriesMs));
[email protected]515ffa942012-11-27 20:18:24534 base::TimeTicks now(base::TimeTicks::Now());
535 if (now >= next_suggest_time) {
536 Run();
537 return;
538 }
539 timer_.Start(FROM_HERE, next_suggest_time - now, this, &SearchProvider::Run);
initial.commit09911bf2008-07-26 23:55:29540}
541
[email protected]83c726482008-09-10 06:36:34542bool SearchProvider::IsQuerySuitableForSuggest() const {
[email protected]3954c3a2012-04-10 20:17:55543 // Don't run Suggest in incognito mode, if the engine doesn't support it, or
544 // if the user has disabled it.
[email protected]85b8d6f2012-05-08 20:53:47545 const TemplateURL* default_url = providers_.GetDefaultProviderURL();
546 const TemplateURL* keyword_url = providers_.GetKeywordProviderURL();
[email protected]83c726482008-09-10 06:36:34547 if (profile_->IsOffTheRecord() ||
[email protected]85b8d6f2012-05-08 20:53:47548 ((!default_url || default_url->suggestions_url().empty()) &&
549 (!keyword_url || keyword_url->suggestions_url().empty())) ||
[email protected]83c726482008-09-10 06:36:34550 !profile_->GetPrefs()->GetBoolean(prefs::kSearchSuggestEnabled))
551 return false;
552
[email protected]cac59d32010-08-09 23:23:14553 // If the input type might be a URL, we take extra care so that private data
[email protected]83c726482008-09-10 06:36:34554 // isn't sent to the server.
[email protected]83c726482008-09-10 06:36:34555
[email protected]cac59d32010-08-09 23:23:14556 // FORCED_QUERY means the user is explicitly asking us to search for this, so
557 // we assume it isn't a URL and/or there isn't private data.
[email protected]3dc75b12014-06-08 00:02:22558 if (input_.type() == metrics::OmniboxInputType::FORCED_QUERY)
[email protected]cac59d32010-08-09 23:23:14559 return true;
[email protected]83c726482008-09-10 06:36:34560
[email protected]f608ea102013-03-18 15:08:09561 // Next we check the scheme. If this is UNKNOWN/URL with a scheme that isn't
562 // http/https/ftp, we shouldn't send it. Sending things like file: and data:
563 // is both a waste of time and a disclosure of potentially private, local
564 // data. Other "schemes" may actually be usernames, and we don't want to send
565 // passwords. If the scheme is OK, we still need to check other cases below.
566 // If this is QUERY, then the presence of these schemes means the user
567 // explicitly typed one, and thus this is probably a URL that's being entered
568 // and happens to currently be invalid -- in which case we again want to run
569 // our checks below. Other QUERY cases are less likely to be URLs and thus we
570 // assume we're OK.
[email protected]e8ca69c2014-05-07 15:31:19571 if (!LowerCaseEqualsASCII(input_.scheme(), url::kHttpScheme) &&
572 !LowerCaseEqualsASCII(input_.scheme(), url::kHttpsScheme) &&
[email protected]cca6f392014-05-28 21:32:26573 !LowerCaseEqualsASCII(input_.scheme(), url::kFtpScheme))
[email protected]3dc75b12014-06-08 00:02:22574 return (input_.type() == metrics::OmniboxInputType::QUERY);
[email protected]cac59d32010-08-09 23:23:14575
576 // Don't send URLs with usernames, queries or refs. Some of these are
577 // private, and the Suggest server is unlikely to have any useful results
578 // for any of them. Also don't send URLs with ports, as we may initially
579 // think that a username + password is a host + port (and we don't want to
580 // send usernames/passwords), and even if the port really is a port, the
581 // server is once again unlikely to have and useful results.
[email protected]825e16f2013-09-30 23:52:58582 // Note that we only block based on refs if the input is URL-typed, as search
583 // queries can legitimately have #s in them which the URL parser
584 // overaggressively categorizes as a url with a ref.
[email protected]b45334502014-04-30 19:44:05585 const url::Parsed& parts = input_.parts();
[email protected]cac59d32010-08-09 23:23:14586 if (parts.username.is_nonempty() || parts.port.is_nonempty() ||
[email protected]825e16f2013-09-30 23:52:58587 parts.query.is_nonempty() ||
[email protected]3dc75b12014-06-08 00:02:22588 (parts.ref.is_nonempty() &&
589 (input_.type() == metrics::OmniboxInputType::URL)))
[email protected]cac59d32010-08-09 23:23:14590 return false;
591
592 // Don't send anything for https except the hostname. Hostnames are OK
593 // because they are visible when the TCP connection is established, but the
594 // specific path may reveal private information.
[email protected]e8ca69c2014-05-07 15:31:19595 if (LowerCaseEqualsASCII(input_.scheme(), url::kHttpsScheme) &&
[email protected]a2fedb1e2011-01-25 15:23:36596 parts.path.is_nonempty())
[email protected]cac59d32010-08-09 23:23:14597 return false;
[email protected]83c726482008-09-10 06:36:34598
599 return true;
600}
601
[email protected]71b46152013-05-03 16:39:20602void SearchProvider::RemoveAllStaleResults() {
[email protected]dc735c02013-11-12 23:23:41603 if (keyword_input_.text().empty()) {
[email protected]1e1550e2013-05-02 17:37:51604 // User is either in keyword mode with a blank input or out of
605 // keyword mode entirely.
[email protected]cc1526e2013-05-17 04:04:24606 keyword_results_.Clear();
[email protected]1e1550e2013-05-02 17:37:51607 }
[email protected]d1f0a7f2012-06-05 10:26:42608}
609
[email protected]d1f0a7f2012-06-05 10:26:42610void SearchProvider::ApplyCalculatedRelevance() {
[email protected]cc1526e2013-05-17 04:04:24611 ApplyCalculatedSuggestRelevance(&keyword_results_.suggest_results);
612 ApplyCalculatedSuggestRelevance(&default_results_.suggest_results);
613 ApplyCalculatedNavigationRelevance(&keyword_results_.navigation_results);
614 ApplyCalculatedNavigationRelevance(&default_results_.navigation_results);
[email protected]cc1526e2013-05-17 04:04:24615 default_results_.verbatim_relevance = -1;
616 keyword_results_.verbatim_relevance = -1;
[email protected]d1f0a7f2012-06-05 10:26:42617}
618
[email protected]0b9575f2014-07-30 11:58:37619void SearchProvider::ApplyCalculatedSuggestRelevance(
620 SearchSuggestionParser::SuggestResults* list) {
[email protected]d1f0a7f2012-06-05 10:26:42621 for (size_t i = 0; i < list->size(); ++i) {
[email protected]0b9575f2014-07-30 11:58:37622 SearchSuggestionParser::SuggestResult& result = (*list)[i];
[email protected]188b50c2013-03-28 07:19:42623 result.set_relevance(
624 result.CalculateRelevance(input_, providers_.has_keyword_provider()) +
625 (list->size() - i - 1));
[email protected]d30268a2013-06-25 22:31:07626 result.set_relevance_from_server(false);
[email protected]d1f0a7f2012-06-05 10:26:42627 }
628}
629
[email protected]188b50c2013-03-28 07:19:42630void SearchProvider::ApplyCalculatedNavigationRelevance(
[email protected]0b9575f2014-07-30 11:58:37631 SearchSuggestionParser::NavigationResults* list) {
[email protected]d1f0a7f2012-06-05 10:26:42632 for (size_t i = 0; i < list->size(); ++i) {
[email protected]0b9575f2014-07-30 11:58:37633 SearchSuggestionParser::NavigationResult& result = (*list)[i];
[email protected]188b50c2013-03-28 07:19:42634 result.set_relevance(
635 result.CalculateRelevance(input_, providers_.has_keyword_provider()) +
636 (list->size() - i - 1));
[email protected]d30268a2013-06-25 22:31:07637 result.set_relevance_from_server(false);
[email protected]d1f0a7f2012-06-05 10:26:42638 }
639}
640
[email protected]15fb2aa2012-05-22 22:52:59641net::URLFetcher* SearchProvider::CreateSuggestFetcher(
[email protected]7cc6e5632011-10-25 17:56:12642 int id,
[email protected]9ff91722012-09-07 05:29:12643 const TemplateURL* template_url,
[email protected]14710852013-02-05 23:45:41644 const AutocompleteInput& input) {
[email protected]9ff91722012-09-07 05:29:12645 if (!template_url || template_url->suggestions_url().empty())
646 return NULL;
647
648 // Bail if the suggestion URL is invalid with the given replacements.
[email protected]14710852013-02-05 23:45:41649 TemplateURLRef::SearchTermsArgs search_term_args(input.text());
[email protected]420472b22014-06-10 13:34:43650 search_term_args.input_type = input.type();
[email protected]14710852013-02-05 23:45:41651 search_term_args.cursor_position = input.cursor_position();
[email protected]d5015ca2013-08-08 22:04:18652 search_term_args.page_classification = input.current_page_classification();
[email protected]2ef2a6642014-07-30 05:50:29653 if (OmniboxFieldTrial::EnableAnswersInSuggest()) {
[email protected]20184242014-05-14 02:57:42654 search_term_args.session_token = GetSessionToken();
[email protected]2ef2a6642014-07-30 05:50:29655 if (!prefetch_data_.full_query_text.empty()) {
656 search_term_args.prefetch_query =
657 base::UTF16ToUTF8(last_answer_seen_.full_query_text);
658 search_term_args.prefetch_query_type =
659 base::UTF16ToUTF8(last_answer_seen_.query_type);
660 }
661 }
[email protected]9ff91722012-09-07 05:29:12662 GURL suggest_url(template_url->suggestions_url_ref().ReplaceSearchTerms(
[email protected]ce7ee5f2014-06-16 23:41:19663 search_term_args,
664 providers_.template_url_service()->search_terms_data()));
[email protected]9ff91722012-09-07 05:29:12665 if (!suggest_url.is_valid())
666 return NULL;
[email protected]9b9fa672013-11-07 06:04:52667 // Send the current page URL if user setting and URL requirements are met and
668 // the user is in the field trial.
669 if (CanSendURL(current_page_url_, suggest_url, template_url,
670 input.current_page_classification(), profile_) &&
671 OmniboxFieldTrial::InZeroSuggestAfterTypingFieldTrial()) {
672 search_term_args.current_page_url = current_page_url_.spec();
673 // Create the suggest URL again with the current page URL.
674 suggest_url = GURL(template_url->suggestions_url_ref().ReplaceSearchTerms(
[email protected]ce7ee5f2014-06-16 23:41:19675 search_term_args,
676 providers_.template_url_service()->search_terms_data()));
[email protected]9b9fa672013-11-07 06:04:52677 }
[email protected]9ff91722012-09-07 05:29:12678
679 suggest_results_pending_++;
680 LogOmniboxSuggestRequest(REQUEST_SENT);
681
682 net::URLFetcher* fetcher =
683 net::URLFetcher::Create(id, suggest_url, net::URLFetcher::GET, this);
[email protected]7cc6e5632011-10-25 17:56:12684 fetcher->SetRequestContext(profile_->GetRequestContext());
[email protected]d3cf8682f02012-02-29 23:29:34685 fetcher->SetLoadFlags(net::LOAD_DO_NOT_SAVE_COOKIES);
[email protected]bd3b4712012-12-18 17:01:30686 // Add Chrome experiment state to the request headers.
687 net::HttpRequestHeaders headers;
[email protected]71011c1682014-07-09 17:19:16688 variations::VariationsHttpHeaderProvider::GetInstance()->AppendHeaders(
[email protected]bd3b4712012-12-18 17:01:30689 fetcher->GetOriginalURL(), profile_->IsOffTheRecord(), false, &headers);
690 fetcher->SetExtraRequestHeaders(headers.ToString());
[email protected]257ab712009-04-14 17:16:24691 fetcher->Start();
692 return fetcher;
693}
694
[email protected]344946a12012-12-20 12:03:42695void SearchProvider::ConvertResultsToAutocompleteMatches() {
initial.commit09911bf2008-07-26 23:55:29696 // Convert all the results to matches and add them to a map, so we can keep
697 // the most relevant match for each result.
[email protected]31afdf72013-09-26 04:29:36698 base::TimeTicks start_time(base::TimeTicks::Now());
initial.commit09911bf2008-07-26 23:55:29699 MatchMap map;
[email protected]bc8bb0cd2013-06-24 21:50:23700 const base::Time no_time;
[email protected]cc1526e2013-05-17 04:04:24701 int did_not_accept_keyword_suggestion =
702 keyword_results_.suggest_results.empty() ?
initial.commit09911bf2008-07-26 23:55:29703 TemplateURLRef::NO_SUGGESTIONS_AVAILABLE :
704 TemplateURLRef::NO_SUGGESTION_CHOSEN;
initial.commit09911bf2008-07-26 23:55:29705
[email protected]d30268a2013-06-25 22:31:07706 bool relevance_from_server;
707 int verbatim_relevance = GetVerbatimRelevance(&relevance_from_server);
[email protected]cc1526e2013-05-17 04:04:24708 int did_not_accept_default_suggestion =
709 default_results_.suggest_results.empty() ?
[email protected]55ce8f12012-05-09 04:44:08710 TemplateURLRef::NO_SUGGESTIONS_AVAILABLE :
711 TemplateURLRef::NO_SUGGESTION_CHOSEN;
[email protected]d1f0a7f2012-06-05 10:26:42712 if (verbatim_relevance > 0) {
[email protected]c2ca3fd2014-03-22 03:07:44713 const base::string16& trimmed_verbatim =
714 base::CollapseWhitespace(input_.text(), false);
[email protected]0b9575f2014-07-30 11:58:37715 SearchSuggestionParser::SuggestResult verbatim(
[email protected]c2ca3fd2014-03-22 03:07:44716 trimmed_verbatim, AutocompleteMatchType::SEARCH_WHAT_YOU_TYPED,
[email protected]7ec287e2014-05-16 02:50:08717 trimmed_verbatim, base::string16(), base::string16(), base::string16(),
718 base::string16(), std::string(), std::string(), false,
719 verbatim_relevance, relevance_from_server, false,
[email protected]c2ca3fd2014-03-22 03:07:44720 trimmed_verbatim);
[email protected]57482a72014-03-14 22:27:37721 AddMatchToMap(verbatim, std::string(), did_not_accept_default_suggestion,
722 false, &map);
[email protected]d1f0a7f2012-06-05 10:26:42723 }
[email protected]5423e562013-02-07 03:58:45724 if (!keyword_input_.text().empty()) {
725 const TemplateURL* keyword_url = providers_.GetKeywordProviderURL();
726 // We only create the verbatim search query match for a keyword
727 // if it's not an extension keyword. Extension keywords are handled
728 // in KeywordProvider::Start(). (Extensions are complicated...)
729 // Note: in this provider, SEARCH_OTHER_ENGINE must correspond
730 // to the keyword verbatim search query. Do not create other matches
731 // of type SEARCH_OTHER_ENGINE.
[email protected]bdcbcd82013-10-28 13:40:25732 if (keyword_url &&
733 (keyword_url->GetType() != TemplateURL::OMNIBOX_API_EXTENSION)) {
[email protected]d30268a2013-06-25 22:31:07734 bool keyword_relevance_from_server;
735 const int keyword_verbatim_relevance =
736 GetKeywordVerbatimRelevance(&keyword_relevance_from_server);
[email protected]dab8d52d2013-03-05 07:35:28737 if (keyword_verbatim_relevance > 0) {
[email protected]c2ca3fd2014-03-22 03:07:44738 const base::string16& trimmed_verbatim =
739 base::CollapseWhitespace(keyword_input_.text(), false);
[email protected]0b9575f2014-07-30 11:58:37740 SearchSuggestionParser::SuggestResult verbatim(
[email protected]c2ca3fd2014-03-22 03:07:44741 trimmed_verbatim, AutocompleteMatchType::SEARCH_OTHER_ENGINE,
742 trimmed_verbatim, base::string16(), base::string16(),
[email protected]7ec287e2014-05-16 02:50:08743 base::string16(), base::string16(), std::string(), std::string(),
744 true, keyword_verbatim_relevance, keyword_relevance_from_server,
745 false, trimmed_verbatim);
[email protected]57482a72014-03-14 22:27:37746 AddMatchToMap(verbatim, std::string(),
747 did_not_accept_keyword_suggestion, false, &map);
[email protected]dab8d52d2013-03-05 07:35:28748 }
[email protected]5423e562013-02-07 03:58:45749 }
750 }
[email protected]257ab712009-04-14 17:16:24751 AddHistoryResultsToMap(keyword_history_results_, true,
752 did_not_accept_keyword_suggestion, &map);
753 AddHistoryResultsToMap(default_history_results_, false,
754 did_not_accept_default_suggestion, &map);
755
[email protected]d1cb6a822013-09-18 19:43:00756 AddSuggestResultsToMap(keyword_results_.suggest_results,
757 keyword_results_.metadata, &map);
[email protected]987fad782013-08-28 06:23:18758 AddSuggestResultsToMap(default_results_.suggest_results,
759 default_results_.metadata, &map);
initial.commit09911bf2008-07-26 23:55:29760
[email protected]d30268a2013-06-25 22:31:07761 ACMatches matches;
initial.commit09911bf2008-07-26 23:55:29762 for (MatchMap::const_iterator i(map.begin()); i != map.end(); ++i)
[email protected]d30268a2013-06-25 22:31:07763 matches.push_back(i->second);
initial.commit09911bf2008-07-26 23:55:29764
[email protected]d30268a2013-06-25 22:31:07765 AddNavigationResultsToMatches(keyword_results_.navigation_results, &matches);
766 AddNavigationResultsToMatches(default_results_.navigation_results, &matches);
initial.commit09911bf2008-07-26 23:55:29767
[email protected]d30268a2013-06-25 22:31:07768 // Now add the most relevant matches to |matches_|. We take up to kMaxMatches
769 // suggest/navsuggest matches, regardless of origin. If Instant Extended is
770 // enabled and we have server-provided (and thus hopefully more accurate)
771 // scores for some suggestions, we allow more of those, until we reach
772 // AutocompleteResult::kMaxMatches total matches (that is, enough to fill the
773 // whole popup).
774 //
775 // We will always return any verbatim matches, no matter how we obtained their
776 // scores, unless we have already accepted AutocompleteResult::kMaxMatches
777 // higher-scoring matches under the conditions above.
778 std::sort(matches.begin(), matches.end(), &AutocompleteMatch::MoreRelevant);
779 matches_.clear();
[email protected]3723e6e2012-06-11 21:06:56780
[email protected]d30268a2013-06-25 22:31:07781 size_t num_suggestions = 0;
782 for (ACMatches::const_iterator i(matches.begin());
783 (i != matches.end()) &&
784 (matches_.size() < AutocompleteResult::kMaxMatches);
785 ++i) {
786 // SEARCH_OTHER_ENGINE is only used in the SearchProvider for the keyword
787 // verbatim result, so this condition basically means "if this match is a
788 // suggestion of some sort".
789 if ((i->type != AutocompleteMatchType::SEARCH_WHAT_YOU_TYPED) &&
790 (i->type != AutocompleteMatchType::SEARCH_OTHER_ENGINE)) {
791 // If we've already hit the limit on non-server-scored suggestions, and
792 // this isn't a server-scored suggestion we can add, skip it.
793 if ((num_suggestions >= kMaxMatches) &&
794 (!chrome::IsInstantExtendedAPIEnabled() ||
795 (i->GetAdditionalInfo(kRelevanceFromServerKey) != kTrue))) {
796 continue;
797 }
798
799 ++num_suggestions;
800 }
801
802 matches_.push_back(*i);
803 }
[email protected]31afdf72013-09-26 04:29:36804 UMA_HISTOGRAM_TIMES("Omnibox.SearchProvider.ConvertResultsTime",
805 base::TimeTicks::Now() - start_time);
[email protected]344946a12012-12-20 12:03:42806}
807
[email protected]89bd27d12014-04-12 17:36:23808ACMatches::const_iterator SearchProvider::FindTopMatch() const {
[email protected]0a8718b12013-11-13 18:41:31809 ACMatches::const_iterator it = matches_.begin();
810 while ((it != matches_.end()) && !it->allowed_to_be_default_match)
811 ++it;
812 return it;
[email protected]9dfb4d362013-04-05 02:15:12813}
814
[email protected]1c1e7842013-11-22 16:28:16815bool SearchProvider::HasKeywordDefaultMatchInKeywordMode() const {
816 const TemplateURL* keyword_url = providers_.GetKeywordProviderURL();
817 // If the user is not in keyword mode, return true to say that this
818 // constraint is not violated.
819 if (keyword_url == NULL)
820 return true;
821 for (ACMatches::const_iterator it = matches_.begin(); it != matches_.end();
822 ++it) {
823 if ((it->keyword == keyword_url->keyword()) &&
824 it->allowed_to_be_default_match)
825 return true;
826 }
827 return false;
828}
829
[email protected]89bd27d12014-04-12 17:36:23830bool SearchProvider::IsTopMatchSearchWithURLInput() const {
831 ACMatches::const_iterator first_match = FindTopMatch();
[email protected]3dc75b12014-06-08 00:02:22832 return (input_.type() == metrics::OmniboxInputType::URL) &&
[email protected]0a8718b12013-11-13 18:41:31833 (first_match != matches_.end()) &&
834 (first_match->relevance > CalculateRelevanceForVerbatim()) &&
[email protected]78981d8c2014-05-09 15:05:47835 (first_match->type != AutocompleteMatchType::NAVSUGGEST) &&
836 (first_match->type != AutocompleteMatchType::NAVSUGGEST_PERSONALIZED);
[email protected]344946a12012-12-20 12:03:42837}
838
[email protected]257ab712009-04-14 17:16:24839void SearchProvider::AddNavigationResultsToMatches(
[email protected]0b9575f2014-07-30 11:58:37840 const SearchSuggestionParser::NavigationResults& navigation_results,
[email protected]d30268a2013-06-25 22:31:07841 ACMatches* matches) {
[email protected]0b9575f2014-07-30 11:58:37842 for (SearchSuggestionParser::NavigationResults::const_iterator it =
843 navigation_results.begin(); it != navigation_results.end(); ++it) {
[email protected]d30268a2013-06-25 22:31:07844 matches->push_back(NavigationToMatch(*it));
[email protected]bc8bb0cd2013-06-24 21:50:23845 // In the absence of suggested relevance scores, use only the single
846 // highest-scoring result. (The results are already sorted by relevance.)
[email protected]d30268a2013-06-25 22:31:07847 if (!it->relevance_from_server())
[email protected]bc8bb0cd2013-06-24 21:50:23848 return;
[email protected]257ab712009-04-14 17:16:24849 }
850}
851
852void SearchProvider::AddHistoryResultsToMap(const HistoryResults& results,
853 bool is_keyword,
854 int did_not_accept_suggestion,
855 MatchMap* map) {
[email protected]51124552011-07-16 01:37:10856 if (results.empty())
857 return;
858
[email protected]31afdf72013-09-26 04:29:36859 base::TimeTicks start_time(base::TimeTicks::Now());
[email protected]d7ad4772012-06-01 03:12:54860 bool prevent_inline_autocomplete = input_.prevent_inline_autocomplete() ||
[email protected]3dc75b12014-06-08 00:02:22861 (input_.type() == metrics::OmniboxInputType::URL);
[email protected]0085863a2013-12-06 21:19:03862 const base::string16& input_text =
[email protected]14710852013-02-05 23:45:41863 is_keyword ? keyword_input_.text() : input_.text();
[email protected]51124552011-07-16 01:37:10864 bool input_multiple_words = HasMultipleWords(input_text);
865
[email protected]0b9575f2014-07-30 11:58:37866 SearchSuggestionParser::SuggestResults scored_results;
[email protected]55ce8f12012-05-09 04:44:08867 if (!prevent_inline_autocomplete && input_multiple_words) {
868 // ScoreHistoryResults() allows autocompletion of multi-word, 1-visit
869 // queries if the input also has multiple words. But if we were already
[email protected]f13a2132014-04-22 08:13:52870 // scoring a multi-word, multi-visit query aggressively, and the current
871 // input is still a prefix of it, then changing the suggestion suddenly
872 // feels wrong. To detect this case, first score as if only one word has
873 // been typed, then check if the best result came from aggressive search
874 // history scoring. If it did, then just keep that score set. This
875 // 1200 the lowest possible score in CalculateRelevanceForHistory()'s
876 // aggressive-scoring curve.
[email protected]55ce8f12012-05-09 04:44:08877 scored_results = ScoreHistoryResults(results, prevent_inline_autocomplete,
878 false, input_text, is_keyword);
[email protected]f13a2132014-04-22 08:13:52879 if ((scored_results.front().relevance() < 1200) ||
[email protected]9dfb4d362013-04-05 02:15:12880 !HasMultipleWords(scored_results.front().suggestion()))
[email protected]55ce8f12012-05-09 04:44:08881 scored_results.clear(); // Didn't detect the case above, score normally.
[email protected]51124552011-07-16 01:37:10882 }
[email protected]55ce8f12012-05-09 04:44:08883 if (scored_results.empty())
884 scored_results = ScoreHistoryResults(results, prevent_inline_autocomplete,
885 input_multiple_words, input_text,
886 is_keyword);
[email protected]0b9575f2014-07-30 11:58:37887 for (SearchSuggestionParser::SuggestResults::const_iterator i(
888 scored_results.begin()); i != scored_results.end(); ++i) {
[email protected]57482a72014-03-14 22:27:37889 AddMatchToMap(*i, std::string(), did_not_accept_suggestion, true, map);
[email protected]51124552011-07-16 01:37:10890 }
[email protected]31afdf72013-09-26 04:29:36891 UMA_HISTOGRAM_TIMES("Omnibox.SearchProvider.AddHistoryResultsTime",
892 base::TimeTicks::Now() - start_time);
[email protected]51124552011-07-16 01:37:10893}
894
[email protected]0b9575f2014-07-30 11:58:37895SearchSuggestionParser::SuggestResults SearchProvider::ScoreHistoryResults(
[email protected]51124552011-07-16 01:37:10896 const HistoryResults& results,
897 bool base_prevent_inline_autocomplete,
898 bool input_multiple_words,
[email protected]0085863a2013-12-06 21:19:03899 const base::string16& input_text,
[email protected]51124552011-07-16 01:37:10900 bool is_keyword) {
[email protected]0b9575f2014-07-30 11:58:37901 SearchSuggestionParser::SuggestResults scored_results;
[email protected]ab5fd2f2014-07-17 19:18:52902 // True if the user has asked this exact query previously.
903 bool found_what_you_typed_match = false;
[email protected]78e5e432013-08-03 02:10:10904 const bool prevent_search_history_inlining =
905 OmniboxFieldTrial::SearchHistoryPreventInlining(
906 input_.current_page_classification());
[email protected]c2ca3fd2014-03-22 03:07:44907 const base::string16& trimmed_input =
908 base::CollapseWhitespace(input_text, false);
[email protected]257ab712009-04-14 17:16:24909 for (HistoryResults::const_iterator i(results.begin()); i != results.end();
910 ++i) {
[email protected]c2ca3fd2014-03-22 03:07:44911 const base::string16& trimmed_suggestion =
912 base::CollapseWhitespace(i->term, false);
913
[email protected]51124552011-07-16 01:37:10914 // Don't autocomplete multi-word queries that have only been seen once
915 // unless the user has typed more than one word.
916 bool prevent_inline_autocomplete = base_prevent_inline_autocomplete ||
[email protected]c2ca3fd2014-03-22 03:07:44917 (!input_multiple_words && (i->visits < 2) &&
918 HasMultipleWords(trimmed_suggestion));
[email protected]51124552011-07-16 01:37:10919
[email protected]78e5e432013-08-03 02:10:10920 int relevance = CalculateRelevanceForHistory(
921 i->time, is_keyword, !prevent_inline_autocomplete,
922 prevent_search_history_inlining);
[email protected]ab5fd2f2014-07-17 19:18:52923 // Add the match to |scored_results| by putting the what-you-typed match
924 // on the front and appending all other matches. We want the what-you-
925 // typed match to always be first.
[email protected]0b9575f2014-07-30 11:58:37926 SearchSuggestionParser::SuggestResults::iterator insertion_position =
927 scored_results.end();
[email protected]ab5fd2f2014-07-17 19:18:52928 if (trimmed_suggestion == trimmed_input) {
929 found_what_you_typed_match = true;
930 insertion_position = scored_results.begin();
931 }
[email protected]0b9575f2014-07-30 11:58:37932 scored_results.insert(
933 insertion_position,
934 SearchSuggestionParser::SuggestResult(
935 trimmed_suggestion, AutocompleteMatchType::SEARCH_HISTORY,
936 trimmed_suggestion, base::string16(), base::string16(),
937 base::string16(), base::string16(), std::string(), std::string(),
938 is_keyword, relevance, false, false, trimmed_input));
[email protected]257ab712009-04-14 17:16:24939 }
[email protected]51124552011-07-16 01:37:10940
941 // History returns results sorted for us. However, we may have docked some
[email protected]ab5fd2f2014-07-17 19:18:52942 // results' scores, so things are no longer in order. While keeping the
943 // what-you-typed match at the front (if it exists), do a stable sort to get
[email protected]51124552011-07-16 01:37:10944 // things back in order without otherwise disturbing results with equal
945 // scores, then force the scores to be unique, so that the order in which
946 // they're shown is deterministic.
[email protected]ab5fd2f2014-07-17 19:18:52947 std::stable_sort(scored_results.begin() +
948 (found_what_you_typed_match ? 1 : 0),
949 scored_results.end(),
[email protected]55ce8f12012-05-09 04:44:08950 CompareScoredResults());
[email protected]7e3b77f2014-07-25 02:29:44951
952 // Don't autocomplete to search terms that would normally be treated as URLs
953 // when typed. For example, if the user searched for "google.com" and types
954 // "goog", don't autocomplete to the search term "google.com". Otherwise,
955 // the input will look like a URL but act like a search, which is confusing.
956 // The 1200 relevance score threshold in the test below is the lowest
957 // possible score in CalculateRelevanceForHistory()'s aggressive-scoring
958 // curve. This is an appropriate threshold to use to decide if we're overly
959 // aggressively inlining because, if we decide the answer is yes, the
960 // way we resolve it it to not use the aggressive-scoring curve.
961 // NOTE: We don't check for autocompleting to URLs in the following cases:
962 // * When inline autocomplete is disabled, we won't be inline autocompleting
963 // this term, so we don't need to worry about confusion as much. This
964 // also prevents calling Classify() again from inside the classifier
965 // (which will corrupt state and likely crash), since the classifier
966 // always disables inline autocomplete.
967 // * When the user has typed the whole string before as a query, then it's
968 // likely the user has no expectation that term should be interpreted as
969 // as a URL, so we need not do anything special to preserve user
970 // expectation.
971 AutocompleteClassifier* classifier =
972 AutocompleteClassifierFactory::GetForProfile(profile_);
[email protected]51124552011-07-16 01:37:10973 int last_relevance = 0;
[email protected]7e3b77f2014-07-25 02:29:44974 if (!base_prevent_inline_autocomplete && !found_what_you_typed_match &&
975 classifier && (scored_results.front().relevance() >= 1200)) {
976 AutocompleteMatch match;
977 classifier->Classify(scored_results.front().suggestion(), false, false,
978 input_.current_page_classification(), &match, NULL);
979 // Demote this match that would normally be interpreted as a URL to have
980 // the highest score a previously-issued search query could have when
981 // scoring with the non-aggressive method. A consequence of demoting
982 // by revising |last_relevance| is that this match and all following
983 // matches get demoted; the relative order of matches is preserved.
984 // One could imagine demoting only those matches that might cause
985 // confusion (which, by the way, might change the relative order of
986 // matches. We have decided to go with the simple demote-all approach
987 // because selective demotion requires multiple Classify() calls and
988 // such calls can be expensive (as expensive as running the whole
989 // autocomplete system).
990 if (!AutocompleteMatch::IsSearchType(match.type)) {
991 last_relevance = CalculateRelevanceForHistory(
992 base::Time::Now(), is_keyword, false,
993 prevent_search_history_inlining);
994 }
995 }
996
[email protected]0b9575f2014-07-30 11:58:37997 for (SearchSuggestionParser::SuggestResults::iterator i(
998 scored_results.begin()); i != scored_results.end(); ++i) {
[email protected]7e3b77f2014-07-25 02:29:44999 if ((last_relevance != 0) && (i->relevance() >= last_relevance))
[email protected]55ce8f12012-05-09 04:44:081000 i->set_relevance(last_relevance - 1);
1001 last_relevance = i->relevance();
[email protected]51124552011-07-16 01:37:101002 }
1003
[email protected]55ce8f12012-05-09 04:44:081004 return scored_results;
[email protected]257ab712009-04-14 17:16:241005}
1006
[email protected]0b9575f2014-07-30 11:58:371007void SearchProvider::AddSuggestResultsToMap(
1008 const SearchSuggestionParser::SuggestResults& results,
1009 const std::string& metadata,
1010 MatchMap* map) {
[email protected]9487b392014-02-14 02:48:181011 for (size_t i = 0; i < results.size(); ++i)
[email protected]57482a72014-03-14 22:27:371012 AddMatchToMap(results[i], metadata, i, false, map);
initial.commit09911bf2008-07-26 23:55:291013}
1014
[email protected]d30268a2013-06-25 22:31:071015int SearchProvider::GetVerbatimRelevance(bool* relevance_from_server) const {
[email protected]dc6943b2012-06-19 06:39:561016 // Use the suggested verbatim relevance score if it is non-negative (valid),
1017 // if inline autocomplete isn't prevented (always show verbatim on backspace),
[email protected]1beee342012-06-19 22:22:281018 // and if it won't suppress verbatim, leaving no default provider matches.
1019 // Otherwise, if the default provider returned no matches and was still able
[email protected]dc6943b2012-06-19 06:39:561020 // to suppress verbatim, the user would have no search/nav matches and may be
[email protected]1beee342012-06-19 22:22:281021 // left unable to search using their default provider from the omnibox.
[email protected]dc6943b2012-06-19 06:39:561022 // Check for results on each verbatim calculation, as results from older
1023 // queries (on previous input) may be trimmed for failing to inline new input.
[email protected]bc8bb0cd2013-06-24 21:50:231024 bool use_server_relevance =
1025 (default_results_.verbatim_relevance >= 0) &&
[email protected]dab8d52d2013-03-05 07:35:281026 !input_.prevent_inline_autocomplete() &&
[email protected]bc8bb0cd2013-06-24 21:50:231027 ((default_results_.verbatim_relevance > 0) ||
[email protected]cc1526e2013-05-17 04:04:241028 !default_results_.suggest_results.empty() ||
[email protected]bc8bb0cd2013-06-24 21:50:231029 !default_results_.navigation_results.empty());
[email protected]d30268a2013-06-25 22:31:071030 if (relevance_from_server)
1031 *relevance_from_server = use_server_relevance;
[email protected]bc8bb0cd2013-06-24 21:50:231032 return use_server_relevance ?
1033 default_results_.verbatim_relevance : CalculateRelevanceForVerbatim();
[email protected]382a0642012-06-06 06:13:521034}
[email protected]d1f0a7f2012-06-05 10:26:421035
[email protected]382a0642012-06-06 06:13:521036int SearchProvider::CalculateRelevanceForVerbatim() const {
[email protected]85b8d6f2012-05-08 20:53:471037 if (!providers_.keyword_provider().empty())
[email protected]52d08b12009-10-19 18:42:361038 return 250;
[email protected]dab8d52d2013-03-05 07:35:281039 return CalculateRelevanceForVerbatimIgnoringKeywordModeState();
1040}
[email protected]52d08b12009-10-19 18:42:361041
[email protected]dab8d52d2013-03-05 07:35:281042int SearchProvider::
1043 CalculateRelevanceForVerbatimIgnoringKeywordModeState() const {
initial.commit09911bf2008-07-26 23:55:291044 switch (input_.type()) {
[email protected]3dc75b12014-06-08 00:02:221045 case metrics::OmniboxInputType::UNKNOWN:
1046 case metrics::OmniboxInputType::QUERY:
1047 case metrics::OmniboxInputType::FORCED_QUERY:
[email protected]90fe2bb2013-01-15 03:42:131048 return kNonURLVerbatimRelevance;
initial.commit09911bf2008-07-26 23:55:291049
[email protected]3dc75b12014-06-08 00:02:221050 case metrics::OmniboxInputType::URL:
[email protected]52d08b12009-10-19 18:42:361051 return 850;
initial.commit09911bf2008-07-26 23:55:291052
1053 default:
1054 NOTREACHED();
1055 return 0;
1056 }
1057}
1058
[email protected]d30268a2013-06-25 22:31:071059int SearchProvider::GetKeywordVerbatimRelevance(
1060 bool* relevance_from_server) const {
[email protected]dab8d52d2013-03-05 07:35:281061 // Use the suggested verbatim relevance score if it is non-negative (valid),
1062 // if inline autocomplete isn't prevented (always show verbatim on backspace),
1063 // and if it won't suppress verbatim, leaving no keyword provider matches.
1064 // Otherwise, if the keyword provider returned no matches and was still able
1065 // to suppress verbatim, the user would have no search/nav matches and may be
1066 // left unable to search using their keyword provider from the omnibox.
1067 // Check for results on each verbatim calculation, as results from older
1068 // queries (on previous input) may be trimmed for failing to inline new input.
[email protected]bc8bb0cd2013-06-24 21:50:231069 bool use_server_relevance =
1070 (keyword_results_.verbatim_relevance >= 0) &&
[email protected]dab8d52d2013-03-05 07:35:281071 !input_.prevent_inline_autocomplete() &&
[email protected]bc8bb0cd2013-06-24 21:50:231072 ((keyword_results_.verbatim_relevance > 0) ||
[email protected]cc1526e2013-05-17 04:04:241073 !keyword_results_.suggest_results.empty() ||
[email protected]bc8bb0cd2013-06-24 21:50:231074 !keyword_results_.navigation_results.empty());
[email protected]d30268a2013-06-25 22:31:071075 if (relevance_from_server)
1076 *relevance_from_server = use_server_relevance;
[email protected]bc8bb0cd2013-06-24 21:50:231077 return use_server_relevance ?
1078 keyword_results_.verbatim_relevance :
1079 CalculateRelevanceForKeywordVerbatim(keyword_input_.type(),
1080 keyword_input_.prefer_keyword());
[email protected]5423e562013-02-07 03:58:451081}
1082
[email protected]51124552011-07-16 01:37:101083int SearchProvider::CalculateRelevanceForHistory(
[email protected]bc8bb0cd2013-06-24 21:50:231084 const base::Time& time,
[email protected]51124552011-07-16 01:37:101085 bool is_keyword,
[email protected]78e5e432013-08-03 02:10:101086 bool use_aggressive_method,
1087 bool prevent_search_history_inlining) const {
[email protected]aa613d62010-11-09 20:40:181088 // The relevance of past searches falls off over time. There are two distinct
1089 // equations used. If the first equation is used (searches to the primary
[email protected]78e5e432013-08-03 02:10:101090 // provider that we want to score aggressively), the score is in the range
1091 // 1300-1599 (unless |prevent_search_history_inlining|, in which case
[email protected]d8cd76b2013-07-10 09:46:161092 // it's in the range 1200-1299). If the second equation is used the
1093 // relevance of a search 15 minutes ago is discounted 50 points, while the
1094 // relevance of a search two weeks ago is discounted 450 points.
[email protected]bc8bb0cd2013-06-24 21:50:231095 double elapsed_time = std::max((base::Time::Now() - time).InSecondsF(), 0.0);
[email protected]188b50c2013-03-28 07:19:421096 bool is_primary_provider = is_keyword || !providers_.has_keyword_provider();
[email protected]78e5e432013-08-03 02:10:101097 if (is_primary_provider && use_aggressive_method) {
[email protected]aa613d62010-11-09 20:40:181098 // Searches with the past two days get a different curve.
[email protected]51124552011-07-16 01:37:101099 const double autocomplete_time = 2 * 24 * 60 * 60;
[email protected]aa613d62010-11-09 20:40:181100 if (elapsed_time < autocomplete_time) {
[email protected]d8cd76b2013-07-10 09:46:161101 int max_score = is_keyword ? 1599 : 1399;
[email protected]78e5e432013-08-03 02:10:101102 if (prevent_search_history_inlining)
[email protected]d8cd76b2013-07-10 09:46:161103 max_score = 1299;
1104 return max_score - static_cast<int>(99 *
[email protected]aa613d62010-11-09 20:40:181105 std::pow(elapsed_time / autocomplete_time, 2.5));
1106 }
1107 elapsed_time -= autocomplete_time;
1108 }
1109
[email protected]c3a4bd992010-08-18 20:25:011110 const int score_discount =
1111 static_cast<int>(6.5 * std::pow(elapsed_time, 0.3));
initial.commit09911bf2008-07-26 23:55:291112
[email protected]6c85aa02009-02-27 12:08:091113 // Don't let scores go below 0. Negative relevance scores are meaningful in
1114 // a different way.
initial.commit09911bf2008-07-26 23:55:291115 int base_score;
[email protected]51124552011-07-16 01:37:101116 if (is_primary_provider)
[email protected]3dc75b12014-06-08 00:02:221117 base_score = (input_.type() == metrics::OmniboxInputType::URL) ? 750 : 1050;
[email protected]51124552011-07-16 01:37:101118 else
1119 base_score = 200;
initial.commit09911bf2008-07-26 23:55:291120 return std::max(0, base_score - score_discount);
1121}
1122
initial.commit09911bf2008-07-26 23:55:291123AutocompleteMatch SearchProvider::NavigationToMatch(
[email protected]0b9575f2014-07-30 11:58:371124 const SearchSuggestionParser::NavigationResult& navigation) {
[email protected]5889bfb2014-03-19 00:26:481125 base::string16 input;
1126 const bool trimmed_whitespace = base::TrimWhitespace(
1127 navigation.from_keyword_provider() ?
1128 keyword_input_.text() : input_.text(),
1129 base::TRIM_TRAILING, &input) != base::TRIM_NONE;
[email protected]55ce8f12012-05-09 04:44:081130 AutocompleteMatch match(this, navigation.relevance(), false,
[email protected]78981d8c2014-05-09 15:05:471131 navigation.type());
[email protected]55ce8f12012-05-09 04:44:081132 match.destination_url = navigation.url();
[email protected]78981d8c2014-05-09 15:05:471133 BaseSearchProvider::SetDeletionURL(navigation.deletion_url(), &match);
[email protected]23db6492014-01-16 02:35:301134 // First look for the user's input inside the formatted url as it would be
[email protected]371dab12012-06-01 03:23:551135 // without trimming the scheme, so we can find matches at the beginning of the
1136 // scheme.
[email protected]371dab12012-06-01 03:23:551137 const URLPrefix* prefix =
[email protected]23db6492014-01-16 02:35:301138 URLPrefix::BestURLPrefix(navigation.formatted_url(), input);
[email protected]371dab12012-06-01 03:23:551139 size_t match_start = (prefix == NULL) ?
[email protected]23db6492014-01-16 02:35:301140 navigation.formatted_url().find(input) : prefix->prefix.length();
[email protected]d2445c82013-11-04 22:28:351141 bool trim_http = !AutocompleteInput::HasHTTPScheme(input) &&
1142 (!prefix || (match_start != 0));
[email protected]23db6492014-01-16 02:35:301143 const net::FormatUrlTypes format_types =
1144 net::kFormatUrlOmitAll & ~(trim_http ? 0 : net::kFormatUrlOmitHTTP);
[email protected]371dab12012-06-01 03:23:551145
[email protected]371dab12012-06-01 03:23:551146 const std::string languages(
1147 profile_->GetPrefs()->GetString(prefs::kAcceptLanguages));
[email protected]23db6492014-01-16 02:35:301148 size_t inline_autocomplete_offset = (prefix == NULL) ?
1149 base::string16::npos : (match_start + input.length());
[email protected]371dab12012-06-01 03:23:551150 match.fill_into_edit +=
[email protected]5655ea32014-06-21 05:28:081151 AutocompleteInput::FormattedStringWithEquivalentMeaning(
1152 navigation.url(),
[email protected]371dab12012-06-01 03:23:551153 net::FormatUrl(navigation.url(), languages, format_types,
1154 net::UnescapeRule::SPACES, NULL, NULL,
[email protected]5655ea32014-06-21 05:28:081155 &inline_autocomplete_offset),
[email protected]a817ed392014-06-27 05:03:001156 ChromeAutocompleteSchemeClassifier(profile_));
[email protected]14119032013-11-07 08:14:261157 // Preserve the forced query '?' prefix in |match.fill_into_edit|.
1158 // Otherwise, user edits to a suggestion would show non-Search results.
[email protected]3dc75b12014-06-08 00:02:221159 if (input_.type() == metrics::OmniboxInputType::FORCED_QUERY) {
[email protected]670d3232013-12-24 17:58:581160 match.fill_into_edit.insert(0, base::ASCIIToUTF16("?"));
[email protected]0085863a2013-12-06 21:19:031161 if (inline_autocomplete_offset != base::string16::npos)
[email protected]14119032013-11-07 08:14:261162 ++inline_autocomplete_offset;
1163 }
[email protected]6c94a1022014-02-21 03:48:041164 if (inline_autocomplete_offset != base::string16::npos) {
[email protected]518024c2013-07-19 23:40:251165 DCHECK(inline_autocomplete_offset <= match.fill_into_edit.length());
1166 match.inline_autocompletion =
1167 match.fill_into_edit.substr(inline_autocomplete_offset);
1168 }
[email protected]6c94a1022014-02-21 03:48:041169 // An inlineable navsuggestion can only be the default match when there
1170 // is no keyword provider active, lest it appear first and break the user
[email protected]5889bfb2014-03-19 00:26:481171 // out of keyword mode. It can also only be default if either the inline
1172 // autocompletion is empty or we're not preventing inline autocompletion.
1173 // Finally, if we have an inlineable navsuggestion with an inline completion
1174 // that we're not preventing, make sure we didn't trim any whitespace.
1175 // We don't want to claim http://foo.com/bar is inlineable against the
1176 // input "foo.com/b ".
[email protected]c7b8be02014-07-11 19:46:341177 match.allowed_to_be_default_match = (prefix != NULL) &&
[email protected]6c94a1022014-02-21 03:48:041178 (providers_.GetKeywordProviderURL() == NULL) &&
[email protected]5889bfb2014-03-19 00:26:481179 (match.inline_autocompletion.empty() ||
[email protected]78981d8c2014-05-09 15:05:471180 (!input_.prevent_inline_autocomplete() && !trimmed_whitespace));
[email protected]c7b8be02014-07-11 19:46:341181 match.EnsureUWYTIsAllowedToBeDefault(
1182 input_.canonicalized_url(), providers_.template_url_service());
[email protected]371dab12012-06-01 03:23:551183
[email protected]23db6492014-01-16 02:35:301184 match.contents = navigation.match_contents();
1185 match.contents_class = navigation.match_contents_class();
[email protected]55ce8f12012-05-09 04:44:081186 match.description = navigation.description();
[email protected]371dab12012-06-01 03:23:551187 AutocompleteMatch::ClassifyMatchInString(input, match.description,
1188 ACMatchClassification::NONE, &match.description_class);
[email protected]d30268a2013-06-25 22:31:071189
1190 match.RecordAdditionalInfo(
1191 kRelevanceFromServerKey,
1192 navigation.relevance_from_server() ? kTrue : kFalse);
[email protected]987fad782013-08-28 06:23:181193 match.RecordAdditionalInfo(kShouldPrefetchKey, kFalse);
[email protected]d30268a2013-06-25 22:31:071194
initial.commit09911bf2008-07-26 23:55:291195 return match;
1196}
[email protected]4ab4c7c2010-11-24 04:49:341197
1198void SearchProvider::UpdateDone() {
[email protected]2cdf1172012-08-26 12:21:331199 // We're done when the timer isn't running, there are no suggest queries
[email protected]5fac3782013-03-06 09:32:311200 // pending, and we're not waiting on Instant.
[email protected]e1290ee62013-06-26 18:31:151201 done_ = !timer_.IsRunning() && (suggest_results_pending_ == 0);
[email protected]4ab4c7c2010-11-24 04:49:341202}
[email protected]20184242014-05-14 02:57:421203
1204std::string SearchProvider::GetSessionToken() {
1205 base::TimeTicks current_time(base::TimeTicks::Now());
1206 // Renew token if it expired.
1207 if (current_time > token_expiration_time_) {
1208 const size_t kTokenBytes = 12;
1209 std::string raw_data;
1210 base::RandBytes(WriteInto(&raw_data, kTokenBytes + 1), kTokenBytes);
1211 base::Base64Encode(raw_data, &current_token_);
[email protected]ab2c31f72014-05-17 17:03:531212
1213 // Make the base64 encoded value URL and filename safe(see RFC 3548).
1214 std::replace(current_token_.begin(), current_token_.end(), '+', '-');
1215 std::replace(current_token_.begin(), current_token_.end(), '/', '_');
[email protected]20184242014-05-14 02:57:421216 }
1217
1218 // Extend expiration time another 60 seconds.
1219 token_expiration_time_ = current_time + base::TimeDelta::FromSeconds(60);
1220
1221 return current_token_;
1222}
[email protected]2ef2a6642014-07-30 05:50:291223
1224void SearchProvider::RegisterDisplayedAnswers(
1225 const AutocompleteResult& result) {
1226 if (result.empty())
1227 return;
1228
1229 // The answer must be in the first or second slot to be considered. It should
1230 // only be in the second slot if AutocompleteController ranked a local search
1231 // history or a verbatim item higher than the answer.
1232 AutocompleteResult::const_iterator match = result.begin();
1233 if (match->answer_contents.empty() && result.size() > 1)
1234 ++match;
1235 if (match->answer_contents.empty() || match->answer_type.empty() ||
1236 match->fill_into_edit.empty())
1237 return;
1238
1239 // Valid answer encountered, cache it for further queries.
1240 last_answer_seen_.full_query_text = match->fill_into_edit;
1241 last_answer_seen_.query_type = match->answer_type;
1242}
1243
1244void SearchProvider::DoAnswersQuery(const AutocompleteInput& input) {
1245 // If the query text starts with trimmed input, this is valid prefetch data.
1246 prefetch_data_ = StartsWith(last_answer_seen_.full_query_text,
1247 base::CollapseWhitespace(input.text(), false),
1248 false) ?
1249 last_answer_seen_ : AnswersQueryData();
1250}