blob: 0e492baad1e60eec9a9840cc8e57903c4046f379 [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:
122 bool operator()(const Result& a, const Result& b) {
123 // Sort in descending relevance order.
124 return a.relevance() > b.relevance();
125 }
126};
127
128
[email protected]3954c3a2012-04-10 20:17:55129// SearchProvider -------------------------------------------------------------
130
131// static
[email protected]24dbf2302013-04-05 16:59:25132int SearchProvider::kMinimumTimeBetweenSuggestQueriesMs = 100;
[email protected]3954c3a2012-04-10 20:17:55133
[email protected]bc8bb0cd2013-06-24 21:50:23134SearchProvider::SearchProvider(AutocompleteProviderListener* listener,
135 Profile* profile)
[email protected]02346202014-02-05 05:18:30136 : BaseSearchProvider(listener, profile, AutocompleteProvider::TYPE_SEARCH),
[email protected]cfa164bf2014-03-19 11:51:15137 providers_(TemplateURLServiceFactory::GetForProfile(profile)) {
[email protected]bc8bb0cd2013-06-24 21:50:23138}
139
[email protected]cb86ee6f2013-04-28 16:58:15140// static
[email protected]987fad782013-08-28 06:23:18141std::string SearchProvider::GetSuggestMetadata(const AutocompleteMatch& match) {
142 return match.GetAdditionalInfo(kSuggestMetadataKey);
143}
144
[email protected]bc8bb0cd2013-06-24 21:50:23145void SearchProvider::ResetSession() {
146 field_trial_triggered_in_session_ = false;
[email protected]4ab4c7c2010-11-24 04:49:34147}
148
[email protected]bc8bb0cd2013-06-24 21:50:23149SearchProvider::~SearchProvider() {
150}
151
[email protected]ee6110b2014-01-09 22:26:31152void SearchProvider::UpdateMatchContentsClass(const base::string16& input_text,
[email protected]23db6492014-01-16 02:35:30153 Results* results) {
154 for (SuggestResults::iterator sug_it = results->suggest_results.begin();
155 sug_it != results->suggest_results.end(); ++sug_it) {
[email protected]ee6110b2014-01-09 22:26:31156 sug_it->ClassifyMatchContents(false, input_text);
157 }
[email protected]23db6492014-01-16 02:35:30158 const std::string languages(
159 profile_->GetPrefs()->GetString(prefs::kAcceptLanguages));
160 for (NavigationResults::iterator nav_it = results->navigation_results.begin();
161 nav_it != results->navigation_results.end(); ++nav_it) {
162 nav_it->CalculateAndClassifyMatchContents(false, input_text, languages);
163 }
[email protected]ee6110b2014-01-09 22:26:31164}
165
166// static
[email protected]bc8bb0cd2013-06-24 21:50:23167int SearchProvider::CalculateRelevanceForKeywordVerbatim(
[email protected]332d17d22014-06-20 16:56:03168 metrics::OmniboxInputType::Type type,
[email protected]bc8bb0cd2013-06-24 21:50:23169 bool prefer_keyword) {
170 // This function is responsible for scoring verbatim query matches
171 // for non-extension keywords. KeywordProvider::CalculateRelevance()
172 // scores verbatim query matches for extension keywords, as well as
173 // for keyword matches (i.e., suggestions of a keyword itself, not a
174 // suggestion of a query on a keyword search engine). These two
175 // functions are currently in sync, but there's no reason we
176 // couldn't decide in the future to score verbatim matches
177 // differently for extension and non-extension keywords. If you
178 // make such a change, however, you should update this comment to
179 // describe it, so it's clear why the functions diverge.
180 if (prefer_keyword)
181 return 1500;
[email protected]3dc75b12014-06-08 00:02:22182 return (type == metrics::OmniboxInputType::QUERY) ? 1450 : 1100;
[email protected]bc8bb0cd2013-06-24 21:50:23183}
184
initial.commit09911bf2008-07-26 23:55:29185void SearchProvider::Start(const AutocompleteInput& input,
[email protected]8deeb952008-10-09 18:21:27186 bool minimal_changes) {
[email protected]04504c242013-01-22 21:08:55187 // Do our best to load the model as early as possible. This will reduce
188 // odds of having the model not ready when really needed (a non-empty input).
189 TemplateURLService* model = providers_.template_url_service();
190 DCHECK(model);
191 model->Load();
192
initial.commit09911bf2008-07-26 23:55:29193 matches_.clear();
[email protected]618d6e62012-12-16 05:55:57194 field_trial_triggered_ = false;
initial.commit09911bf2008-07-26 23:55:29195
[email protected]6c85aa02009-02-27 12:08:09196 // Can't return search/suggest results for bogus input or without a profile.
[email protected]3dc75b12014-06-08 00:02:22197 if (!profile_ || (input.type() == metrics::OmniboxInputType::INVALID)) {
[email protected]9950e5d52014-02-25 23:34:19198 Stop(true);
initial.commit09911bf2008-07-26 23:55:29199 return;
200 }
201
[email protected]14710852013-02-05 23:45:41202 keyword_input_ = input;
[email protected]257ab712009-04-14 17:16:24203 const TemplateURL* keyword_provider =
[email protected]14710852013-02-05 23:45:41204 KeywordProvider::GetSubstitutingTemplateURLForInput(model,
205 &keyword_input_);
206 if (keyword_provider == NULL)
207 keyword_input_.Clear();
208 else if (keyword_input_.text().empty())
[email protected]257ab712009-04-14 17:16:24209 keyword_provider = NULL;
[email protected]257ab712009-04-14 17:16:24210
[email protected]85b8d6f2012-05-08 20:53:47211 const TemplateURL* default_provider = model->GetDefaultSearchProvider();
[email protected]ce7ee5f2014-06-16 23:41:19212 if (default_provider &&
213 !default_provider->SupportsReplacement(model->search_terms_data()))
[email protected]257ab712009-04-14 17:16:24214 default_provider = NULL;
215
216 if (keyword_provider == default_provider)
[email protected]e17511f2011-07-13 14:09:18217 default_provider = NULL; // No use in querying the same provider twice.
[email protected]257ab712009-04-14 17:16:24218
219 if (!default_provider && !keyword_provider) {
220 // No valid providers.
[email protected]9950e5d52014-02-25 23:34:19221 Stop(true);
initial.commit09911bf2008-07-26 23:55:29222 return;
223 }
224
225 // If we're still running an old query but have since changed the query text
[email protected]257ab712009-04-14 17:16:24226 // or the providers, abort the query.
[email protected]0085863a2013-12-06 21:19:03227 base::string16 default_provider_keyword(default_provider ?
228 default_provider->keyword() : base::string16());
229 base::string16 keyword_provider_keyword(keyword_provider ?
230 keyword_provider->keyword() : base::string16());
[email protected]9e789742011-01-10 23:27:32231 if (!minimal_changes ||
[email protected]85b8d6f2012-05-08 20:53:47232 !providers_.equal(default_provider_keyword, keyword_provider_keyword)) {
[email protected]bb900e02013-03-14 14:15:29233 // Cancel any in-flight suggest requests.
[email protected]e1290ee62013-06-26 18:31:15234 if (!done_)
[email protected]e29249dc52012-07-19 17:33:50235 Stop(false);
[email protected]257ab712009-04-14 17:16:24236 }
initial.commit09911bf2008-07-26 23:55:29237
[email protected]85b8d6f2012-05-08 20:53:47238 providers_.set(default_provider_keyword, keyword_provider_keyword);
initial.commit09911bf2008-07-26 23:55:29239
240 if (input.text().empty()) {
241 // User typed "?" alone. Give them a placeholder result indicating what
242 // this syntax does.
[email protected]257ab712009-04-14 17:16:24243 if (default_provider) {
[email protected]69c579e2010-04-23 20:01:00244 AutocompleteMatch match;
245 match.provider = this;
[email protected]a2fedb1e2011-01-25 15:23:36246 match.contents.assign(l10n_util::GetStringUTF16(IDS_EMPTY_KEYWORD_VALUE));
[email protected]257ab712009-04-14 17:16:24247 match.contents_class.push_back(
[email protected]2c33dd22010-02-11 21:46:35248 ACMatchClassification(0, ACMatchClassification::NONE));
[email protected]85b8d6f2012-05-08 20:53:47249 match.keyword = providers_.default_provider();
[email protected]45f89a92013-08-12 13:41:36250 match.allowed_to_be_default_match = true;
[email protected]257ab712009-04-14 17:16:24251 matches_.push_back(match);
252 }
[email protected]9950e5d52014-02-25 23:34:19253 Stop(true);
initial.commit09911bf2008-07-26 23:55:29254 return;
255 }
256
257 input_ = input;
258
[email protected]e1290ee62013-06-26 18:31:15259 DoHistoryQuery(minimal_changes);
[email protected]2ef2a6642014-07-30 05:50:29260 DoAnswersQuery(input);
[email protected]e1290ee62013-06-26 18:31:15261 StartOrStopSuggestQuery(minimal_changes);
[email protected]344946a12012-12-20 12:03:42262 UpdateMatches();
initial.commit09911bf2008-07-26 23:55:29263}
264
[email protected]d4a94b92014-03-04 01:35:22265void SearchProvider::SortResults(bool is_keyword,
266 const base::ListValue* relevances,
267 Results* results) {
268 // Ignore suggested scores for non-keyword matches in keyword mode; if the
269 // server is allowed to score these, it could interfere with the user's
270 // ability to get good keyword results.
271 const bool abandon_suggested_scores =
272 !is_keyword && !providers_.keyword_provider().empty();
273 // Apply calculated relevance scores to suggestions if a valid list was
274 // not provided or we're abandoning suggested scores entirely.
275 if ((relevances == NULL) || abandon_suggested_scores) {
276 ApplyCalculatedSuggestRelevance(&results->suggest_results);
277 ApplyCalculatedNavigationRelevance(&results->navigation_results);
278 // If abandoning scores entirely, also abandon the verbatim score.
279 if (abandon_suggested_scores)
280 results->verbatim_relevance = -1;
281 }
282
283 // Keep the result lists sorted.
284 const CompareScoredResults comparator = CompareScoredResults();
285 std::stable_sort(results->suggest_results.begin(),
286 results->suggest_results.end(),
287 comparator);
288 std::stable_sort(results->navigation_results.begin(),
289 results->navigation_results.end(),
290 comparator);
291}
292
[email protected]cfa164bf2014-03-19 11:51:15293const TemplateURL* SearchProvider::GetTemplateURL(bool is_keyword) const {
294 return is_keyword ? providers_.GetKeywordProviderURL()
295 : providers_.GetDefaultProviderURL();
[email protected]9487b392014-02-14 02:48:18296}
297
[email protected]d4a94b92014-03-04 01:35:22298const AutocompleteInput SearchProvider::GetInput(bool is_keyword) const {
299 return is_keyword ? keyword_input_ : input_;
[email protected]9487b392014-02-14 02:48:18300}
301
[email protected]cfa164bf2014-03-19 11:51:15302BaseSearchProvider::Results* SearchProvider::GetResultsToFill(bool is_keyword) {
303 return is_keyword ? &keyword_results_ : &default_results_;
304}
305
[email protected]9487b392014-02-14 02:48:18306bool SearchProvider::ShouldAppendExtraParams(
307 const SuggestResult& result) const {
308 return !result.from_keyword_provider() ||
309 providers_.default_provider().empty();
310}
311
[email protected]ef6866f2014-02-18 08:26:34312void SearchProvider::StopSuggest() {
313 // Increment the appropriate field in the histogram by the number of
314 // pending requests that were invalidated.
315 for (int i = 0; i < suggest_results_pending_; ++i)
316 LogOmniboxSuggestRequest(REQUEST_INVALIDATED);
317 suggest_results_pending_ = 0;
318 timer_.Stop();
319 // Stop any in-progress URL fetches.
320 keyword_fetcher_.reset();
321 default_fetcher_.reset();
322}
323
324void SearchProvider::ClearAllResults() {
325 keyword_results_.Clear();
326 default_results_.Clear();
327}
328
[email protected]d4a94b92014-03-04 01:35:22329int SearchProvider::GetDefaultResultRelevance() const {
330 return -1;
331}
332
[email protected]7267ff82013-12-03 17:20:30333void SearchProvider::RecordDeletionResult(bool success) {
334 if (success) {
335 content::RecordAction(
[email protected]e6e30ac2014-01-13 21:24:39336 base::UserMetricsAction("Omnibox.ServerSuggestDelete.Success"));
[email protected]7267ff82013-12-03 17:20:30337 } else {
338 content::RecordAction(
[email protected]e6e30ac2014-01-13 21:24:39339 base::UserMetricsAction("Omnibox.ServerSuggestDelete.Failure"));
[email protected]7267ff82013-12-03 17:20:30340 }
341}
342
[email protected]cfa164bf2014-03-19 11:51:15343void SearchProvider::LogFetchComplete(bool success, bool is_keyword) {
344 LogOmniboxSuggestRequest(REPLY_RECEIVED);
345 // Record response time for suggest requests sent to Google. We care
346 // only about the common case: the Google default provider used in
347 // non-keyword mode.
348 const TemplateURL* default_url = providers_.GetDefaultProviderURL();
349 if (!is_keyword && default_url &&
[email protected]ce7ee5f2014-06-16 23:41:19350 (TemplateURLPrepopulateData::GetEngineType(
351 *default_url,
352 providers_.template_url_service()->search_terms_data()) ==
[email protected]cfa164bf2014-03-19 11:51:15353 SEARCH_ENGINE_GOOGLE)) {
354 const base::TimeDelta elapsed_time =
355 base::TimeTicks::Now() - time_suggest_request_sent_;
356 if (success) {
357 UMA_HISTOGRAM_TIMES("Omnibox.SuggestRequest.Success.GoogleResponseTime",
358 elapsed_time);
359 } else {
360 UMA_HISTOGRAM_TIMES("Omnibox.SuggestRequest.Failure.GoogleResponseTime",
361 elapsed_time);
362 }
363 }
364}
365
366bool SearchProvider::IsKeywordFetcher(const net::URLFetcher* fetcher) const {
367 return fetcher == keyword_fetcher_.get();
368}
369
370void SearchProvider::UpdateMatches() {
[email protected]cfa164bf2014-03-19 11:51:15371 ConvertResultsToAutocompleteMatches();
372
373 // Check constraints that may be violated by suggested relevances.
374 if (!matches_.empty() &&
375 (default_results_.HasServerProvidedScores() ||
376 keyword_results_.HasServerProvidedScores())) {
377 // These blocks attempt to repair undesirable behavior by suggested
378 // relevances with minimal impact, preserving other suggested relevances.
379
[email protected]cfa164bf2014-03-19 11:51:15380 if (!HasKeywordDefaultMatchInKeywordMode()) {
381 // In keyword mode, disregard the keyword verbatim suggested relevance
382 // if necessary so there at least one keyword match that's allowed to
383 // be the default match.
384 keyword_results_.verbatim_relevance = -1;
385 ConvertResultsToAutocompleteMatches();
386 }
[email protected]89bd27d12014-04-12 17:36:23387 if (IsTopMatchSearchWithURLInput()) {
[email protected]cfa164bf2014-03-19 11:51:15388 // Disregard the suggested search and verbatim relevances if the input
389 // type is URL and the top match is a highly-ranked search suggestion.
390 // For example, prevent a search for "foo.com" from outranking another
391 // provider's navigation for "foo.com" or "foo.com/url_from_history".
392 ApplyCalculatedSuggestRelevance(&keyword_results_.suggest_results);
393 ApplyCalculatedSuggestRelevance(&default_results_.suggest_results);
394 default_results_.verbatim_relevance = -1;
395 keyword_results_.verbatim_relevance = -1;
396 ConvertResultsToAutocompleteMatches();
397 }
[email protected]89bd27d12014-04-12 17:36:23398 if (FindTopMatch() == matches_.end()) {
399 // Guarantee that SearchProvider returns a legal default match. (The
400 // omnibox always needs at least one legal default match, and it relies
401 // on SearchProvider to always return one.)
[email protected]cfa164bf2014-03-19 11:51:15402 ApplyCalculatedRelevance();
403 ConvertResultsToAutocompleteMatches();
404 }
[email protected]cfa164bf2014-03-19 11:51:15405 DCHECK(HasKeywordDefaultMatchInKeywordMode());
[email protected]89bd27d12014-04-12 17:36:23406 DCHECK(!IsTopMatchSearchWithURLInput());
407 DCHECK(FindTopMatch() != matches_.end());
[email protected]cfa164bf2014-03-19 11:51:15408 }
409 UMA_HISTOGRAM_CUSTOM_COUNTS(
410 "Omnibox.SearchProviderMatches", matches_.size(), 1, 6, 7);
411
412 const TemplateURL* keyword_url = providers_.GetKeywordProviderURL();
413 if ((keyword_url != NULL) && HasKeywordDefaultMatchInKeywordMode()) {
414 // If there is a keyword match that is allowed to be the default match,
415 // then prohibit default provider matches from being the default match lest
416 // such matches cause the user to break out of keyword mode.
417 for (ACMatches::iterator it = matches_.begin(); it != matches_.end();
418 ++it) {
419 if (it->keyword != keyword_url->keyword())
420 it->allowed_to_be_default_match = false;
421 }
422 }
[email protected]cfa164bf2014-03-19 11:51:15423 UpdateDone();
[email protected]cfa164bf2014-03-19 11:51:15424}
425
[email protected]bc8bb0cd2013-06-24 21:50:23426void SearchProvider::Run() {
427 // Start a new request with the current input.
428 suggest_results_pending_ = 0;
429 time_suggest_request_sent_ = base::TimeTicks::Now();
[email protected]abe441e2013-05-06 12:35:05430
[email protected]bc8bb0cd2013-06-24 21:50:23431 default_fetcher_.reset(CreateSuggestFetcher(kDefaultProviderURLFetcherID,
432 providers_.GetDefaultProviderURL(), input_));
433 keyword_fetcher_.reset(CreateSuggestFetcher(kKeywordProviderURLFetcherID,
434 providers_.GetKeywordProviderURL(), keyword_input_));
435
436 // Both the above can fail if the providers have been modified or deleted
437 // since the query began.
438 if (suggest_results_pending_ == 0) {
439 UpdateDone();
440 // We only need to update the listener if we're actually done.
441 if (done_)
442 listener_->OnProviderUpdate(false);
443 }
[email protected]601858c02010-09-01 17:08:20444}
445
[email protected]8d457132010-11-04 18:13:40446void SearchProvider::DoHistoryQuery(bool minimal_changes) {
447 // The history query results are synchronous, so if minimal_changes is true,
448 // we still have the last results and don't need to do anything.
449 if (minimal_changes)
initial.commit09911bf2008-07-26 23:55:29450 return;
451
[email protected]8d457132010-11-04 18:13:40452 keyword_history_results_.clear();
453 default_history_results_.clear();
initial.commit09911bf2008-07-26 23:55:29454
[email protected]78e5e432013-08-03 02:10:10455 if (OmniboxFieldTrial::SearchHistoryDisable(
456 input_.current_page_classification()))
[email protected]d8cd76b2013-07-10 09:46:16457 return;
458
[email protected]8d457132010-11-04 18:13:40459 HistoryService* const history_service =
[email protected]9d2db762012-06-19 00:01:10460 HistoryServiceFactory::GetForProfile(profile_, Profile::EXPLICIT_ACCESS);
[email protected]8d457132010-11-04 18:13:40461 history::URLDatabase* url_db = history_service ?
462 history_service->InMemoryDatabase() : NULL;
[email protected]8d457132010-11-04 18:13:40463 if (!url_db)
initial.commit09911bf2008-07-26 23:55:29464 return;
465
[email protected]51124552011-07-16 01:37:10466 // Request history for both the keyword and default provider. We grab many
467 // more matches than we'll ultimately clamp to so that if there are several
468 // recent multi-word matches who scores are lowered (see
469 // AddHistoryResultsToMap()), they won't crowd out older, higher-scoring
470 // matches. Note that this doesn't fix the problem entirely, but merely
471 // limits it to cases with a very large number of such multi-word matches; for
472 // now, this seems OK compared with the complexity of a real fix, which would
473 // require multiple searches and tracking of "single- vs. multi-word" in the
474 // database.
475 int num_matches = kMaxMatches * 5;
[email protected]85b8d6f2012-05-08 20:53:47476 const TemplateURL* default_url = providers_.GetDefaultProviderURL();
477 if (default_url) {
[email protected]b4bec972014-04-05 18:07:15478 const base::TimeTicks start_time = base::TimeTicks::Now();
[email protected]85b8d6f2012-05-08 20:53:47479 url_db->GetMostRecentKeywordSearchTerms(default_url->id(), input_.text(),
480 num_matches, &default_history_results_);
[email protected]31afdf72013-09-26 04:29:36481 UMA_HISTOGRAM_TIMES(
482 "Omnibox.SearchProvider.GetMostRecentKeywordTermsDefaultProviderTime",
483 base::TimeTicks::Now() - start_time);
[email protected]257ab712009-04-14 17:16:24484 }
[email protected]85b8d6f2012-05-08 20:53:47485 const TemplateURL* keyword_url = providers_.GetKeywordProviderURL();
486 if (keyword_url) {
487 url_db->GetMostRecentKeywordSearchTerms(keyword_url->id(),
[email protected]14710852013-02-05 23:45:41488 keyword_input_.text(), num_matches, &keyword_history_results_);
[email protected]3954c3a2012-04-10 20:17:55489 }
initial.commit09911bf2008-07-26 23:55:29490}
491
[email protected]6dc950f2012-07-16 19:49:08492void SearchProvider::StartOrStopSuggestQuery(bool minimal_changes) {
[email protected]83c726482008-09-10 06:36:34493 if (!IsQuerySuitableForSuggest()) {
initial.commit09911bf2008-07-26 23:55:29494 StopSuggest();
[email protected]71b46152013-05-03 16:39:20495 ClearAllResults();
initial.commit09911bf2008-07-26 23:55:29496 return;
497 }
498
499 // For the minimal_changes case, if we finished the previous query and still
500 // have its results, or are allowed to keep running it, just do that, rather
501 // than starting a new query.
502 if (minimal_changes &&
[email protected]cc1526e2013-05-17 04:04:24503 (!default_results_.suggest_results.empty() ||
504 !default_results_.navigation_results.empty() ||
505 !keyword_results_.suggest_results.empty() ||
506 !keyword_results_.navigation_results.empty() ||
[email protected]a2770a7d2014-04-22 19:33:35507 (!done_ && input_.want_asynchronous_matches())))
initial.commit09911bf2008-07-26 23:55:29508 return;
509
510 // We can't keep running any previous query, so halt it.
511 StopSuggest();
[email protected]d1f0a7f2012-06-05 10:26:42512
513 // Remove existing results that cannot inline autocomplete the new input.
[email protected]71b46152013-05-03 16:39:20514 RemoveAllStaleResults();
initial.commit09911bf2008-07-26 23:55:29515
[email protected]ee6110b2014-01-09 22:26:31516 // Update the content classifications of remaining results so they look good
517 // against the current input.
[email protected]23db6492014-01-16 02:35:30518 UpdateMatchContentsClass(input_.text(), &default_results_);
519 if (!keyword_input_.text().empty())
520 UpdateMatchContentsClass(keyword_input_.text(), &keyword_results_);
[email protected]ee6110b2014-01-09 22:26:31521
initial.commit09911bf2008-07-26 23:55:29522 // We can't start a new query if we're only allowed synchronous results.
[email protected]a2770a7d2014-04-22 19:33:35523 if (!input_.want_asynchronous_matches())
initial.commit09911bf2008-07-26 23:55:29524 return;
525
[email protected]24dbf2302013-04-05 16:59:25526 // To avoid flooding the suggest server, don't send a query until at
527 // least 100 ms since the last query.
[email protected]515ffa942012-11-27 20:18:24528 base::TimeTicks next_suggest_time(time_suggest_request_sent_ +
[email protected]bc8bb0cd2013-06-24 21:50:23529 base::TimeDelta::FromMilliseconds(kMinimumTimeBetweenSuggestQueriesMs));
[email protected]515ffa942012-11-27 20:18:24530 base::TimeTicks now(base::TimeTicks::Now());
531 if (now >= next_suggest_time) {
532 Run();
533 return;
534 }
535 timer_.Start(FROM_HERE, next_suggest_time - now, this, &SearchProvider::Run);
initial.commit09911bf2008-07-26 23:55:29536}
537
[email protected]83c726482008-09-10 06:36:34538bool SearchProvider::IsQuerySuitableForSuggest() const {
[email protected]3954c3a2012-04-10 20:17:55539 // Don't run Suggest in incognito mode, if the engine doesn't support it, or
540 // if the user has disabled it.
[email protected]85b8d6f2012-05-08 20:53:47541 const TemplateURL* default_url = providers_.GetDefaultProviderURL();
542 const TemplateURL* keyword_url = providers_.GetKeywordProviderURL();
[email protected]83c726482008-09-10 06:36:34543 if (profile_->IsOffTheRecord() ||
[email protected]85b8d6f2012-05-08 20:53:47544 ((!default_url || default_url->suggestions_url().empty()) &&
545 (!keyword_url || keyword_url->suggestions_url().empty())) ||
[email protected]83c726482008-09-10 06:36:34546 !profile_->GetPrefs()->GetBoolean(prefs::kSearchSuggestEnabled))
547 return false;
548
[email protected]cac59d32010-08-09 23:23:14549 // If the input type might be a URL, we take extra care so that private data
[email protected]83c726482008-09-10 06:36:34550 // isn't sent to the server.
[email protected]83c726482008-09-10 06:36:34551
[email protected]cac59d32010-08-09 23:23:14552 // FORCED_QUERY means the user is explicitly asking us to search for this, so
553 // we assume it isn't a URL and/or there isn't private data.
[email protected]3dc75b12014-06-08 00:02:22554 if (input_.type() == metrics::OmniboxInputType::FORCED_QUERY)
[email protected]cac59d32010-08-09 23:23:14555 return true;
[email protected]83c726482008-09-10 06:36:34556
[email protected]f608ea102013-03-18 15:08:09557 // Next we check the scheme. If this is UNKNOWN/URL with a scheme that isn't
558 // http/https/ftp, we shouldn't send it. Sending things like file: and data:
559 // is both a waste of time and a disclosure of potentially private, local
560 // data. Other "schemes" may actually be usernames, and we don't want to send
561 // passwords. If the scheme is OK, we still need to check other cases below.
562 // If this is QUERY, then the presence of these schemes means the user
563 // explicitly typed one, and thus this is probably a URL that's being entered
564 // and happens to currently be invalid -- in which case we again want to run
565 // our checks below. Other QUERY cases are less likely to be URLs and thus we
566 // assume we're OK.
[email protected]e8ca69c2014-05-07 15:31:19567 if (!LowerCaseEqualsASCII(input_.scheme(), url::kHttpScheme) &&
568 !LowerCaseEqualsASCII(input_.scheme(), url::kHttpsScheme) &&
[email protected]cca6f392014-05-28 21:32:26569 !LowerCaseEqualsASCII(input_.scheme(), url::kFtpScheme))
[email protected]3dc75b12014-06-08 00:02:22570 return (input_.type() == metrics::OmniboxInputType::QUERY);
[email protected]cac59d32010-08-09 23:23:14571
572 // Don't send URLs with usernames, queries or refs. Some of these are
573 // private, and the Suggest server is unlikely to have any useful results
574 // for any of them. Also don't send URLs with ports, as we may initially
575 // think that a username + password is a host + port (and we don't want to
576 // send usernames/passwords), and even if the port really is a port, the
577 // server is once again unlikely to have and useful results.
[email protected]825e16f2013-09-30 23:52:58578 // Note that we only block based on refs if the input is URL-typed, as search
579 // queries can legitimately have #s in them which the URL parser
580 // overaggressively categorizes as a url with a ref.
[email protected]b45334502014-04-30 19:44:05581 const url::Parsed& parts = input_.parts();
[email protected]cac59d32010-08-09 23:23:14582 if (parts.username.is_nonempty() || parts.port.is_nonempty() ||
[email protected]825e16f2013-09-30 23:52:58583 parts.query.is_nonempty() ||
[email protected]3dc75b12014-06-08 00:02:22584 (parts.ref.is_nonempty() &&
585 (input_.type() == metrics::OmniboxInputType::URL)))
[email protected]cac59d32010-08-09 23:23:14586 return false;
587
588 // Don't send anything for https except the hostname. Hostnames are OK
589 // because they are visible when the TCP connection is established, but the
590 // specific path may reveal private information.
[email protected]e8ca69c2014-05-07 15:31:19591 if (LowerCaseEqualsASCII(input_.scheme(), url::kHttpsScheme) &&
[email protected]a2fedb1e2011-01-25 15:23:36592 parts.path.is_nonempty())
[email protected]cac59d32010-08-09 23:23:14593 return false;
[email protected]83c726482008-09-10 06:36:34594
595 return true;
596}
597
[email protected]71b46152013-05-03 16:39:20598void SearchProvider::RemoveAllStaleResults() {
[email protected]dc735c02013-11-12 23:23:41599 if (keyword_input_.text().empty()) {
[email protected]1e1550e2013-05-02 17:37:51600 // User is either in keyword mode with a blank input or out of
601 // keyword mode entirely.
[email protected]cc1526e2013-05-17 04:04:24602 keyword_results_.Clear();
[email protected]1e1550e2013-05-02 17:37:51603 }
[email protected]d1f0a7f2012-06-05 10:26:42604}
605
[email protected]d1f0a7f2012-06-05 10:26:42606void SearchProvider::ApplyCalculatedRelevance() {
[email protected]cc1526e2013-05-17 04:04:24607 ApplyCalculatedSuggestRelevance(&keyword_results_.suggest_results);
608 ApplyCalculatedSuggestRelevance(&default_results_.suggest_results);
609 ApplyCalculatedNavigationRelevance(&keyword_results_.navigation_results);
610 ApplyCalculatedNavigationRelevance(&default_results_.navigation_results);
[email protected]cc1526e2013-05-17 04:04:24611 default_results_.verbatim_relevance = -1;
612 keyword_results_.verbatim_relevance = -1;
[email protected]d1f0a7f2012-06-05 10:26:42613}
614
[email protected]188b50c2013-03-28 07:19:42615void SearchProvider::ApplyCalculatedSuggestRelevance(SuggestResults* list) {
[email protected]d1f0a7f2012-06-05 10:26:42616 for (size_t i = 0; i < list->size(); ++i) {
[email protected]188b50c2013-03-28 07:19:42617 SuggestResult& result = (*list)[i];
618 result.set_relevance(
619 result.CalculateRelevance(input_, providers_.has_keyword_provider()) +
620 (list->size() - i - 1));
[email protected]d30268a2013-06-25 22:31:07621 result.set_relevance_from_server(false);
[email protected]d1f0a7f2012-06-05 10:26:42622 }
623}
624
[email protected]188b50c2013-03-28 07:19:42625void SearchProvider::ApplyCalculatedNavigationRelevance(
626 NavigationResults* list) {
[email protected]d1f0a7f2012-06-05 10:26:42627 for (size_t i = 0; i < list->size(); ++i) {
[email protected]188b50c2013-03-28 07:19:42628 NavigationResult& result = (*list)[i];
629 result.set_relevance(
630 result.CalculateRelevance(input_, providers_.has_keyword_provider()) +
631 (list->size() - i - 1));
[email protected]d30268a2013-06-25 22:31:07632 result.set_relevance_from_server(false);
[email protected]d1f0a7f2012-06-05 10:26:42633 }
634}
635
[email protected]15fb2aa2012-05-22 22:52:59636net::URLFetcher* SearchProvider::CreateSuggestFetcher(
[email protected]7cc6e5632011-10-25 17:56:12637 int id,
[email protected]9ff91722012-09-07 05:29:12638 const TemplateURL* template_url,
[email protected]14710852013-02-05 23:45:41639 const AutocompleteInput& input) {
[email protected]9ff91722012-09-07 05:29:12640 if (!template_url || template_url->suggestions_url().empty())
641 return NULL;
642
643 // Bail if the suggestion URL is invalid with the given replacements.
[email protected]14710852013-02-05 23:45:41644 TemplateURLRef::SearchTermsArgs search_term_args(input.text());
[email protected]420472b22014-06-10 13:34:43645 search_term_args.input_type = input.type();
[email protected]14710852013-02-05 23:45:41646 search_term_args.cursor_position = input.cursor_position();
[email protected]d5015ca2013-08-08 22:04:18647 search_term_args.page_classification = input.current_page_classification();
[email protected]2ef2a6642014-07-30 05:50:29648 if (OmniboxFieldTrial::EnableAnswersInSuggest()) {
[email protected]20184242014-05-14 02:57:42649 search_term_args.session_token = GetSessionToken();
[email protected]2ef2a6642014-07-30 05:50:29650 if (!prefetch_data_.full_query_text.empty()) {
651 search_term_args.prefetch_query =
652 base::UTF16ToUTF8(last_answer_seen_.full_query_text);
653 search_term_args.prefetch_query_type =
654 base::UTF16ToUTF8(last_answer_seen_.query_type);
655 }
656 }
[email protected]9ff91722012-09-07 05:29:12657 GURL suggest_url(template_url->suggestions_url_ref().ReplaceSearchTerms(
[email protected]ce7ee5f2014-06-16 23:41:19658 search_term_args,
659 providers_.template_url_service()->search_terms_data()));
[email protected]9ff91722012-09-07 05:29:12660 if (!suggest_url.is_valid())
661 return NULL;
[email protected]9b9fa672013-11-07 06:04:52662 // Send the current page URL if user setting and URL requirements are met and
663 // the user is in the field trial.
664 if (CanSendURL(current_page_url_, suggest_url, template_url,
665 input.current_page_classification(), profile_) &&
666 OmniboxFieldTrial::InZeroSuggestAfterTypingFieldTrial()) {
667 search_term_args.current_page_url = current_page_url_.spec();
668 // Create the suggest URL again with the current page URL.
669 suggest_url = GURL(template_url->suggestions_url_ref().ReplaceSearchTerms(
[email protected]ce7ee5f2014-06-16 23:41:19670 search_term_args,
671 providers_.template_url_service()->search_terms_data()));
[email protected]9b9fa672013-11-07 06:04:52672 }
[email protected]9ff91722012-09-07 05:29:12673
674 suggest_results_pending_++;
675 LogOmniboxSuggestRequest(REQUEST_SENT);
676
677 net::URLFetcher* fetcher =
678 net::URLFetcher::Create(id, suggest_url, net::URLFetcher::GET, this);
[email protected]7cc6e5632011-10-25 17:56:12679 fetcher->SetRequestContext(profile_->GetRequestContext());
[email protected]d3cf8682f02012-02-29 23:29:34680 fetcher->SetLoadFlags(net::LOAD_DO_NOT_SAVE_COOKIES);
[email protected]bd3b4712012-12-18 17:01:30681 // Add Chrome experiment state to the request headers.
682 net::HttpRequestHeaders headers;
[email protected]71011c1682014-07-09 17:19:16683 variations::VariationsHttpHeaderProvider::GetInstance()->AppendHeaders(
[email protected]bd3b4712012-12-18 17:01:30684 fetcher->GetOriginalURL(), profile_->IsOffTheRecord(), false, &headers);
685 fetcher->SetExtraRequestHeaders(headers.ToString());
[email protected]257ab712009-04-14 17:16:24686 fetcher->Start();
687 return fetcher;
688}
689
[email protected]344946a12012-12-20 12:03:42690void SearchProvider::ConvertResultsToAutocompleteMatches() {
initial.commit09911bf2008-07-26 23:55:29691 // Convert all the results to matches and add them to a map, so we can keep
692 // the most relevant match for each result.
[email protected]31afdf72013-09-26 04:29:36693 base::TimeTicks start_time(base::TimeTicks::Now());
initial.commit09911bf2008-07-26 23:55:29694 MatchMap map;
[email protected]bc8bb0cd2013-06-24 21:50:23695 const base::Time no_time;
[email protected]cc1526e2013-05-17 04:04:24696 int did_not_accept_keyword_suggestion =
697 keyword_results_.suggest_results.empty() ?
initial.commit09911bf2008-07-26 23:55:29698 TemplateURLRef::NO_SUGGESTIONS_AVAILABLE :
699 TemplateURLRef::NO_SUGGESTION_CHOSEN;
initial.commit09911bf2008-07-26 23:55:29700
[email protected]d30268a2013-06-25 22:31:07701 bool relevance_from_server;
702 int verbatim_relevance = GetVerbatimRelevance(&relevance_from_server);
[email protected]cc1526e2013-05-17 04:04:24703 int did_not_accept_default_suggestion =
704 default_results_.suggest_results.empty() ?
[email protected]55ce8f12012-05-09 04:44:08705 TemplateURLRef::NO_SUGGESTIONS_AVAILABLE :
706 TemplateURLRef::NO_SUGGESTION_CHOSEN;
[email protected]d1f0a7f2012-06-05 10:26:42707 if (verbatim_relevance > 0) {
[email protected]c2ca3fd2014-03-22 03:07:44708 const base::string16& trimmed_verbatim =
709 base::CollapseWhitespace(input_.text(), false);
[email protected]2c03c06b2013-12-11 20:45:02710 SuggestResult verbatim(
[email protected]c2ca3fd2014-03-22 03:07:44711 trimmed_verbatim, AutocompleteMatchType::SEARCH_WHAT_YOU_TYPED,
[email protected]7ec287e2014-05-16 02:50:08712 trimmed_verbatim, base::string16(), base::string16(), base::string16(),
713 base::string16(), std::string(), std::string(), false,
714 verbatim_relevance, relevance_from_server, false,
[email protected]c2ca3fd2014-03-22 03:07:44715 trimmed_verbatim);
[email protected]57482a72014-03-14 22:27:37716 AddMatchToMap(verbatim, std::string(), did_not_accept_default_suggestion,
717 false, &map);
[email protected]d1f0a7f2012-06-05 10:26:42718 }
[email protected]5423e562013-02-07 03:58:45719 if (!keyword_input_.text().empty()) {
720 const TemplateURL* keyword_url = providers_.GetKeywordProviderURL();
721 // We only create the verbatim search query match for a keyword
722 // if it's not an extension keyword. Extension keywords are handled
723 // in KeywordProvider::Start(). (Extensions are complicated...)
724 // Note: in this provider, SEARCH_OTHER_ENGINE must correspond
725 // to the keyword verbatim search query. Do not create other matches
726 // of type SEARCH_OTHER_ENGINE.
[email protected]bdcbcd82013-10-28 13:40:25727 if (keyword_url &&
728 (keyword_url->GetType() != TemplateURL::OMNIBOX_API_EXTENSION)) {
[email protected]d30268a2013-06-25 22:31:07729 bool keyword_relevance_from_server;
730 const int keyword_verbatim_relevance =
731 GetKeywordVerbatimRelevance(&keyword_relevance_from_server);
[email protected]dab8d52d2013-03-05 07:35:28732 if (keyword_verbatim_relevance > 0) {
[email protected]c2ca3fd2014-03-22 03:07:44733 const base::string16& trimmed_verbatim =
734 base::CollapseWhitespace(keyword_input_.text(), false);
[email protected]2c03c06b2013-12-11 20:45:02735 SuggestResult verbatim(
[email protected]c2ca3fd2014-03-22 03:07:44736 trimmed_verbatim, AutocompleteMatchType::SEARCH_OTHER_ENGINE,
737 trimmed_verbatim, base::string16(), base::string16(),
[email protected]7ec287e2014-05-16 02:50:08738 base::string16(), base::string16(), std::string(), std::string(),
739 true, keyword_verbatim_relevance, keyword_relevance_from_server,
740 false, trimmed_verbatim);
[email protected]57482a72014-03-14 22:27:37741 AddMatchToMap(verbatim, std::string(),
742 did_not_accept_keyword_suggestion, false, &map);
[email protected]dab8d52d2013-03-05 07:35:28743 }
[email protected]5423e562013-02-07 03:58:45744 }
745 }
[email protected]257ab712009-04-14 17:16:24746 AddHistoryResultsToMap(keyword_history_results_, true,
747 did_not_accept_keyword_suggestion, &map);
748 AddHistoryResultsToMap(default_history_results_, false,
749 did_not_accept_default_suggestion, &map);
750
[email protected]d1cb6a822013-09-18 19:43:00751 AddSuggestResultsToMap(keyword_results_.suggest_results,
752 keyword_results_.metadata, &map);
[email protected]987fad782013-08-28 06:23:18753 AddSuggestResultsToMap(default_results_.suggest_results,
754 default_results_.metadata, &map);
initial.commit09911bf2008-07-26 23:55:29755
[email protected]d30268a2013-06-25 22:31:07756 ACMatches matches;
initial.commit09911bf2008-07-26 23:55:29757 for (MatchMap::const_iterator i(map.begin()); i != map.end(); ++i)
[email protected]d30268a2013-06-25 22:31:07758 matches.push_back(i->second);
initial.commit09911bf2008-07-26 23:55:29759
[email protected]d30268a2013-06-25 22:31:07760 AddNavigationResultsToMatches(keyword_results_.navigation_results, &matches);
761 AddNavigationResultsToMatches(default_results_.navigation_results, &matches);
initial.commit09911bf2008-07-26 23:55:29762
[email protected]d30268a2013-06-25 22:31:07763 // Now add the most relevant matches to |matches_|. We take up to kMaxMatches
764 // suggest/navsuggest matches, regardless of origin. If Instant Extended is
765 // enabled and we have server-provided (and thus hopefully more accurate)
766 // scores for some suggestions, we allow more of those, until we reach
767 // AutocompleteResult::kMaxMatches total matches (that is, enough to fill the
768 // whole popup).
769 //
770 // We will always return any verbatim matches, no matter how we obtained their
771 // scores, unless we have already accepted AutocompleteResult::kMaxMatches
772 // higher-scoring matches under the conditions above.
[email protected]d30268a2013-06-25 22:31:07773 std::sort(matches.begin(), matches.end(), &AutocompleteMatch::MoreRelevant);
774 matches_.clear();
[email protected]3723e6e2012-06-11 21:06:56775
[email protected]d30268a2013-06-25 22:31:07776 size_t num_suggestions = 0;
777 for (ACMatches::const_iterator i(matches.begin());
778 (i != matches.end()) &&
779 (matches_.size() < AutocompleteResult::kMaxMatches);
780 ++i) {
781 // SEARCH_OTHER_ENGINE is only used in the SearchProvider for the keyword
782 // verbatim result, so this condition basically means "if this match is a
783 // suggestion of some sort".
784 if ((i->type != AutocompleteMatchType::SEARCH_WHAT_YOU_TYPED) &&
785 (i->type != AutocompleteMatchType::SEARCH_OTHER_ENGINE)) {
786 // If we've already hit the limit on non-server-scored suggestions, and
787 // this isn't a server-scored suggestion we can add, skip it.
788 if ((num_suggestions >= kMaxMatches) &&
789 (!chrome::IsInstantExtendedAPIEnabled() ||
790 (i->GetAdditionalInfo(kRelevanceFromServerKey) != kTrue))) {
791 continue;
792 }
793
794 ++num_suggestions;
795 }
796
797 matches_.push_back(*i);
798 }
[email protected]31afdf72013-09-26 04:29:36799 UMA_HISTOGRAM_TIMES("Omnibox.SearchProvider.ConvertResultsTime",
800 base::TimeTicks::Now() - start_time);
[email protected]344946a12012-12-20 12:03:42801}
802
[email protected]89bd27d12014-04-12 17:36:23803ACMatches::const_iterator SearchProvider::FindTopMatch() const {
[email protected]0a8718b12013-11-13 18:41:31804 ACMatches::const_iterator it = matches_.begin();
805 while ((it != matches_.end()) && !it->allowed_to_be_default_match)
806 ++it;
807 return it;
[email protected]9dfb4d362013-04-05 02:15:12808}
809
[email protected]1c1e7842013-11-22 16:28:16810bool SearchProvider::HasKeywordDefaultMatchInKeywordMode() const {
811 const TemplateURL* keyword_url = providers_.GetKeywordProviderURL();
812 // If the user is not in keyword mode, return true to say that this
813 // constraint is not violated.
814 if (keyword_url == NULL)
815 return true;
816 for (ACMatches::const_iterator it = matches_.begin(); it != matches_.end();
817 ++it) {
818 if ((it->keyword == keyword_url->keyword()) &&
819 it->allowed_to_be_default_match)
820 return true;
821 }
822 return false;
823}
824
[email protected]89bd27d12014-04-12 17:36:23825bool SearchProvider::IsTopMatchSearchWithURLInput() const {
826 ACMatches::const_iterator first_match = FindTopMatch();
[email protected]3dc75b12014-06-08 00:02:22827 return (input_.type() == metrics::OmniboxInputType::URL) &&
[email protected]0a8718b12013-11-13 18:41:31828 (first_match != matches_.end()) &&
829 (first_match->relevance > CalculateRelevanceForVerbatim()) &&
[email protected]78981d8c2014-05-09 15:05:47830 (first_match->type != AutocompleteMatchType::NAVSUGGEST) &&
831 (first_match->type != AutocompleteMatchType::NAVSUGGEST_PERSONALIZED);
[email protected]344946a12012-12-20 12:03:42832}
833
[email protected]257ab712009-04-14 17:16:24834void SearchProvider::AddNavigationResultsToMatches(
[email protected]d30268a2013-06-25 22:31:07835 const NavigationResults& navigation_results,
836 ACMatches* matches) {
[email protected]bc8bb0cd2013-06-24 21:50:23837 for (NavigationResults::const_iterator it = navigation_results.begin();
838 it != navigation_results.end(); ++it) {
[email protected]d30268a2013-06-25 22:31:07839 matches->push_back(NavigationToMatch(*it));
[email protected]bc8bb0cd2013-06-24 21:50:23840 // In the absence of suggested relevance scores, use only the single
841 // highest-scoring result. (The results are already sorted by relevance.)
[email protected]d30268a2013-06-25 22:31:07842 if (!it->relevance_from_server())
[email protected]bc8bb0cd2013-06-24 21:50:23843 return;
[email protected]257ab712009-04-14 17:16:24844 }
845}
846
847void SearchProvider::AddHistoryResultsToMap(const HistoryResults& results,
848 bool is_keyword,
849 int did_not_accept_suggestion,
850 MatchMap* map) {
[email protected]51124552011-07-16 01:37:10851 if (results.empty())
852 return;
853
[email protected]31afdf72013-09-26 04:29:36854 base::TimeTicks start_time(base::TimeTicks::Now());
[email protected]d7ad4772012-06-01 03:12:54855 bool prevent_inline_autocomplete = input_.prevent_inline_autocomplete() ||
[email protected]3dc75b12014-06-08 00:02:22856 (input_.type() == metrics::OmniboxInputType::URL);
[email protected]0085863a2013-12-06 21:19:03857 const base::string16& input_text =
[email protected]14710852013-02-05 23:45:41858 is_keyword ? keyword_input_.text() : input_.text();
[email protected]51124552011-07-16 01:37:10859 bool input_multiple_words = HasMultipleWords(input_text);
860
[email protected]55ce8f12012-05-09 04:44:08861 SuggestResults scored_results;
862 if (!prevent_inline_autocomplete && input_multiple_words) {
863 // ScoreHistoryResults() allows autocompletion of multi-word, 1-visit
864 // queries if the input also has multiple words. But if we were already
[email protected]f13a2132014-04-22 08:13:52865 // scoring a multi-word, multi-visit query aggressively, and the current
866 // input is still a prefix of it, then changing the suggestion suddenly
867 // feels wrong. To detect this case, first score as if only one word has
868 // been typed, then check if the best result came from aggressive search
869 // history scoring. If it did, then just keep that score set. This
870 // 1200 the lowest possible score in CalculateRelevanceForHistory()'s
871 // aggressive-scoring curve.
[email protected]55ce8f12012-05-09 04:44:08872 scored_results = ScoreHistoryResults(results, prevent_inline_autocomplete,
873 false, input_text, is_keyword);
[email protected]f13a2132014-04-22 08:13:52874 if ((scored_results.front().relevance() < 1200) ||
[email protected]9dfb4d362013-04-05 02:15:12875 !HasMultipleWords(scored_results.front().suggestion()))
[email protected]55ce8f12012-05-09 04:44:08876 scored_results.clear(); // Didn't detect the case above, score normally.
[email protected]51124552011-07-16 01:37:10877 }
[email protected]55ce8f12012-05-09 04:44:08878 if (scored_results.empty())
879 scored_results = ScoreHistoryResults(results, prevent_inline_autocomplete,
880 input_multiple_words, input_text,
881 is_keyword);
882 for (SuggestResults::const_iterator i(scored_results.begin());
883 i != scored_results.end(); ++i) {
[email protected]57482a72014-03-14 22:27:37884 AddMatchToMap(*i, std::string(), did_not_accept_suggestion, true, map);
[email protected]51124552011-07-16 01:37:10885 }
[email protected]31afdf72013-09-26 04:29:36886 UMA_HISTOGRAM_TIMES("Omnibox.SearchProvider.AddHistoryResultsTime",
887 base::TimeTicks::Now() - start_time);
[email protected]51124552011-07-16 01:37:10888}
889
[email protected]55ce8f12012-05-09 04:44:08890SearchProvider::SuggestResults SearchProvider::ScoreHistoryResults(
[email protected]51124552011-07-16 01:37:10891 const HistoryResults& results,
892 bool base_prevent_inline_autocomplete,
893 bool input_multiple_words,
[email protected]0085863a2013-12-06 21:19:03894 const base::string16& input_text,
[email protected]51124552011-07-16 01:37:10895 bool is_keyword) {
[email protected]55ce8f12012-05-09 04:44:08896 SuggestResults scored_results;
[email protected]ab5fd2f2014-07-17 19:18:52897 // True if the user has asked this exact query previously.
898 bool found_what_you_typed_match = false;
[email protected]78e5e432013-08-03 02:10:10899 const bool prevent_search_history_inlining =
900 OmniboxFieldTrial::SearchHistoryPreventInlining(
901 input_.current_page_classification());
[email protected]c2ca3fd2014-03-22 03:07:44902 const base::string16& trimmed_input =
903 base::CollapseWhitespace(input_text, false);
[email protected]257ab712009-04-14 17:16:24904 for (HistoryResults::const_iterator i(results.begin()); i != results.end();
905 ++i) {
[email protected]c2ca3fd2014-03-22 03:07:44906 const base::string16& trimmed_suggestion =
907 base::CollapseWhitespace(i->term, false);
908
[email protected]51124552011-07-16 01:37:10909 // Don't autocomplete multi-word queries that have only been seen once
910 // unless the user has typed more than one word.
911 bool prevent_inline_autocomplete = base_prevent_inline_autocomplete ||
[email protected]c2ca3fd2014-03-22 03:07:44912 (!input_multiple_words && (i->visits < 2) &&
913 HasMultipleWords(trimmed_suggestion));
[email protected]51124552011-07-16 01:37:10914
[email protected]78e5e432013-08-03 02:10:10915 int relevance = CalculateRelevanceForHistory(
916 i->time, is_keyword, !prevent_inline_autocomplete,
917 prevent_search_history_inlining);
[email protected]ab5fd2f2014-07-17 19:18:52918 // Add the match to |scored_results| by putting the what-you-typed match
919 // on the front and appending all other matches. We want the what-you-
920 // typed match to always be first.
921 SuggestResults::iterator insertion_position = scored_results.end();
922 if (trimmed_suggestion == trimmed_input) {
923 found_what_you_typed_match = true;
924 insertion_position = scored_results.begin();
925 }
926 scored_results.insert(insertion_position, SuggestResult(
[email protected]c2ca3fd2014-03-22 03:07:44927 trimmed_suggestion, AutocompleteMatchType::SEARCH_HISTORY,
[email protected]7ec287e2014-05-16 02:50:08928 trimmed_suggestion, base::string16(), base::string16(),
929 base::string16(), base::string16(), std::string(), std::string(),
930 is_keyword, relevance, false, false, trimmed_input));
[email protected]257ab712009-04-14 17:16:24931 }
[email protected]51124552011-07-16 01:37:10932
933 // History returns results sorted for us. However, we may have docked some
[email protected]ab5fd2f2014-07-17 19:18:52934 // results' scores, so things are no longer in order. While keeping the
935 // what-you-typed match at the front (if it exists), do a stable sort to get
[email protected]51124552011-07-16 01:37:10936 // things back in order without otherwise disturbing results with equal
937 // scores, then force the scores to be unique, so that the order in which
938 // they're shown is deterministic.
[email protected]ab5fd2f2014-07-17 19:18:52939 std::stable_sort(scored_results.begin() +
940 (found_what_you_typed_match ? 1 : 0),
941 scored_results.end(),
[email protected]55ce8f12012-05-09 04:44:08942 CompareScoredResults());
[email protected]7e3b77f2014-07-25 02:29:44943
944 // Don't autocomplete to search terms that would normally be treated as URLs
945 // when typed. For example, if the user searched for "google.com" and types
946 // "goog", don't autocomplete to the search term "google.com". Otherwise,
947 // the input will look like a URL but act like a search, which is confusing.
948 // The 1200 relevance score threshold in the test below is the lowest
949 // possible score in CalculateRelevanceForHistory()'s aggressive-scoring
950 // curve. This is an appropriate threshold to use to decide if we're overly
951 // aggressively inlining because, if we decide the answer is yes, the
952 // way we resolve it it to not use the aggressive-scoring curve.
953 // NOTE: We don't check for autocompleting to URLs in the following cases:
954 // * When inline autocomplete is disabled, we won't be inline autocompleting
955 // this term, so we don't need to worry about confusion as much. This
956 // also prevents calling Classify() again from inside the classifier
957 // (which will corrupt state and likely crash), since the classifier
958 // always disables inline autocomplete.
959 // * When the user has typed the whole string before as a query, then it's
960 // likely the user has no expectation that term should be interpreted as
961 // as a URL, so we need not do anything special to preserve user
962 // expectation.
963 AutocompleteClassifier* classifier =
964 AutocompleteClassifierFactory::GetForProfile(profile_);
[email protected]51124552011-07-16 01:37:10965 int last_relevance = 0;
[email protected]7e3b77f2014-07-25 02:29:44966 if (!base_prevent_inline_autocomplete && !found_what_you_typed_match &&
967 classifier && (scored_results.front().relevance() >= 1200)) {
968 AutocompleteMatch match;
969 classifier->Classify(scored_results.front().suggestion(), false, false,
970 input_.current_page_classification(), &match, NULL);
971 // Demote this match that would normally be interpreted as a URL to have
972 // the highest score a previously-issued search query could have when
973 // scoring with the non-aggressive method. A consequence of demoting
974 // by revising |last_relevance| is that this match and all following
975 // matches get demoted; the relative order of matches is preserved.
976 // One could imagine demoting only those matches that might cause
977 // confusion (which, by the way, might change the relative order of
978 // matches. We have decided to go with the simple demote-all approach
979 // because selective demotion requires multiple Classify() calls and
980 // such calls can be expensive (as expensive as running the whole
981 // autocomplete system).
982 if (!AutocompleteMatch::IsSearchType(match.type)) {
983 last_relevance = CalculateRelevanceForHistory(
984 base::Time::Now(), is_keyword, false,
985 prevent_search_history_inlining);
986 }
987 }
988
[email protected]55ce8f12012-05-09 04:44:08989 for (SuggestResults::iterator i(scored_results.begin());
990 i != scored_results.end(); ++i) {
[email protected]7e3b77f2014-07-25 02:29:44991 if ((last_relevance != 0) && (i->relevance() >= last_relevance))
[email protected]55ce8f12012-05-09 04:44:08992 i->set_relevance(last_relevance - 1);
993 last_relevance = i->relevance();
[email protected]51124552011-07-16 01:37:10994 }
995
[email protected]55ce8f12012-05-09 04:44:08996 return scored_results;
[email protected]257ab712009-04-14 17:16:24997}
998
[email protected]55ce8f12012-05-09 04:44:08999void SearchProvider::AddSuggestResultsToMap(const SuggestResults& results,
[email protected]987fad782013-08-28 06:23:181000 const std::string& metadata,
[email protected]55ce8f12012-05-09 04:44:081001 MatchMap* map) {
[email protected]9487b392014-02-14 02:48:181002 for (size_t i = 0; i < results.size(); ++i)
[email protected]57482a72014-03-14 22:27:371003 AddMatchToMap(results[i], metadata, i, false, map);
initial.commit09911bf2008-07-26 23:55:291004}
1005
[email protected]d30268a2013-06-25 22:31:071006int SearchProvider::GetVerbatimRelevance(bool* relevance_from_server) const {
[email protected]dc6943b2012-06-19 06:39:561007 // Use the suggested verbatim relevance score if it is non-negative (valid),
1008 // if inline autocomplete isn't prevented (always show verbatim on backspace),
[email protected]1beee342012-06-19 22:22:281009 // and if it won't suppress verbatim, leaving no default provider matches.
1010 // Otherwise, if the default provider returned no matches and was still able
[email protected]dc6943b2012-06-19 06:39:561011 // to suppress verbatim, the user would have no search/nav matches and may be
[email protected]1beee342012-06-19 22:22:281012 // left unable to search using their default provider from the omnibox.
[email protected]dc6943b2012-06-19 06:39:561013 // Check for results on each verbatim calculation, as results from older
1014 // queries (on previous input) may be trimmed for failing to inline new input.
[email protected]bc8bb0cd2013-06-24 21:50:231015 bool use_server_relevance =
1016 (default_results_.verbatim_relevance >= 0) &&
[email protected]dab8d52d2013-03-05 07:35:281017 !input_.prevent_inline_autocomplete() &&
[email protected]bc8bb0cd2013-06-24 21:50:231018 ((default_results_.verbatim_relevance > 0) ||
[email protected]cc1526e2013-05-17 04:04:241019 !default_results_.suggest_results.empty() ||
[email protected]bc8bb0cd2013-06-24 21:50:231020 !default_results_.navigation_results.empty());
[email protected]d30268a2013-06-25 22:31:071021 if (relevance_from_server)
1022 *relevance_from_server = use_server_relevance;
[email protected]bc8bb0cd2013-06-24 21:50:231023 return use_server_relevance ?
1024 default_results_.verbatim_relevance : CalculateRelevanceForVerbatim();
[email protected]382a0642012-06-06 06:13:521025}
[email protected]d1f0a7f2012-06-05 10:26:421026
[email protected]382a0642012-06-06 06:13:521027int SearchProvider::CalculateRelevanceForVerbatim() const {
[email protected]85b8d6f2012-05-08 20:53:471028 if (!providers_.keyword_provider().empty())
[email protected]52d08b12009-10-19 18:42:361029 return 250;
[email protected]dab8d52d2013-03-05 07:35:281030 return CalculateRelevanceForVerbatimIgnoringKeywordModeState();
1031}
[email protected]52d08b12009-10-19 18:42:361032
[email protected]dab8d52d2013-03-05 07:35:281033int SearchProvider::
1034 CalculateRelevanceForVerbatimIgnoringKeywordModeState() const {
initial.commit09911bf2008-07-26 23:55:291035 switch (input_.type()) {
[email protected]3dc75b12014-06-08 00:02:221036 case metrics::OmniboxInputType::UNKNOWN:
1037 case metrics::OmniboxInputType::QUERY:
1038 case metrics::OmniboxInputType::FORCED_QUERY:
[email protected]90fe2bb2013-01-15 03:42:131039 return kNonURLVerbatimRelevance;
initial.commit09911bf2008-07-26 23:55:291040
[email protected]3dc75b12014-06-08 00:02:221041 case metrics::OmniboxInputType::URL:
[email protected]52d08b12009-10-19 18:42:361042 return 850;
initial.commit09911bf2008-07-26 23:55:291043
1044 default:
1045 NOTREACHED();
1046 return 0;
1047 }
1048}
1049
[email protected]d30268a2013-06-25 22:31:071050int SearchProvider::GetKeywordVerbatimRelevance(
1051 bool* relevance_from_server) const {
[email protected]dab8d52d2013-03-05 07:35:281052 // Use the suggested verbatim relevance score if it is non-negative (valid),
1053 // if inline autocomplete isn't prevented (always show verbatim on backspace),
1054 // and if it won't suppress verbatim, leaving no keyword provider matches.
1055 // Otherwise, if the keyword provider returned no matches and was still able
1056 // to suppress verbatim, the user would have no search/nav matches and may be
1057 // left unable to search using their keyword provider from the omnibox.
1058 // Check for results on each verbatim calculation, as results from older
1059 // queries (on previous input) may be trimmed for failing to inline new input.
[email protected]bc8bb0cd2013-06-24 21:50:231060 bool use_server_relevance =
1061 (keyword_results_.verbatim_relevance >= 0) &&
[email protected]dab8d52d2013-03-05 07:35:281062 !input_.prevent_inline_autocomplete() &&
[email protected]bc8bb0cd2013-06-24 21:50:231063 ((keyword_results_.verbatim_relevance > 0) ||
[email protected]cc1526e2013-05-17 04:04:241064 !keyword_results_.suggest_results.empty() ||
[email protected]bc8bb0cd2013-06-24 21:50:231065 !keyword_results_.navigation_results.empty());
[email protected]d30268a2013-06-25 22:31:071066 if (relevance_from_server)
1067 *relevance_from_server = use_server_relevance;
[email protected]bc8bb0cd2013-06-24 21:50:231068 return use_server_relevance ?
1069 keyword_results_.verbatim_relevance :
1070 CalculateRelevanceForKeywordVerbatim(keyword_input_.type(),
1071 keyword_input_.prefer_keyword());
[email protected]5423e562013-02-07 03:58:451072}
1073
[email protected]51124552011-07-16 01:37:101074int SearchProvider::CalculateRelevanceForHistory(
[email protected]bc8bb0cd2013-06-24 21:50:231075 const base::Time& time,
[email protected]51124552011-07-16 01:37:101076 bool is_keyword,
[email protected]78e5e432013-08-03 02:10:101077 bool use_aggressive_method,
1078 bool prevent_search_history_inlining) const {
[email protected]aa613d62010-11-09 20:40:181079 // The relevance of past searches falls off over time. There are two distinct
1080 // equations used. If the first equation is used (searches to the primary
[email protected]78e5e432013-08-03 02:10:101081 // provider that we want to score aggressively), the score is in the range
1082 // 1300-1599 (unless |prevent_search_history_inlining|, in which case
[email protected]d8cd76b2013-07-10 09:46:161083 // it's in the range 1200-1299). If the second equation is used the
1084 // relevance of a search 15 minutes ago is discounted 50 points, while the
1085 // relevance of a search two weeks ago is discounted 450 points.
[email protected]bc8bb0cd2013-06-24 21:50:231086 double elapsed_time = std::max((base::Time::Now() - time).InSecondsF(), 0.0);
[email protected]188b50c2013-03-28 07:19:421087 bool is_primary_provider = is_keyword || !providers_.has_keyword_provider();
[email protected]78e5e432013-08-03 02:10:101088 if (is_primary_provider && use_aggressive_method) {
[email protected]aa613d62010-11-09 20:40:181089 // Searches with the past two days get a different curve.
[email protected]51124552011-07-16 01:37:101090 const double autocomplete_time = 2 * 24 * 60 * 60;
[email protected]aa613d62010-11-09 20:40:181091 if (elapsed_time < autocomplete_time) {
[email protected]d8cd76b2013-07-10 09:46:161092 int max_score = is_keyword ? 1599 : 1399;
[email protected]78e5e432013-08-03 02:10:101093 if (prevent_search_history_inlining)
[email protected]d8cd76b2013-07-10 09:46:161094 max_score = 1299;
1095 return max_score - static_cast<int>(99 *
[email protected]aa613d62010-11-09 20:40:181096 std::pow(elapsed_time / autocomplete_time, 2.5));
1097 }
1098 elapsed_time -= autocomplete_time;
1099 }
1100
[email protected]c3a4bd992010-08-18 20:25:011101 const int score_discount =
1102 static_cast<int>(6.5 * std::pow(elapsed_time, 0.3));
initial.commit09911bf2008-07-26 23:55:291103
[email protected]6c85aa02009-02-27 12:08:091104 // Don't let scores go below 0. Negative relevance scores are meaningful in
1105 // a different way.
initial.commit09911bf2008-07-26 23:55:291106 int base_score;
[email protected]51124552011-07-16 01:37:101107 if (is_primary_provider)
[email protected]3dc75b12014-06-08 00:02:221108 base_score = (input_.type() == metrics::OmniboxInputType::URL) ? 750 : 1050;
[email protected]51124552011-07-16 01:37:101109 else
1110 base_score = 200;
initial.commit09911bf2008-07-26 23:55:291111 return std::max(0, base_score - score_discount);
1112}
1113
initial.commit09911bf2008-07-26 23:55:291114AutocompleteMatch SearchProvider::NavigationToMatch(
[email protected]188b50c2013-03-28 07:19:421115 const NavigationResult& navigation) {
[email protected]5889bfb2014-03-19 00:26:481116 base::string16 input;
1117 const bool trimmed_whitespace = base::TrimWhitespace(
1118 navigation.from_keyword_provider() ?
1119 keyword_input_.text() : input_.text(),
1120 base::TRIM_TRAILING, &input) != base::TRIM_NONE;
[email protected]55ce8f12012-05-09 04:44:081121 AutocompleteMatch match(this, navigation.relevance(), false,
[email protected]78981d8c2014-05-09 15:05:471122 navigation.type());
[email protected]55ce8f12012-05-09 04:44:081123 match.destination_url = navigation.url();
[email protected]78981d8c2014-05-09 15:05:471124 BaseSearchProvider::SetDeletionURL(navigation.deletion_url(), &match);
[email protected]23db6492014-01-16 02:35:301125 // First look for the user's input inside the formatted url as it would be
[email protected]371dab12012-06-01 03:23:551126 // without trimming the scheme, so we can find matches at the beginning of the
1127 // scheme.
[email protected]371dab12012-06-01 03:23:551128 const URLPrefix* prefix =
[email protected]23db6492014-01-16 02:35:301129 URLPrefix::BestURLPrefix(navigation.formatted_url(), input);
[email protected]371dab12012-06-01 03:23:551130 size_t match_start = (prefix == NULL) ?
[email protected]23db6492014-01-16 02:35:301131 navigation.formatted_url().find(input) : prefix->prefix.length();
[email protected]d2445c82013-11-04 22:28:351132 bool trim_http = !AutocompleteInput::HasHTTPScheme(input) &&
1133 (!prefix || (match_start != 0));
[email protected]23db6492014-01-16 02:35:301134 const net::FormatUrlTypes format_types =
1135 net::kFormatUrlOmitAll & ~(trim_http ? 0 : net::kFormatUrlOmitHTTP);
[email protected]371dab12012-06-01 03:23:551136
[email protected]371dab12012-06-01 03:23:551137 const std::string languages(
1138 profile_->GetPrefs()->GetString(prefs::kAcceptLanguages));
[email protected]23db6492014-01-16 02:35:301139 size_t inline_autocomplete_offset = (prefix == NULL) ?
1140 base::string16::npos : (match_start + input.length());
[email protected]371dab12012-06-01 03:23:551141 match.fill_into_edit +=
[email protected]5655ea32014-06-21 05:28:081142 AutocompleteInput::FormattedStringWithEquivalentMeaning(
1143 navigation.url(),
[email protected]371dab12012-06-01 03:23:551144 net::FormatUrl(navigation.url(), languages, format_types,
1145 net::UnescapeRule::SPACES, NULL, NULL,
[email protected]5655ea32014-06-21 05:28:081146 &inline_autocomplete_offset),
[email protected]a817ed392014-06-27 05:03:001147 ChromeAutocompleteSchemeClassifier(profile_));
[email protected]14119032013-11-07 08:14:261148 // Preserve the forced query '?' prefix in |match.fill_into_edit|.
1149 // Otherwise, user edits to a suggestion would show non-Search results.
[email protected]3dc75b12014-06-08 00:02:221150 if (input_.type() == metrics::OmniboxInputType::FORCED_QUERY) {
[email protected]670d3232013-12-24 17:58:581151 match.fill_into_edit.insert(0, base::ASCIIToUTF16("?"));
[email protected]0085863a2013-12-06 21:19:031152 if (inline_autocomplete_offset != base::string16::npos)
[email protected]14119032013-11-07 08:14:261153 ++inline_autocomplete_offset;
1154 }
[email protected]6c94a1022014-02-21 03:48:041155 if (inline_autocomplete_offset != base::string16::npos) {
[email protected]518024c2013-07-19 23:40:251156 DCHECK(inline_autocomplete_offset <= match.fill_into_edit.length());
1157 match.inline_autocompletion =
1158 match.fill_into_edit.substr(inline_autocomplete_offset);
1159 }
[email protected]6c94a1022014-02-21 03:48:041160 // An inlineable navsuggestion can only be the default match when there
1161 // is no keyword provider active, lest it appear first and break the user
[email protected]5889bfb2014-03-19 00:26:481162 // out of keyword mode. It can also only be default if either the inline
1163 // autocompletion is empty or we're not preventing inline autocompletion.
1164 // Finally, if we have an inlineable navsuggestion with an inline completion
1165 // that we're not preventing, make sure we didn't trim any whitespace.
1166 // We don't want to claim http://foo.com/bar is inlineable against the
1167 // input "foo.com/b ".
[email protected]c7b8be02014-07-11 19:46:341168 match.allowed_to_be_default_match = (prefix != NULL) &&
[email protected]6c94a1022014-02-21 03:48:041169 (providers_.GetKeywordProviderURL() == NULL) &&
[email protected]5889bfb2014-03-19 00:26:481170 (match.inline_autocompletion.empty() ||
[email protected]78981d8c2014-05-09 15:05:471171 (!input_.prevent_inline_autocomplete() && !trimmed_whitespace));
[email protected]c7b8be02014-07-11 19:46:341172 match.EnsureUWYTIsAllowedToBeDefault(
1173 input_.canonicalized_url(), providers_.template_url_service());
[email protected]371dab12012-06-01 03:23:551174
[email protected]23db6492014-01-16 02:35:301175 match.contents = navigation.match_contents();
1176 match.contents_class = navigation.match_contents_class();
[email protected]55ce8f12012-05-09 04:44:081177 match.description = navigation.description();
[email protected]371dab12012-06-01 03:23:551178 AutocompleteMatch::ClassifyMatchInString(input, match.description,
1179 ACMatchClassification::NONE, &match.description_class);
[email protected]d30268a2013-06-25 22:31:071180
1181 match.RecordAdditionalInfo(
1182 kRelevanceFromServerKey,
1183 navigation.relevance_from_server() ? kTrue : kFalse);
[email protected]987fad782013-08-28 06:23:181184 match.RecordAdditionalInfo(kShouldPrefetchKey, kFalse);
[email protected]d30268a2013-06-25 22:31:071185
initial.commit09911bf2008-07-26 23:55:291186 return match;
1187}
[email protected]4ab4c7c2010-11-24 04:49:341188
[email protected]4ab4c7c2010-11-24 04:49:341189void SearchProvider::UpdateDone() {
[email protected]2cdf1172012-08-26 12:21:331190 // We're done when the timer isn't running, there are no suggest queries
[email protected]5fac3782013-03-06 09:32:311191 // pending, and we're not waiting on Instant.
[email protected]e1290ee62013-06-26 18:31:151192 done_ = !timer_.IsRunning() && (suggest_results_pending_ == 0);
[email protected]4ab4c7c2010-11-24 04:49:341193}
[email protected]20184242014-05-14 02:57:421194
1195std::string SearchProvider::GetSessionToken() {
1196 base::TimeTicks current_time(base::TimeTicks::Now());
1197 // Renew token if it expired.
1198 if (current_time > token_expiration_time_) {
1199 const size_t kTokenBytes = 12;
1200 std::string raw_data;
1201 base::RandBytes(WriteInto(&raw_data, kTokenBytes + 1), kTokenBytes);
1202 base::Base64Encode(raw_data, &current_token_);
[email protected]ab2c31f72014-05-17 17:03:531203
1204 // Make the base64 encoded value URL and filename safe(see RFC 3548).
1205 std::replace(current_token_.begin(), current_token_.end(), '+', '-');
1206 std::replace(current_token_.begin(), current_token_.end(), '/', '_');
[email protected]20184242014-05-14 02:57:421207 }
1208
1209 // Extend expiration time another 60 seconds.
1210 token_expiration_time_ = current_time + base::TimeDelta::FromSeconds(60);
1211
1212 return current_token_;
1213}
[email protected]2ef2a6642014-07-30 05:50:291214
1215void SearchProvider::RegisterDisplayedAnswers(
1216 const AutocompleteResult& result) {
1217 if (result.empty())
1218 return;
1219
1220 // The answer must be in the first or second slot to be considered. It should
1221 // only be in the second slot if AutocompleteController ranked a local search
1222 // history or a verbatim item higher than the answer.
1223 AutocompleteResult::const_iterator match = result.begin();
1224 if (match->answer_contents.empty() && result.size() > 1)
1225 ++match;
1226 if (match->answer_contents.empty() || match->answer_type.empty() ||
1227 match->fill_into_edit.empty())
1228 return;
1229
1230 // Valid answer encountered, cache it for further queries.
1231 last_answer_seen_.full_query_text = match->fill_into_edit;
1232 last_answer_seen_.query_type = match->answer_type;
1233}
1234
1235void SearchProvider::DoAnswersQuery(const AutocompleteInput& input) {
1236 // If the query text starts with trimmed input, this is valid prefetch data.
1237 prefetch_data_ = StartsWith(last_answer_seen_.full_query_text,
1238 base::CollapseWhitespace(input.text(), false),
1239 false) ?
1240 last_answer_seen_ : AnswersQueryData();
1241}