blob: 1b77f3403b9d4668440db12768bce082add6b692 [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]2041cf342010-02-19 03:15:5910#include "base/callback.h"
[email protected]51124552011-07-16 01:37:1011#include "base/i18n/break_iterator.h"
[email protected]503d03872011-05-06 08:36:2612#include "base/i18n/case_conversion.h"
[email protected]ffbec692012-02-26 20:26:4213#include "base/json/json_string_value_serializer.h"
[email protected]fa1e0e12013-07-18 00:10:1414#include "base/message_loop/message_loop.h"
[email protected]f5b95ba92012-03-27 14:05:1915#include "base/metrics/histogram.h"
[email protected]3853a4c2013-02-11 17:15:5716#include "base/prefs/pref_service.h"
[email protected]5889bfb2014-03-19 00:26:4817#include "base/strings/string_util.h"
[email protected]135cb802013-06-09 16:44:2018#include "base/strings/utf_string_conversions.h"
[email protected]ea3b9a502011-04-04 14:19:3719#include "chrome/browser/autocomplete/autocomplete_classifier.h"
[email protected]810ffba2012-06-12 01:07:4820#include "chrome/browser/autocomplete/autocomplete_classifier_factory.h"
[email protected]5af9bc82012-06-29 00:53:4821#include "chrome/browser/autocomplete/autocomplete_provider_listener.h"
[email protected]73c2b1632012-07-02 22:51:3822#include "chrome/browser/autocomplete/autocomplete_result.h"
[email protected]2c812ba02011-07-14 00:23:1523#include "chrome/browser/autocomplete/keyword_provider.h"
[email protected]371dab12012-06-01 03:23:5524#include "chrome/browser/autocomplete/url_prefix.h"
[email protected]9b9fa672013-11-07 06:04:5225#include "chrome/browser/google/google_util.h"
[email protected]6a2c09f2013-01-25 04:50:0726#include "chrome/browser/history/history_service.h"
[email protected]9d2db762012-06-19 00:01:1027#include "chrome/browser/history/history_service_factory.h"
[email protected]10c2d692012-05-11 05:32:2328#include "chrome/browser/history/in_memory_database.h"
[email protected]ab7780792013-01-10 01:26:0929#include "chrome/browser/metrics/variations/variations_http_header_provider.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]a7b8e43d2013-03-18 18:52:4332#include "chrome/browser/search/search.h"
[email protected]9899a612012-08-21 23:50:0433#include "chrome/browser/search_engines/template_url_prepopulate_data.h"
[email protected]8e5c89a2011-06-07 18:13:3334#include "chrome/browser/search_engines/template_url_service.h"
35#include "chrome/browser/search_engines/template_url_service_factory.h"
[email protected]c4a9d4c2013-08-10 07:06:2736#include "chrome/browser/ui/search/instant_controller.h"
initial.commit09911bf2008-07-26 23:55:2937#include "chrome/common/pref_names.h"
[email protected]dcf7d352009-02-26 01:56:0238#include "chrome/common/url_constants.h"
[email protected]7267ff82013-12-03 17:20:3039#include "content/public/browser/user_metrics.h"
[email protected]34ac8f32009-02-22 23:03:2740#include "grit/generated_resources.h"
initial.commit09911bf2008-07-26 23:55:2941#include "net/base/escape.h"
[email protected]d3cf8682f02012-02-29 23:29:3442#include "net/base/load_flags.h"
[email protected]371dab12012-06-01 03:23:5543#include "net/base/net_util.h"
[email protected]bd3b4712012-12-18 17:01:3044#include "net/http/http_request_headers.h"
[email protected]3dc1bc42012-06-19 08:20:5345#include "net/url_request/url_fetcher.h"
[email protected]319d9e6f2009-02-18 19:47:2146#include "net/url_request/url_request_status.h"
[email protected]c051a1b2011-01-21 23:30:1747#include "ui/base/l10n/l10n_util.h"
[email protected]761fa4702013-07-02 15:25:1548#include "url/url_util.h"
initial.commit09911bf2008-07-26 23:55:2949
[email protected]bc8bb0cd2013-06-24 21:50:2350
51// Helpers --------------------------------------------------------------------
[email protected]e1acf6f2008-10-27 20:43:3352
[email protected]51124552011-07-16 01:37:1053namespace {
54
[email protected]7706a522012-08-16 17:42:2555// We keep track in a histogram how many suggest requests we send, how
56// many suggest requests we invalidate (e.g., due to a user typing
57// another character), and how many replies we receive.
58// *** ADD NEW ENUMS AFTER ALL PREVIOUSLY DEFINED ONES! ***
59// (excluding the end-of-list enum value)
60// We do not want values of existing enums to change or else it screws
61// up the statistics.
62enum SuggestRequestsHistogramValue {
63 REQUEST_SENT = 1,
64 REQUEST_INVALIDATED,
65 REPLY_RECEIVED,
66 MAX_SUGGEST_REQUEST_HISTOGRAM_VALUE
67};
68
[email protected]90fe2bb2013-01-15 03:42:1369// The verbatim score for an input which is not an URL.
70const int kNonURLVerbatimRelevance = 1300;
71
[email protected]7706a522012-08-16 17:42:2572// Increments the appropriate value in the histogram by one.
73void LogOmniboxSuggestRequest(
74 SuggestRequestsHistogramValue request_value) {
75 UMA_HISTOGRAM_ENUMERATION("Omnibox.SuggestRequests", request_value,
76 MAX_SUGGEST_REQUEST_HISTOGRAM_VALUE);
77}
78
[email protected]0085863a2013-12-06 21:19:0379bool HasMultipleWords(const base::string16& text) {
[email protected]51124552011-07-16 01:37:1080 base::i18n::BreakIterator i(text, base::i18n::BreakIterator::BREAK_WORD);
81 bool found_word = false;
82 if (i.Init()) {
83 while (i.Advance()) {
84 if (i.IsWord()) {
85 if (found_word)
86 return true;
87 found_word = true;
88 }
89 }
90 }
91 return false;
92}
93
[email protected]d1f0a7f2012-06-05 10:26:4294} // namespace
[email protected]51124552011-07-16 01:37:1095
[email protected]3954c3a2012-04-10 20:17:5596// SearchProvider::Providers --------------------------------------------------
[email protected]b547666d2009-04-23 16:37:5897
[email protected]85b8d6f2012-05-08 20:53:4798SearchProvider::Providers::Providers(TemplateURLService* template_url_service)
[email protected]02346202014-02-05 05:18:3099 : template_url_service_(template_url_service) {}
[email protected]85b8d6f2012-05-08 20:53:47100
101const TemplateURL* SearchProvider::Providers::GetDefaultProviderURL() const {
102 return default_provider_.empty() ? NULL :
103 template_url_service_->GetTemplateURLForKeyword(default_provider_);
104}
105
106const TemplateURL* SearchProvider::Providers::GetKeywordProviderURL() const {
107 return keyword_provider_.empty() ? NULL :
108 template_url_service_->GetTemplateURLForKeyword(keyword_provider_);
[email protected]257ab712009-04-14 17:16:24109}
110
[email protected]3954c3a2012-04-10 20:17:55111
[email protected]bc8bb0cd2013-06-24 21:50:23112// SearchProvider::CompareScoredResults ---------------------------------------
113
114class SearchProvider::CompareScoredResults {
115 public:
116 bool operator()(const Result& a, const Result& b) {
117 // Sort in descending relevance order.
118 return a.relevance() > b.relevance();
119 }
120};
121
122
[email protected]3954c3a2012-04-10 20:17:55123// SearchProvider -------------------------------------------------------------
124
125// static
[email protected]24dbf2302013-04-05 16:59:25126int SearchProvider::kMinimumTimeBetweenSuggestQueriesMs = 100;
[email protected]3954c3a2012-04-10 20:17:55127
[email protected]bc8bb0cd2013-06-24 21:50:23128SearchProvider::SearchProvider(AutocompleteProviderListener* listener,
129 Profile* profile)
[email protected]02346202014-02-05 05:18:30130 : BaseSearchProvider(listener, profile, AutocompleteProvider::TYPE_SEARCH),
[email protected]cfa164bf2014-03-19 11:51:15131 providers_(TemplateURLServiceFactory::GetForProfile(profile)) {
[email protected]bc8bb0cd2013-06-24 21:50:23132}
133
[email protected]cb86ee6f2013-04-28 16:58:15134// static
[email protected]987fad782013-08-28 06:23:18135std::string SearchProvider::GetSuggestMetadata(const AutocompleteMatch& match) {
136 return match.GetAdditionalInfo(kSuggestMetadataKey);
137}
138
[email protected]bc8bb0cd2013-06-24 21:50:23139void SearchProvider::ResetSession() {
140 field_trial_triggered_in_session_ = false;
[email protected]4ab4c7c2010-11-24 04:49:34141}
142
[email protected]bc8bb0cd2013-06-24 21:50:23143SearchProvider::~SearchProvider() {
144}
145
146// static
[email protected]0085863a2013-12-06 21:19:03147void SearchProvider::RemoveStaleResults(const base::string16& input,
[email protected]bc8bb0cd2013-06-24 21:50:23148 int verbatim_relevance,
149 SuggestResults* suggest_results,
150 NavigationResults* navigation_results) {
151 DCHECK_GE(verbatim_relevance, 0);
152 // Keep pointers to the head of (the highest scoring elements of)
153 // |suggest_results| and |navigation_results|. Iterate down the lists
154 // removing non-inlineable results in order of decreasing relevance
155 // scores. Stop when the highest scoring element among those remaining
156 // is inlineable or the element is less than |verbatim_relevance|.
157 // This allows non-inlineable lower-scoring results to remain
158 // because (i) they are guaranteed to not be inlined and (ii)
159 // letting them remain reduces visual jank. For instance, as the
160 // user types the mis-spelled query "fpobar" (for foobar), the
161 // suggestion "foobar" will be suggested on every keystroke. If the
162 // SearchProvider always removes all non-inlineable results, the user will
163 // see visual jitter/jank as the result disappears and re-appears moments
164 // later as the suggest server returns results.
165 SuggestResults::iterator sug_it = suggest_results->begin();
166 NavigationResults::iterator nav_it = navigation_results->begin();
167 while ((sug_it != suggest_results->end()) ||
168 (nav_it != navigation_results->end())) {
169 const int sug_rel =
170 (sug_it != suggest_results->end()) ? sug_it->relevance() : -1;
171 const int nav_rel =
172 (nav_it != navigation_results->end()) ? nav_it->relevance() : -1;
173 if (std::max(sug_rel, nav_rel) < verbatim_relevance)
174 break;
175 if (sug_rel > nav_rel) {
176 // The current top result is a search suggestion.
177 if (sug_it->IsInlineable(input))
178 break;
179 sug_it = suggest_results->erase(sug_it);
180 } else if (sug_rel == nav_rel) {
181 // Have both results and they're tied.
182 const bool sug_inlineable = sug_it->IsInlineable(input);
183 const bool nav_inlineable = nav_it->IsInlineable(input);
184 if (!sug_inlineable)
185 sug_it = suggest_results->erase(sug_it);
186 if (!nav_inlineable)
187 nav_it = navigation_results->erase(nav_it);
188 if (sug_inlineable || nav_inlineable)
189 break;
190 } else {
191 // The current top result is a navigational suggestion.
192 if (nav_it->IsInlineable(input))
193 break;
194 nav_it = navigation_results->erase(nav_it);
195 }
196 }
197}
198
[email protected]ee6110b2014-01-09 22:26:31199void SearchProvider::UpdateMatchContentsClass(const base::string16& input_text,
[email protected]23db6492014-01-16 02:35:30200 Results* results) {
201 for (SuggestResults::iterator sug_it = results->suggest_results.begin();
202 sug_it != results->suggest_results.end(); ++sug_it) {
[email protected]ee6110b2014-01-09 22:26:31203 sug_it->ClassifyMatchContents(false, input_text);
204 }
[email protected]23db6492014-01-16 02:35:30205 const std::string languages(
206 profile_->GetPrefs()->GetString(prefs::kAcceptLanguages));
207 for (NavigationResults::iterator nav_it = results->navigation_results.begin();
208 nav_it != results->navigation_results.end(); ++nav_it) {
209 nav_it->CalculateAndClassifyMatchContents(false, input_text, languages);
210 }
[email protected]ee6110b2014-01-09 22:26:31211}
212
213// static
[email protected]bc8bb0cd2013-06-24 21:50:23214int SearchProvider::CalculateRelevanceForKeywordVerbatim(
215 AutocompleteInput::Type type,
216 bool prefer_keyword) {
217 // This function is responsible for scoring verbatim query matches
218 // for non-extension keywords. KeywordProvider::CalculateRelevance()
219 // scores verbatim query matches for extension keywords, as well as
220 // for keyword matches (i.e., suggestions of a keyword itself, not a
221 // suggestion of a query on a keyword search engine). These two
222 // functions are currently in sync, but there's no reason we
223 // couldn't decide in the future to score verbatim matches
224 // differently for extension and non-extension keywords. If you
225 // make such a change, however, you should update this comment to
226 // describe it, so it's clear why the functions diverge.
227 if (prefer_keyword)
228 return 1500;
229 return (type == AutocompleteInput::QUERY) ? 1450 : 1100;
230}
231
initial.commit09911bf2008-07-26 23:55:29232void SearchProvider::Start(const AutocompleteInput& input,
[email protected]8deeb952008-10-09 18:21:27233 bool minimal_changes) {
[email protected]04504c242013-01-22 21:08:55234 // Do our best to load the model as early as possible. This will reduce
235 // odds of having the model not ready when really needed (a non-empty input).
236 TemplateURLService* model = providers_.template_url_service();
237 DCHECK(model);
238 model->Load();
239
initial.commit09911bf2008-07-26 23:55:29240 matches_.clear();
[email protected]618d6e62012-12-16 05:55:57241 field_trial_triggered_ = false;
initial.commit09911bf2008-07-26 23:55:29242
[email protected]6c85aa02009-02-27 12:08:09243 // Can't return search/suggest results for bogus input or without a profile.
initial.commit09911bf2008-07-26 23:55:29244 if (!profile_ || (input.type() == AutocompleteInput::INVALID)) {
[email protected]9950e5d52014-02-25 23:34:19245 Stop(true);
initial.commit09911bf2008-07-26 23:55:29246 return;
247 }
248
[email protected]14710852013-02-05 23:45:41249 keyword_input_ = input;
[email protected]257ab712009-04-14 17:16:24250 const TemplateURL* keyword_provider =
[email protected]14710852013-02-05 23:45:41251 KeywordProvider::GetSubstitutingTemplateURLForInput(model,
252 &keyword_input_);
253 if (keyword_provider == NULL)
254 keyword_input_.Clear();
255 else if (keyword_input_.text().empty())
[email protected]257ab712009-04-14 17:16:24256 keyword_provider = NULL;
[email protected]257ab712009-04-14 17:16:24257
[email protected]85b8d6f2012-05-08 20:53:47258 const TemplateURL* default_provider = model->GetDefaultSearchProvider();
[email protected]9b74ab52012-03-30 16:08:07259 if (default_provider && !default_provider->SupportsReplacement())
[email protected]257ab712009-04-14 17:16:24260 default_provider = NULL;
261
262 if (keyword_provider == default_provider)
[email protected]e17511f2011-07-13 14:09:18263 default_provider = NULL; // No use in querying the same provider twice.
[email protected]257ab712009-04-14 17:16:24264
265 if (!default_provider && !keyword_provider) {
266 // No valid providers.
[email protected]9950e5d52014-02-25 23:34:19267 Stop(true);
initial.commit09911bf2008-07-26 23:55:29268 return;
269 }
270
271 // If we're still running an old query but have since changed the query text
[email protected]257ab712009-04-14 17:16:24272 // or the providers, abort the query.
[email protected]0085863a2013-12-06 21:19:03273 base::string16 default_provider_keyword(default_provider ?
274 default_provider->keyword() : base::string16());
275 base::string16 keyword_provider_keyword(keyword_provider ?
276 keyword_provider->keyword() : base::string16());
[email protected]9e789742011-01-10 23:27:32277 if (!minimal_changes ||
[email protected]85b8d6f2012-05-08 20:53:47278 !providers_.equal(default_provider_keyword, keyword_provider_keyword)) {
[email protected]bb900e02013-03-14 14:15:29279 // Cancel any in-flight suggest requests.
[email protected]e1290ee62013-06-26 18:31:15280 if (!done_)
[email protected]e29249dc52012-07-19 17:33:50281 Stop(false);
[email protected]257ab712009-04-14 17:16:24282 }
initial.commit09911bf2008-07-26 23:55:29283
[email protected]85b8d6f2012-05-08 20:53:47284 providers_.set(default_provider_keyword, keyword_provider_keyword);
initial.commit09911bf2008-07-26 23:55:29285
286 if (input.text().empty()) {
287 // User typed "?" alone. Give them a placeholder result indicating what
288 // this syntax does.
[email protected]257ab712009-04-14 17:16:24289 if (default_provider) {
[email protected]69c579e2010-04-23 20:01:00290 AutocompleteMatch match;
291 match.provider = this;
[email protected]a2fedb1e2011-01-25 15:23:36292 match.contents.assign(l10n_util::GetStringUTF16(IDS_EMPTY_KEYWORD_VALUE));
[email protected]257ab712009-04-14 17:16:24293 match.contents_class.push_back(
[email protected]2c33dd22010-02-11 21:46:35294 ACMatchClassification(0, ACMatchClassification::NONE));
[email protected]85b8d6f2012-05-08 20:53:47295 match.keyword = providers_.default_provider();
[email protected]45f89a92013-08-12 13:41:36296 match.allowed_to_be_default_match = true;
[email protected]257ab712009-04-14 17:16:24297 matches_.push_back(match);
298 }
[email protected]9950e5d52014-02-25 23:34:19299 Stop(true);
initial.commit09911bf2008-07-26 23:55:29300 return;
301 }
302
303 input_ = input;
304
[email protected]e1290ee62013-06-26 18:31:15305 DoHistoryQuery(minimal_changes);
306 StartOrStopSuggestQuery(minimal_changes);
[email protected]344946a12012-12-20 12:03:42307 UpdateMatches();
initial.commit09911bf2008-07-26 23:55:29308}
309
[email protected]d4a94b92014-03-04 01:35:22310void SearchProvider::SortResults(bool is_keyword,
311 const base::ListValue* relevances,
312 Results* results) {
313 // Ignore suggested scores for non-keyword matches in keyword mode; if the
314 // server is allowed to score these, it could interfere with the user's
315 // ability to get good keyword results.
316 const bool abandon_suggested_scores =
317 !is_keyword && !providers_.keyword_provider().empty();
318 // Apply calculated relevance scores to suggestions if a valid list was
319 // not provided or we're abandoning suggested scores entirely.
320 if ((relevances == NULL) || abandon_suggested_scores) {
321 ApplyCalculatedSuggestRelevance(&results->suggest_results);
322 ApplyCalculatedNavigationRelevance(&results->navigation_results);
323 // If abandoning scores entirely, also abandon the verbatim score.
324 if (abandon_suggested_scores)
325 results->verbatim_relevance = -1;
326 }
327
328 // Keep the result lists sorted.
329 const CompareScoredResults comparator = CompareScoredResults();
330 std::stable_sort(results->suggest_results.begin(),
331 results->suggest_results.end(),
332 comparator);
333 std::stable_sort(results->navigation_results.begin(),
334 results->navigation_results.end(),
335 comparator);
336}
337
[email protected]cfa164bf2014-03-19 11:51:15338const TemplateURL* SearchProvider::GetTemplateURL(bool is_keyword) const {
339 return is_keyword ? providers_.GetKeywordProviderURL()
340 : providers_.GetDefaultProviderURL();
[email protected]9487b392014-02-14 02:48:18341}
342
[email protected]d4a94b92014-03-04 01:35:22343const AutocompleteInput SearchProvider::GetInput(bool is_keyword) const {
344 return is_keyword ? keyword_input_ : input_;
[email protected]9487b392014-02-14 02:48:18345}
346
[email protected]cfa164bf2014-03-19 11:51:15347BaseSearchProvider::Results* SearchProvider::GetResultsToFill(bool is_keyword) {
348 return is_keyword ? &keyword_results_ : &default_results_;
349}
350
[email protected]9487b392014-02-14 02:48:18351bool SearchProvider::ShouldAppendExtraParams(
352 const SuggestResult& result) const {
353 return !result.from_keyword_provider() ||
354 providers_.default_provider().empty();
355}
356
[email protected]ef6866f2014-02-18 08:26:34357void SearchProvider::StopSuggest() {
358 // Increment the appropriate field in the histogram by the number of
359 // pending requests that were invalidated.
360 for (int i = 0; i < suggest_results_pending_; ++i)
361 LogOmniboxSuggestRequest(REQUEST_INVALIDATED);
362 suggest_results_pending_ = 0;
363 timer_.Stop();
364 // Stop any in-progress URL fetches.
365 keyword_fetcher_.reset();
366 default_fetcher_.reset();
367}
368
369void SearchProvider::ClearAllResults() {
370 keyword_results_.Clear();
371 default_results_.Clear();
372}
373
[email protected]d4a94b92014-03-04 01:35:22374int SearchProvider::GetDefaultResultRelevance() const {
375 return -1;
376}
377
[email protected]7267ff82013-12-03 17:20:30378void SearchProvider::RecordDeletionResult(bool success) {
379 if (success) {
380 content::RecordAction(
[email protected]e6e30ac2014-01-13 21:24:39381 base::UserMetricsAction("Omnibox.ServerSuggestDelete.Success"));
[email protected]7267ff82013-12-03 17:20:30382 } else {
383 content::RecordAction(
[email protected]e6e30ac2014-01-13 21:24:39384 base::UserMetricsAction("Omnibox.ServerSuggestDelete.Failure"));
[email protected]7267ff82013-12-03 17:20:30385 }
386}
387
[email protected]cfa164bf2014-03-19 11:51:15388void SearchProvider::LogFetchComplete(bool success, bool is_keyword) {
389 LogOmniboxSuggestRequest(REPLY_RECEIVED);
390 // Record response time for suggest requests sent to Google. We care
391 // only about the common case: the Google default provider used in
392 // non-keyword mode.
393 const TemplateURL* default_url = providers_.GetDefaultProviderURL();
394 if (!is_keyword && default_url &&
395 (TemplateURLPrepopulateData::GetEngineType(*default_url) ==
396 SEARCH_ENGINE_GOOGLE)) {
397 const base::TimeDelta elapsed_time =
398 base::TimeTicks::Now() - time_suggest_request_sent_;
399 if (success) {
400 UMA_HISTOGRAM_TIMES("Omnibox.SuggestRequest.Success.GoogleResponseTime",
401 elapsed_time);
402 } else {
403 UMA_HISTOGRAM_TIMES("Omnibox.SuggestRequest.Failure.GoogleResponseTime",
404 elapsed_time);
405 }
406 }
407}
408
409bool SearchProvider::IsKeywordFetcher(const net::URLFetcher* fetcher) const {
410 return fetcher == keyword_fetcher_.get();
411}
412
413void SearchProvider::UpdateMatches() {
414 base::TimeTicks update_matches_start_time(base::TimeTicks::Now());
415 ConvertResultsToAutocompleteMatches();
416
417 // Check constraints that may be violated by suggested relevances.
418 if (!matches_.empty() &&
419 (default_results_.HasServerProvidedScores() ||
420 keyword_results_.HasServerProvidedScores())) {
421 // These blocks attempt to repair undesirable behavior by suggested
422 // relevances with minimal impact, preserving other suggested relevances.
423
424 // True if the omnibox will reorder matches as necessary to make the first
425 // one something that is allowed to be the default match.
426 const bool omnibox_will_reorder_for_legal_default_match =
427 OmniboxFieldTrial::ReorderForLegalDefaultMatch(
428 input_.current_page_classification());
429 if (IsTopMatchNavigationInKeywordMode(
430 omnibox_will_reorder_for_legal_default_match)) {
431 // Correct the suggested relevance scores if the top match is a
432 // navigation in keyword mode, since inlining a navigation match
433 // would break the user out of keyword mode. This will only be
434 // triggered in regular (non-reorder) mode; in reorder mode,
435 // navigation matches are marked as not allowed to be the default
436 // match and hence IsTopMatchNavigation() will always return false.
437 DCHECK(!omnibox_will_reorder_for_legal_default_match);
438 DemoteKeywordNavigationMatchesPastTopQuery();
439 ConvertResultsToAutocompleteMatches();
440 DCHECK(!IsTopMatchNavigationInKeywordMode(
441 omnibox_will_reorder_for_legal_default_match));
442 }
443 if (!HasKeywordDefaultMatchInKeywordMode()) {
444 // In keyword mode, disregard the keyword verbatim suggested relevance
445 // if necessary so there at least one keyword match that's allowed to
446 // be the default match.
447 keyword_results_.verbatim_relevance = -1;
448 ConvertResultsToAutocompleteMatches();
449 }
450 if (IsTopMatchScoreTooLow(omnibox_will_reorder_for_legal_default_match)) {
451 // Disregard the suggested verbatim relevance if the top score is below
452 // the usual verbatim value. For example, a BarProvider may rely on
453 // SearchProvider's verbatim or inlineable matches for input "foo" (all
454 // allowed to be default match) to always outrank its own lowly-ranked
455 // "bar" matches that shouldn't be the default match.
456 default_results_.verbatim_relevance = -1;
457 keyword_results_.verbatim_relevance = -1;
458 ConvertResultsToAutocompleteMatches();
459 }
460 if (IsTopMatchSearchWithURLInput(
461 omnibox_will_reorder_for_legal_default_match)) {
462 // Disregard the suggested search and verbatim relevances if the input
463 // type is URL and the top match is a highly-ranked search suggestion.
464 // For example, prevent a search for "foo.com" from outranking another
465 // provider's navigation for "foo.com" or "foo.com/url_from_history".
466 ApplyCalculatedSuggestRelevance(&keyword_results_.suggest_results);
467 ApplyCalculatedSuggestRelevance(&default_results_.suggest_results);
468 default_results_.verbatim_relevance = -1;
469 keyword_results_.verbatim_relevance = -1;
470 ConvertResultsToAutocompleteMatches();
471 }
472 if (!HasValidDefaultMatch(omnibox_will_reorder_for_legal_default_match)) {
473 // If the omnibox is not going to reorder results to put a legal default
474 // match at the top, then this provider needs to guarantee that its top
475 // scoring result is a legal default match (i.e., it's either a verbatim
476 // match or inlinable). For example, input "foo" should not invoke a
477 // search for "bar", which would happen if the "bar" search match
478 // outranked all other matches. On the other hand, if the omnibox will
479 // reorder matches as necessary to put a legal default match at the top,
480 // all we need to guarantee is that SearchProvider returns a legal
481 // default match. (The omnibox always needs at least one legal default
482 // match, and it relies on SearchProvider to always return one.)
483 ApplyCalculatedRelevance();
484 ConvertResultsToAutocompleteMatches();
485 }
486 DCHECK(!IsTopMatchNavigationInKeywordMode(
487 omnibox_will_reorder_for_legal_default_match));
488 DCHECK(HasKeywordDefaultMatchInKeywordMode());
489 DCHECK(!IsTopMatchScoreTooLow(
490 omnibox_will_reorder_for_legal_default_match));
491 DCHECK(!IsTopMatchSearchWithURLInput(
492 omnibox_will_reorder_for_legal_default_match));
493 DCHECK(HasValidDefaultMatch(omnibox_will_reorder_for_legal_default_match));
494 }
495 UMA_HISTOGRAM_CUSTOM_COUNTS(
496 "Omnibox.SearchProviderMatches", matches_.size(), 1, 6, 7);
497
498 const TemplateURL* keyword_url = providers_.GetKeywordProviderURL();
499 if ((keyword_url != NULL) && HasKeywordDefaultMatchInKeywordMode()) {
500 // If there is a keyword match that is allowed to be the default match,
501 // then prohibit default provider matches from being the default match lest
502 // such matches cause the user to break out of keyword mode.
503 for (ACMatches::iterator it = matches_.begin(); it != matches_.end();
504 ++it) {
505 if (it->keyword != keyword_url->keyword())
506 it->allowed_to_be_default_match = false;
507 }
508 }
509
510 base::TimeTicks update_starred_start_time(base::TimeTicks::Now());
511 UpdateStarredStateOfMatches();
512 UMA_HISTOGRAM_TIMES("Omnibox.SearchProvider.UpdateStarredTime",
513 base::TimeTicks::Now() - update_starred_start_time);
514 UpdateDone();
515 UMA_HISTOGRAM_TIMES("Omnibox.SearchProvider.UpdateMatchesTime",
516 base::TimeTicks::Now() - update_matches_start_time);
517}
518
[email protected]bc8bb0cd2013-06-24 21:50:23519void SearchProvider::Run() {
520 // Start a new request with the current input.
521 suggest_results_pending_ = 0;
522 time_suggest_request_sent_ = base::TimeTicks::Now();
[email protected]abe441e2013-05-06 12:35:05523
[email protected]bc8bb0cd2013-06-24 21:50:23524 default_fetcher_.reset(CreateSuggestFetcher(kDefaultProviderURLFetcherID,
525 providers_.GetDefaultProviderURL(), input_));
526 keyword_fetcher_.reset(CreateSuggestFetcher(kKeywordProviderURLFetcherID,
527 providers_.GetKeywordProviderURL(), keyword_input_));
528
529 // Both the above can fail if the providers have been modified or deleted
530 // since the query began.
531 if (suggest_results_pending_ == 0) {
532 UpdateDone();
533 // We only need to update the listener if we're actually done.
534 if (done_)
535 listener_->OnProviderUpdate(false);
536 }
[email protected]601858c02010-09-01 17:08:20537}
538
[email protected]8d457132010-11-04 18:13:40539void SearchProvider::DoHistoryQuery(bool minimal_changes) {
540 // The history query results are synchronous, so if minimal_changes is true,
541 // we still have the last results and don't need to do anything.
542 if (minimal_changes)
initial.commit09911bf2008-07-26 23:55:29543 return;
544
[email protected]31afdf72013-09-26 04:29:36545 base::TimeTicks do_history_query_start_time(base::TimeTicks::Now());
546
[email protected]8d457132010-11-04 18:13:40547 keyword_history_results_.clear();
548 default_history_results_.clear();
initial.commit09911bf2008-07-26 23:55:29549
[email protected]78e5e432013-08-03 02:10:10550 if (OmniboxFieldTrial::SearchHistoryDisable(
551 input_.current_page_classification()))
[email protected]d8cd76b2013-07-10 09:46:16552 return;
553
[email protected]31afdf72013-09-26 04:29:36554 base::TimeTicks start_time(base::TimeTicks::Now());
[email protected]8d457132010-11-04 18:13:40555 HistoryService* const history_service =
[email protected]9d2db762012-06-19 00:01:10556 HistoryServiceFactory::GetForProfile(profile_, Profile::EXPLICIT_ACCESS);
[email protected]31afdf72013-09-26 04:29:36557 base::TimeTicks now(base::TimeTicks::Now());
558 UMA_HISTOGRAM_TIMES("Omnibox.SearchProvider.GetHistoryServiceTime",
559 now - start_time);
560 start_time = now;
[email protected]8d457132010-11-04 18:13:40561 history::URLDatabase* url_db = history_service ?
562 history_service->InMemoryDatabase() : NULL;
[email protected]31afdf72013-09-26 04:29:36563 UMA_HISTOGRAM_TIMES("Omnibox.SearchProvider.InMemoryDatabaseTime",
564 base::TimeTicks::Now() - start_time);
[email protected]8d457132010-11-04 18:13:40565 if (!url_db)
initial.commit09911bf2008-07-26 23:55:29566 return;
567
[email protected]51124552011-07-16 01:37:10568 // Request history for both the keyword and default provider. We grab many
569 // more matches than we'll ultimately clamp to so that if there are several
570 // recent multi-word matches who scores are lowered (see
571 // AddHistoryResultsToMap()), they won't crowd out older, higher-scoring
572 // matches. Note that this doesn't fix the problem entirely, but merely
573 // limits it to cases with a very large number of such multi-word matches; for
574 // now, this seems OK compared with the complexity of a real fix, which would
575 // require multiple searches and tracking of "single- vs. multi-word" in the
576 // database.
577 int num_matches = kMaxMatches * 5;
[email protected]85b8d6f2012-05-08 20:53:47578 const TemplateURL* default_url = providers_.GetDefaultProviderURL();
579 if (default_url) {
[email protected]31afdf72013-09-26 04:29:36580 start_time = base::TimeTicks::Now();
[email protected]85b8d6f2012-05-08 20:53:47581 url_db->GetMostRecentKeywordSearchTerms(default_url->id(), input_.text(),
582 num_matches, &default_history_results_);
[email protected]31afdf72013-09-26 04:29:36583 UMA_HISTOGRAM_TIMES(
584 "Omnibox.SearchProvider.GetMostRecentKeywordTermsDefaultProviderTime",
585 base::TimeTicks::Now() - start_time);
[email protected]257ab712009-04-14 17:16:24586 }
[email protected]85b8d6f2012-05-08 20:53:47587 const TemplateURL* keyword_url = providers_.GetKeywordProviderURL();
588 if (keyword_url) {
589 url_db->GetMostRecentKeywordSearchTerms(keyword_url->id(),
[email protected]14710852013-02-05 23:45:41590 keyword_input_.text(), num_matches, &keyword_history_results_);
[email protected]3954c3a2012-04-10 20:17:55591 }
[email protected]31afdf72013-09-26 04:29:36592 UMA_HISTOGRAM_TIMES("Omnibox.SearchProvider.DoHistoryQueryTime",
593 base::TimeTicks::Now() - do_history_query_start_time);
initial.commit09911bf2008-07-26 23:55:29594}
595
[email protected]6dc950f2012-07-16 19:49:08596void SearchProvider::StartOrStopSuggestQuery(bool minimal_changes) {
[email protected]83c726482008-09-10 06:36:34597 if (!IsQuerySuitableForSuggest()) {
initial.commit09911bf2008-07-26 23:55:29598 StopSuggest();
[email protected]71b46152013-05-03 16:39:20599 ClearAllResults();
initial.commit09911bf2008-07-26 23:55:29600 return;
601 }
602
603 // For the minimal_changes case, if we finished the previous query and still
604 // have its results, or are allowed to keep running it, just do that, rather
605 // than starting a new query.
606 if (minimal_changes &&
[email protected]cc1526e2013-05-17 04:04:24607 (!default_results_.suggest_results.empty() ||
608 !default_results_.navigation_results.empty() ||
609 !keyword_results_.suggest_results.empty() ||
610 !keyword_results_.navigation_results.empty() ||
[email protected]ea3b9a502011-04-04 14:19:37611 (!done_ &&
612 input_.matches_requested() == AutocompleteInput::ALL_MATCHES)))
initial.commit09911bf2008-07-26 23:55:29613 return;
614
615 // We can't keep running any previous query, so halt it.
616 StopSuggest();
[email protected]d1f0a7f2012-06-05 10:26:42617
618 // Remove existing results that cannot inline autocomplete the new input.
[email protected]71b46152013-05-03 16:39:20619 RemoveAllStaleResults();
initial.commit09911bf2008-07-26 23:55:29620
[email protected]ee6110b2014-01-09 22:26:31621 // Update the content classifications of remaining results so they look good
622 // against the current input.
[email protected]23db6492014-01-16 02:35:30623 UpdateMatchContentsClass(input_.text(), &default_results_);
624 if (!keyword_input_.text().empty())
625 UpdateMatchContentsClass(keyword_input_.text(), &keyword_results_);
[email protected]ee6110b2014-01-09 22:26:31626
initial.commit09911bf2008-07-26 23:55:29627 // We can't start a new query if we're only allowed synchronous results.
[email protected]ea3b9a502011-04-04 14:19:37628 if (input_.matches_requested() != AutocompleteInput::ALL_MATCHES)
initial.commit09911bf2008-07-26 23:55:29629 return;
630
[email protected]24dbf2302013-04-05 16:59:25631 // To avoid flooding the suggest server, don't send a query until at
632 // least 100 ms since the last query.
[email protected]515ffa942012-11-27 20:18:24633 base::TimeTicks next_suggest_time(time_suggest_request_sent_ +
[email protected]bc8bb0cd2013-06-24 21:50:23634 base::TimeDelta::FromMilliseconds(kMinimumTimeBetweenSuggestQueriesMs));
[email protected]515ffa942012-11-27 20:18:24635 base::TimeTicks now(base::TimeTicks::Now());
636 if (now >= next_suggest_time) {
637 Run();
638 return;
639 }
640 timer_.Start(FROM_HERE, next_suggest_time - now, this, &SearchProvider::Run);
initial.commit09911bf2008-07-26 23:55:29641}
642
[email protected]83c726482008-09-10 06:36:34643bool SearchProvider::IsQuerySuitableForSuggest() const {
[email protected]3954c3a2012-04-10 20:17:55644 // Don't run Suggest in incognito mode, if the engine doesn't support it, or
645 // if the user has disabled it.
[email protected]85b8d6f2012-05-08 20:53:47646 const TemplateURL* default_url = providers_.GetDefaultProviderURL();
647 const TemplateURL* keyword_url = providers_.GetKeywordProviderURL();
[email protected]83c726482008-09-10 06:36:34648 if (profile_->IsOffTheRecord() ||
[email protected]85b8d6f2012-05-08 20:53:47649 ((!default_url || default_url->suggestions_url().empty()) &&
650 (!keyword_url || keyword_url->suggestions_url().empty())) ||
[email protected]83c726482008-09-10 06:36:34651 !profile_->GetPrefs()->GetBoolean(prefs::kSearchSuggestEnabled))
652 return false;
653
[email protected]cac59d32010-08-09 23:23:14654 // If the input type might be a URL, we take extra care so that private data
[email protected]83c726482008-09-10 06:36:34655 // isn't sent to the server.
[email protected]83c726482008-09-10 06:36:34656
[email protected]cac59d32010-08-09 23:23:14657 // FORCED_QUERY means the user is explicitly asking us to search for this, so
658 // we assume it isn't a URL and/or there isn't private data.
659 if (input_.type() == AutocompleteInput::FORCED_QUERY)
660 return true;
[email protected]83c726482008-09-10 06:36:34661
[email protected]f608ea102013-03-18 15:08:09662 // Next we check the scheme. If this is UNKNOWN/URL with a scheme that isn't
663 // http/https/ftp, we shouldn't send it. Sending things like file: and data:
664 // is both a waste of time and a disclosure of potentially private, local
665 // data. Other "schemes" may actually be usernames, and we don't want to send
666 // passwords. If the scheme is OK, we still need to check other cases below.
667 // If this is QUERY, then the presence of these schemes means the user
668 // explicitly typed one, and thus this is probably a URL that's being entered
669 // and happens to currently be invalid -- in which case we again want to run
670 // our checks below. Other QUERY cases are less likely to be URLs and thus we
671 // assume we're OK.
[email protected]e9a82042013-09-15 03:38:29672 if (!LowerCaseEqualsASCII(input_.scheme(), content::kHttpScheme) &&
[email protected]4654bfe2013-08-26 03:36:58673 !LowerCaseEqualsASCII(input_.scheme(), content::kHttpsScheme) &&
[email protected]72aa4c22013-12-01 15:09:35674 !LowerCaseEqualsASCII(input_.scheme(), content::kFtpScheme))
[email protected]cac59d32010-08-09 23:23:14675 return (input_.type() == AutocompleteInput::QUERY);
676
677 // Don't send URLs with usernames, queries or refs. Some of these are
678 // private, and the Suggest server is unlikely to have any useful results
679 // for any of them. Also don't send URLs with ports, as we may initially
680 // think that a username + password is a host + port (and we don't want to
681 // send usernames/passwords), and even if the port really is a port, the
682 // server is once again unlikely to have and useful results.
[email protected]825e16f2013-09-30 23:52:58683 // Note that we only block based on refs if the input is URL-typed, as search
684 // queries can legitimately have #s in them which the URL parser
685 // overaggressively categorizes as a url with a ref.
[email protected]cac59d32010-08-09 23:23:14686 const url_parse::Parsed& parts = input_.parts();
687 if (parts.username.is_nonempty() || parts.port.is_nonempty() ||
[email protected]825e16f2013-09-30 23:52:58688 parts.query.is_nonempty() ||
689 (parts.ref.is_nonempty() && (input_.type() == AutocompleteInput::URL)))
[email protected]cac59d32010-08-09 23:23:14690 return false;
691
692 // Don't send anything for https except the hostname. Hostnames are OK
693 // because they are visible when the TCP connection is established, but the
694 // specific path may reveal private information.
[email protected]4654bfe2013-08-26 03:36:58695 if (LowerCaseEqualsASCII(input_.scheme(), content::kHttpsScheme) &&
[email protected]a2fedb1e2011-01-25 15:23:36696 parts.path.is_nonempty())
[email protected]cac59d32010-08-09 23:23:14697 return false;
[email protected]83c726482008-09-10 06:36:34698
699 return true;
700}
701
[email protected]71b46152013-05-03 16:39:20702void SearchProvider::RemoveAllStaleResults() {
[email protected]dc735c02013-11-12 23:23:41703 // We only need to remove stale results (which ensures the top-scoring
704 // match is inlineable) if the user is not in reorder mode. In reorder
705 // mode, the autocomplete system will reorder results to make sure the
706 // top result is inlineable.
707 const bool omnibox_will_reorder_for_legal_default_match =
708 OmniboxFieldTrial::ReorderForLegalDefaultMatch(
709 input_.current_page_classification());
[email protected]1e1550e2013-05-02 17:37:51710 // In theory it would be better to run an algorithm like that in
711 // RemoveStaleResults(...) below that uses all four results lists
712 // and both verbatim scores at once. However, that will be much
713 // more complicated for little obvious gain. For code simplicity
714 // and ease in reasoning about the invariants involved, this code
715 // removes stales results from the keyword provider and default
716 // provider independently.
[email protected]dc735c02013-11-12 23:23:41717 if (!omnibox_will_reorder_for_legal_default_match) {
718 RemoveStaleResults(input_.text(), GetVerbatimRelevance(NULL),
719 &default_results_.suggest_results,
720 &default_results_.navigation_results);
721 if (!keyword_input_.text().empty()) {
722 RemoveStaleResults(keyword_input_.text(),
723 GetKeywordVerbatimRelevance(NULL),
724 &keyword_results_.suggest_results,
725 &keyword_results_.navigation_results);
726 }
727 }
728 if (keyword_input_.text().empty()) {
[email protected]1e1550e2013-05-02 17:37:51729 // User is either in keyword mode with a blank input or out of
730 // keyword mode entirely.
[email protected]cc1526e2013-05-17 04:04:24731 keyword_results_.Clear();
[email protected]1e1550e2013-05-02 17:37:51732 }
[email protected]d1f0a7f2012-06-05 10:26:42733}
734
[email protected]d1f0a7f2012-06-05 10:26:42735void SearchProvider::ApplyCalculatedRelevance() {
[email protected]cc1526e2013-05-17 04:04:24736 ApplyCalculatedSuggestRelevance(&keyword_results_.suggest_results);
737 ApplyCalculatedSuggestRelevance(&default_results_.suggest_results);
738 ApplyCalculatedNavigationRelevance(&keyword_results_.navigation_results);
739 ApplyCalculatedNavigationRelevance(&default_results_.navigation_results);
[email protected]cc1526e2013-05-17 04:04:24740 default_results_.verbatim_relevance = -1;
741 keyword_results_.verbatim_relevance = -1;
[email protected]d1f0a7f2012-06-05 10:26:42742}
743
[email protected]188b50c2013-03-28 07:19:42744void SearchProvider::ApplyCalculatedSuggestRelevance(SuggestResults* list) {
[email protected]d1f0a7f2012-06-05 10:26:42745 for (size_t i = 0; i < list->size(); ++i) {
[email protected]188b50c2013-03-28 07:19:42746 SuggestResult& result = (*list)[i];
747 result.set_relevance(
748 result.CalculateRelevance(input_, providers_.has_keyword_provider()) +
749 (list->size() - i - 1));
[email protected]d30268a2013-06-25 22:31:07750 result.set_relevance_from_server(false);
[email protected]d1f0a7f2012-06-05 10:26:42751 }
752}
753
[email protected]188b50c2013-03-28 07:19:42754void SearchProvider::ApplyCalculatedNavigationRelevance(
755 NavigationResults* list) {
[email protected]d1f0a7f2012-06-05 10:26:42756 for (size_t i = 0; i < list->size(); ++i) {
[email protected]188b50c2013-03-28 07:19:42757 NavigationResult& result = (*list)[i];
758 result.set_relevance(
759 result.CalculateRelevance(input_, providers_.has_keyword_provider()) +
760 (list->size() - i - 1));
[email protected]d30268a2013-06-25 22:31:07761 result.set_relevance_from_server(false);
[email protected]d1f0a7f2012-06-05 10:26:42762 }
763}
764
[email protected]15fb2aa2012-05-22 22:52:59765net::URLFetcher* SearchProvider::CreateSuggestFetcher(
[email protected]7cc6e5632011-10-25 17:56:12766 int id,
[email protected]9ff91722012-09-07 05:29:12767 const TemplateURL* template_url,
[email protected]14710852013-02-05 23:45:41768 const AutocompleteInput& input) {
[email protected]9ff91722012-09-07 05:29:12769 if (!template_url || template_url->suggestions_url().empty())
770 return NULL;
771
772 // Bail if the suggestion URL is invalid with the given replacements.
[email protected]14710852013-02-05 23:45:41773 TemplateURLRef::SearchTermsArgs search_term_args(input.text());
774 search_term_args.cursor_position = input.cursor_position();
[email protected]d5015ca2013-08-08 22:04:18775 search_term_args.page_classification = input.current_page_classification();
[email protected]9ff91722012-09-07 05:29:12776 GURL suggest_url(template_url->suggestions_url_ref().ReplaceSearchTerms(
[email protected]00790562012-12-14 09:57:16777 search_term_args));
[email protected]9ff91722012-09-07 05:29:12778 if (!suggest_url.is_valid())
779 return NULL;
[email protected]9b9fa672013-11-07 06:04:52780 // Send the current page URL if user setting and URL requirements are met and
781 // the user is in the field trial.
782 if (CanSendURL(current_page_url_, suggest_url, template_url,
783 input.current_page_classification(), profile_) &&
784 OmniboxFieldTrial::InZeroSuggestAfterTypingFieldTrial()) {
785 search_term_args.current_page_url = current_page_url_.spec();
786 // Create the suggest URL again with the current page URL.
787 suggest_url = GURL(template_url->suggestions_url_ref().ReplaceSearchTerms(
788 search_term_args));
789 }
[email protected]9ff91722012-09-07 05:29:12790
791 suggest_results_pending_++;
792 LogOmniboxSuggestRequest(REQUEST_SENT);
793
794 net::URLFetcher* fetcher =
795 net::URLFetcher::Create(id, suggest_url, net::URLFetcher::GET, this);
[email protected]7cc6e5632011-10-25 17:56:12796 fetcher->SetRequestContext(profile_->GetRequestContext());
[email protected]d3cf8682f02012-02-29 23:29:34797 fetcher->SetLoadFlags(net::LOAD_DO_NOT_SAVE_COOKIES);
[email protected]bd3b4712012-12-18 17:01:30798 // Add Chrome experiment state to the request headers.
799 net::HttpRequestHeaders headers;
[email protected]ab7780792013-01-10 01:26:09800 chrome_variations::VariationsHttpHeaderProvider::GetInstance()->AppendHeaders(
[email protected]bd3b4712012-12-18 17:01:30801 fetcher->GetOriginalURL(), profile_->IsOffTheRecord(), false, &headers);
802 fetcher->SetExtraRequestHeaders(headers.ToString());
[email protected]257ab712009-04-14 17:16:24803 fetcher->Start();
804 return fetcher;
805}
806
[email protected]344946a12012-12-20 12:03:42807void SearchProvider::ConvertResultsToAutocompleteMatches() {
initial.commit09911bf2008-07-26 23:55:29808 // Convert all the results to matches and add them to a map, so we can keep
809 // the most relevant match for each result.
[email protected]31afdf72013-09-26 04:29:36810 base::TimeTicks start_time(base::TimeTicks::Now());
initial.commit09911bf2008-07-26 23:55:29811 MatchMap map;
[email protected]bc8bb0cd2013-06-24 21:50:23812 const base::Time no_time;
[email protected]cc1526e2013-05-17 04:04:24813 int did_not_accept_keyword_suggestion =
814 keyword_results_.suggest_results.empty() ?
initial.commit09911bf2008-07-26 23:55:29815 TemplateURLRef::NO_SUGGESTIONS_AVAILABLE :
816 TemplateURLRef::NO_SUGGESTION_CHOSEN;
initial.commit09911bf2008-07-26 23:55:29817
[email protected]d30268a2013-06-25 22:31:07818 bool relevance_from_server;
819 int verbatim_relevance = GetVerbatimRelevance(&relevance_from_server);
[email protected]cc1526e2013-05-17 04:04:24820 int did_not_accept_default_suggestion =
821 default_results_.suggest_results.empty() ?
[email protected]55ce8f12012-05-09 04:44:08822 TemplateURLRef::NO_SUGGESTIONS_AVAILABLE :
823 TemplateURLRef::NO_SUGGESTION_CHOSEN;
[email protected]d1f0a7f2012-06-05 10:26:42824 if (verbatim_relevance > 0) {
[email protected]2c03c06b2013-12-11 20:45:02825 SuggestResult verbatim(
826 input_.text(), AutocompleteMatchType::SEARCH_WHAT_YOU_TYPED,
[email protected]61f99082014-02-24 02:17:49827 input_.text(), base::string16(), base::string16(), std::string(),
828 std::string(), false, verbatim_relevance, relevance_from_server, false,
829 input_.text());
[email protected]57482a72014-03-14 22:27:37830 AddMatchToMap(verbatim, std::string(), did_not_accept_default_suggestion,
831 false, &map);
[email protected]d1f0a7f2012-06-05 10:26:42832 }
[email protected]5423e562013-02-07 03:58:45833 if (!keyword_input_.text().empty()) {
834 const TemplateURL* keyword_url = providers_.GetKeywordProviderURL();
835 // We only create the verbatim search query match for a keyword
836 // if it's not an extension keyword. Extension keywords are handled
837 // in KeywordProvider::Start(). (Extensions are complicated...)
838 // Note: in this provider, SEARCH_OTHER_ENGINE must correspond
839 // to the keyword verbatim search query. Do not create other matches
840 // of type SEARCH_OTHER_ENGINE.
[email protected]bdcbcd82013-10-28 13:40:25841 if (keyword_url &&
842 (keyword_url->GetType() != TemplateURL::OMNIBOX_API_EXTENSION)) {
[email protected]d30268a2013-06-25 22:31:07843 bool keyword_relevance_from_server;
844 const int keyword_verbatim_relevance =
845 GetKeywordVerbatimRelevance(&keyword_relevance_from_server);
[email protected]dab8d52d2013-03-05 07:35:28846 if (keyword_verbatim_relevance > 0) {
[email protected]2c03c06b2013-12-11 20:45:02847 SuggestResult verbatim(
848 keyword_input_.text(), AutocompleteMatchType::SEARCH_OTHER_ENGINE,
[email protected]61f99082014-02-24 02:17:49849 keyword_input_.text(), base::string16(), base::string16(),
850 std::string(), std::string(), true, keyword_verbatim_relevance,
[email protected]ee6110b2014-01-09 22:26:31851 keyword_relevance_from_server, false, keyword_input_.text());
[email protected]57482a72014-03-14 22:27:37852 AddMatchToMap(verbatim, std::string(),
853 did_not_accept_keyword_suggestion, false, &map);
[email protected]dab8d52d2013-03-05 07:35:28854 }
[email protected]5423e562013-02-07 03:58:45855 }
856 }
[email protected]257ab712009-04-14 17:16:24857 AddHistoryResultsToMap(keyword_history_results_, true,
858 did_not_accept_keyword_suggestion, &map);
859 AddHistoryResultsToMap(default_history_results_, false,
860 did_not_accept_default_suggestion, &map);
861
[email protected]d1cb6a822013-09-18 19:43:00862 AddSuggestResultsToMap(keyword_results_.suggest_results,
863 keyword_results_.metadata, &map);
[email protected]987fad782013-08-28 06:23:18864 AddSuggestResultsToMap(default_results_.suggest_results,
865 default_results_.metadata, &map);
initial.commit09911bf2008-07-26 23:55:29866
[email protected]d30268a2013-06-25 22:31:07867 ACMatches matches;
initial.commit09911bf2008-07-26 23:55:29868 for (MatchMap::const_iterator i(map.begin()); i != map.end(); ++i)
[email protected]d30268a2013-06-25 22:31:07869 matches.push_back(i->second);
initial.commit09911bf2008-07-26 23:55:29870
[email protected]d30268a2013-06-25 22:31:07871 AddNavigationResultsToMatches(keyword_results_.navigation_results, &matches);
872 AddNavigationResultsToMatches(default_results_.navigation_results, &matches);
initial.commit09911bf2008-07-26 23:55:29873
[email protected]d30268a2013-06-25 22:31:07874 // Now add the most relevant matches to |matches_|. We take up to kMaxMatches
875 // suggest/navsuggest matches, regardless of origin. If Instant Extended is
876 // enabled and we have server-provided (and thus hopefully more accurate)
877 // scores for some suggestions, we allow more of those, until we reach
878 // AutocompleteResult::kMaxMatches total matches (that is, enough to fill the
879 // whole popup).
880 //
881 // We will always return any verbatim matches, no matter how we obtained their
882 // scores, unless we have already accepted AutocompleteResult::kMaxMatches
883 // higher-scoring matches under the conditions above.
[email protected]31afdf72013-09-26 04:29:36884 UMA_HISTOGRAM_CUSTOM_COUNTS(
885 "Omnibox.SearchProvider.NumMatchesToSort", matches.size(), 1, 50, 20);
[email protected]d30268a2013-06-25 22:31:07886 std::sort(matches.begin(), matches.end(), &AutocompleteMatch::MoreRelevant);
887 matches_.clear();
[email protected]3723e6e2012-06-11 21:06:56888
[email protected]d30268a2013-06-25 22:31:07889 size_t num_suggestions = 0;
890 for (ACMatches::const_iterator i(matches.begin());
891 (i != matches.end()) &&
892 (matches_.size() < AutocompleteResult::kMaxMatches);
893 ++i) {
894 // SEARCH_OTHER_ENGINE is only used in the SearchProvider for the keyword
895 // verbatim result, so this condition basically means "if this match is a
896 // suggestion of some sort".
897 if ((i->type != AutocompleteMatchType::SEARCH_WHAT_YOU_TYPED) &&
898 (i->type != AutocompleteMatchType::SEARCH_OTHER_ENGINE)) {
899 // If we've already hit the limit on non-server-scored suggestions, and
900 // this isn't a server-scored suggestion we can add, skip it.
901 if ((num_suggestions >= kMaxMatches) &&
902 (!chrome::IsInstantExtendedAPIEnabled() ||
903 (i->GetAdditionalInfo(kRelevanceFromServerKey) != kTrue))) {
904 continue;
905 }
906
907 ++num_suggestions;
908 }
909
910 matches_.push_back(*i);
911 }
[email protected]31afdf72013-09-26 04:29:36912 UMA_HISTOGRAM_TIMES("Omnibox.SearchProvider.ConvertResultsTime",
913 base::TimeTicks::Now() - start_time);
[email protected]344946a12012-12-20 12:03:42914}
915
[email protected]0a8718b12013-11-13 18:41:31916ACMatches::const_iterator SearchProvider::FindTopMatch(
917 bool autocomplete_result_will_reorder_for_default_match) const {
918 if (!autocomplete_result_will_reorder_for_default_match)
919 return matches_.begin();
920 ACMatches::const_iterator it = matches_.begin();
921 while ((it != matches_.end()) && !it->allowed_to_be_default_match)
922 ++it;
923 return it;
[email protected]9dfb4d362013-04-05 02:15:12924}
925
[email protected]0a8718b12013-11-13 18:41:31926bool SearchProvider::IsTopMatchNavigationInKeywordMode(
927 bool autocomplete_result_will_reorder_for_default_match) const {
928 ACMatches::const_iterator first_match =
929 FindTopMatch(autocomplete_result_will_reorder_for_default_match);
930 return !providers_.keyword_provider().empty() &&
931 (first_match != matches_.end()) &&
932 (first_match->type == AutocompleteMatchType::NAVSUGGEST);
933}
934
[email protected]1c1e7842013-11-22 16:28:16935bool SearchProvider::HasKeywordDefaultMatchInKeywordMode() const {
936 const TemplateURL* keyword_url = providers_.GetKeywordProviderURL();
937 // If the user is not in keyword mode, return true to say that this
938 // constraint is not violated.
939 if (keyword_url == NULL)
940 return true;
941 for (ACMatches::const_iterator it = matches_.begin(); it != matches_.end();
942 ++it) {
943 if ((it->keyword == keyword_url->keyword()) &&
944 it->allowed_to_be_default_match)
945 return true;
946 }
947 return false;
948}
949
[email protected]0a8718b12013-11-13 18:41:31950bool SearchProvider::IsTopMatchScoreTooLow(
951 bool autocomplete_result_will_reorder_for_default_match) const {
952 // In reorder mode, there's no such thing as a score that's too low.
953 if (autocomplete_result_will_reorder_for_default_match)
954 return false;
955
[email protected]dab8d52d2013-03-05 07:35:28956 // Here we use CalculateRelevanceForVerbatimIgnoringKeywordModeState()
957 // rather than CalculateRelevanceForVerbatim() because the latter returns
958 // a very low score (250) if keyword mode is active. This is because
959 // when keyword mode is active the user probably wants the keyword matches,
960 // not matches from the default provider. Hence, we use the version of
961 // the function that ignores whether keyword mode is active. This allows
962 // SearchProvider to maintain its contract with the AutocompleteController
963 // that it will always provide an inlineable match with a reasonable
964 // score.
965 return matches_.front().relevance <
966 CalculateRelevanceForVerbatimIgnoringKeywordModeState();
[email protected]344946a12012-12-20 12:03:42967}
968
[email protected]0a8718b12013-11-13 18:41:31969bool SearchProvider::IsTopMatchSearchWithURLInput(
970 bool autocomplete_result_will_reorder_for_default_match) const {
971 ACMatches::const_iterator first_match =
972 FindTopMatch(autocomplete_result_will_reorder_for_default_match);
973 return (input_.type() == AutocompleteInput::URL) &&
974 (first_match != matches_.end()) &&
975 (first_match->relevance > CalculateRelevanceForVerbatim()) &&
976 (first_match->type != AutocompleteMatchType::NAVSUGGEST);
[email protected]344946a12012-12-20 12:03:42977}
978
[email protected]45f89a92013-08-12 13:41:36979bool SearchProvider::HasValidDefaultMatch(
980 bool autocomplete_result_will_reorder_for_default_match) const {
981 // One of the SearchProvider matches may need to be the overall default. If
982 // AutocompleteResult is allowed to reorder matches, this means we simply
983 // need at least one match in the list to be |allowed_to_be_default_match|.
984 // If no reordering is possible, however, then our first match needs to have
985 // this flag.
986 for (ACMatches::const_iterator it = matches_.begin(); it != matches_.end();
987 ++it) {
988 if (it->allowed_to_be_default_match)
989 return true;
990 if (!autocomplete_result_will_reorder_for_default_match)
991 return false;
992 }
993 return false;
[email protected]344946a12012-12-20 12:03:42994}
995
[email protected]257ab712009-04-14 17:16:24996
997void SearchProvider::AddNavigationResultsToMatches(
[email protected]d30268a2013-06-25 22:31:07998 const NavigationResults& navigation_results,
999 ACMatches* matches) {
[email protected]bc8bb0cd2013-06-24 21:50:231000 for (NavigationResults::const_iterator it = navigation_results.begin();
1001 it != navigation_results.end(); ++it) {
[email protected]d30268a2013-06-25 22:31:071002 matches->push_back(NavigationToMatch(*it));
[email protected]bc8bb0cd2013-06-24 21:50:231003 // In the absence of suggested relevance scores, use only the single
1004 // highest-scoring result. (The results are already sorted by relevance.)
[email protected]d30268a2013-06-25 22:31:071005 if (!it->relevance_from_server())
[email protected]bc8bb0cd2013-06-24 21:50:231006 return;
[email protected]257ab712009-04-14 17:16:241007 }
1008}
1009
1010void SearchProvider::AddHistoryResultsToMap(const HistoryResults& results,
1011 bool is_keyword,
1012 int did_not_accept_suggestion,
1013 MatchMap* map) {
[email protected]51124552011-07-16 01:37:101014 if (results.empty())
1015 return;
1016
[email protected]31afdf72013-09-26 04:29:361017 base::TimeTicks start_time(base::TimeTicks::Now());
[email protected]d7ad4772012-06-01 03:12:541018 bool prevent_inline_autocomplete = input_.prevent_inline_autocomplete() ||
1019 (input_.type() == AutocompleteInput::URL);
[email protected]0085863a2013-12-06 21:19:031020 const base::string16& input_text =
[email protected]14710852013-02-05 23:45:411021 is_keyword ? keyword_input_.text() : input_.text();
[email protected]51124552011-07-16 01:37:101022 bool input_multiple_words = HasMultipleWords(input_text);
1023
[email protected]55ce8f12012-05-09 04:44:081024 SuggestResults scored_results;
1025 if (!prevent_inline_autocomplete && input_multiple_words) {
1026 // ScoreHistoryResults() allows autocompletion of multi-word, 1-visit
1027 // queries if the input also has multiple words. But if we were already
[email protected]51124552011-07-16 01:37:101028 // autocompleting a multi-word, multi-visit query, and the current input is
1029 // still a prefix of it, then changing the autocompletion suddenly feels
1030 // wrong. To detect this case, first score as if only one word has been
1031 // typed, then check for a best result that is an autocompleted, multi-word
1032 // query. If we find one, then just keep that score set.
[email protected]55ce8f12012-05-09 04:44:081033 scored_results = ScoreHistoryResults(results, prevent_inline_autocomplete,
1034 false, input_text, is_keyword);
[email protected]9dfb4d362013-04-05 02:15:121035 if ((scored_results.front().relevance() <
[email protected]55ce8f12012-05-09 04:44:081036 AutocompleteResult::kLowestDefaultScore) ||
[email protected]9dfb4d362013-04-05 02:15:121037 !HasMultipleWords(scored_results.front().suggestion()))
[email protected]55ce8f12012-05-09 04:44:081038 scored_results.clear(); // Didn't detect the case above, score normally.
[email protected]51124552011-07-16 01:37:101039 }
[email protected]55ce8f12012-05-09 04:44:081040 if (scored_results.empty())
1041 scored_results = ScoreHistoryResults(results, prevent_inline_autocomplete,
1042 input_multiple_words, input_text,
1043 is_keyword);
1044 for (SuggestResults::const_iterator i(scored_results.begin());
1045 i != scored_results.end(); ++i) {
[email protected]57482a72014-03-14 22:27:371046 AddMatchToMap(*i, std::string(), did_not_accept_suggestion, true, map);
[email protected]51124552011-07-16 01:37:101047 }
[email protected]31afdf72013-09-26 04:29:361048 UMA_HISTOGRAM_TIMES("Omnibox.SearchProvider.AddHistoryResultsTime",
1049 base::TimeTicks::Now() - start_time);
[email protected]51124552011-07-16 01:37:101050}
1051
[email protected]55ce8f12012-05-09 04:44:081052SearchProvider::SuggestResults SearchProvider::ScoreHistoryResults(
[email protected]51124552011-07-16 01:37:101053 const HistoryResults& results,
1054 bool base_prevent_inline_autocomplete,
1055 bool input_multiple_words,
[email protected]0085863a2013-12-06 21:19:031056 const base::string16& input_text,
[email protected]51124552011-07-16 01:37:101057 bool is_keyword) {
[email protected]810ffba2012-06-12 01:07:481058 AutocompleteClassifier* classifier =
1059 AutocompleteClassifierFactory::GetForProfile(profile_);
[email protected]55ce8f12012-05-09 04:44:081060 SuggestResults scored_results;
[email protected]78e5e432013-08-03 02:10:101061 const bool prevent_search_history_inlining =
1062 OmniboxFieldTrial::SearchHistoryPreventInlining(
1063 input_.current_page_classification());
[email protected]257ab712009-04-14 17:16:241064 for (HistoryResults::const_iterator i(results.begin()); i != results.end();
1065 ++i) {
[email protected]51124552011-07-16 01:37:101066 // Don't autocomplete multi-word queries that have only been seen once
1067 // unless the user has typed more than one word.
1068 bool prevent_inline_autocomplete = base_prevent_inline_autocomplete ||
1069 (!input_multiple_words && (i->visits < 2) && HasMultipleWords(i->term));
1070
[email protected]ea3b9a502011-04-04 14:19:371071 // Don't autocomplete search terms that would normally be treated as URLs
[email protected]51124552011-07-16 01:37:101072 // when typed. For example, if the user searched for "google.com" and types
1073 // "goog", don't autocomplete to the search term "google.com". Otherwise,
1074 // the input will look like a URL but act like a search, which is confusing.
[email protected]cc447362011-04-06 03:57:481075 // NOTE: We don't check this in the following cases:
1076 // * When inline autocomplete is disabled, we won't be inline
1077 // autocompleting this term, so we don't need to worry about confusion as
1078 // much. This also prevents calling Classify() again from inside the
1079 // classifier (which will corrupt state and likely crash), since the
[email protected]51124552011-07-16 01:37:101080 // classifier always disables inline autocomplete.
[email protected]cc447362011-04-06 03:57:481081 // * When the user has typed the whole term, the "what you typed" history
1082 // match will outrank us for URL-like inputs anyway, so we need not do
1083 // anything special.
[email protected]51124552011-07-16 01:37:101084 if (!prevent_inline_autocomplete && classifier && (i->term != input_text)) {
[email protected]ea3b9a502011-04-04 14:19:371085 AutocompleteMatch match;
[email protected]51abb7b2014-02-09 23:00:081086 classifier->Classify(i->term, false, false,
1087 input_.current_page_classification(), &match, NULL);
[email protected]2905f742011-10-13 03:51:581088 prevent_inline_autocomplete =
[email protected]749e7ae02012-09-05 18:47:461089 !AutocompleteMatch::IsSearchType(match.type);
[email protected]ea3b9a502011-04-04 14:19:371090 }
[email protected]51124552011-07-16 01:37:101091
[email protected]78e5e432013-08-03 02:10:101092 int relevance = CalculateRelevanceForHistory(
1093 i->time, is_keyword, !prevent_inline_autocomplete,
1094 prevent_search_history_inlining);
[email protected]2c03c06b2013-12-11 20:45:021095 scored_results.push_back(SuggestResult(
1096 i->term, AutocompleteMatchType::SEARCH_HISTORY, i->term,
[email protected]61f99082014-02-24 02:17:491097 base::string16(), base::string16(), std::string(), std::string(),
1098 is_keyword, relevance, false, false, input_text));
[email protected]257ab712009-04-14 17:16:241099 }
[email protected]51124552011-07-16 01:37:101100
1101 // History returns results sorted for us. However, we may have docked some
1102 // results' scores, so things are no longer in order. Do a stable sort to get
1103 // things back in order without otherwise disturbing results with equal
1104 // scores, then force the scores to be unique, so that the order in which
1105 // they're shown is deterministic.
[email protected]55ce8f12012-05-09 04:44:081106 std::stable_sort(scored_results.begin(), scored_results.end(),
1107 CompareScoredResults());
[email protected]51124552011-07-16 01:37:101108 int last_relevance = 0;
[email protected]55ce8f12012-05-09 04:44:081109 for (SuggestResults::iterator i(scored_results.begin());
1110 i != scored_results.end(); ++i) {
1111 if ((i != scored_results.begin()) && (i->relevance() >= last_relevance))
1112 i->set_relevance(last_relevance - 1);
1113 last_relevance = i->relevance();
[email protected]51124552011-07-16 01:37:101114 }
1115
[email protected]55ce8f12012-05-09 04:44:081116 return scored_results;
[email protected]257ab712009-04-14 17:16:241117}
1118
[email protected]55ce8f12012-05-09 04:44:081119void SearchProvider::AddSuggestResultsToMap(const SuggestResults& results,
[email protected]987fad782013-08-28 06:23:181120 const std::string& metadata,
[email protected]55ce8f12012-05-09 04:44:081121 MatchMap* map) {
[email protected]9487b392014-02-14 02:48:181122 for (size_t i = 0; i < results.size(); ++i)
[email protected]57482a72014-03-14 22:27:371123 AddMatchToMap(results[i], metadata, i, false, map);
initial.commit09911bf2008-07-26 23:55:291124}
1125
[email protected]d30268a2013-06-25 22:31:071126int SearchProvider::GetVerbatimRelevance(bool* relevance_from_server) const {
[email protected]dc6943b2012-06-19 06:39:561127 // Use the suggested verbatim relevance score if it is non-negative (valid),
1128 // if inline autocomplete isn't prevented (always show verbatim on backspace),
[email protected]1beee342012-06-19 22:22:281129 // and if it won't suppress verbatim, leaving no default provider matches.
1130 // Otherwise, if the default provider returned no matches and was still able
[email protected]dc6943b2012-06-19 06:39:561131 // to suppress verbatim, the user would have no search/nav matches and may be
[email protected]1beee342012-06-19 22:22:281132 // left unable to search using their default provider from the omnibox.
[email protected]dc6943b2012-06-19 06:39:561133 // Check for results on each verbatim calculation, as results from older
1134 // queries (on previous input) may be trimmed for failing to inline new input.
[email protected]bc8bb0cd2013-06-24 21:50:231135 bool use_server_relevance =
1136 (default_results_.verbatim_relevance >= 0) &&
[email protected]dab8d52d2013-03-05 07:35:281137 !input_.prevent_inline_autocomplete() &&
[email protected]bc8bb0cd2013-06-24 21:50:231138 ((default_results_.verbatim_relevance > 0) ||
[email protected]cc1526e2013-05-17 04:04:241139 !default_results_.suggest_results.empty() ||
[email protected]bc8bb0cd2013-06-24 21:50:231140 !default_results_.navigation_results.empty());
[email protected]d30268a2013-06-25 22:31:071141 if (relevance_from_server)
1142 *relevance_from_server = use_server_relevance;
[email protected]bc8bb0cd2013-06-24 21:50:231143 return use_server_relevance ?
1144 default_results_.verbatim_relevance : CalculateRelevanceForVerbatim();
[email protected]382a0642012-06-06 06:13:521145}
[email protected]d1f0a7f2012-06-05 10:26:421146
[email protected]382a0642012-06-06 06:13:521147int SearchProvider::CalculateRelevanceForVerbatim() const {
[email protected]85b8d6f2012-05-08 20:53:471148 if (!providers_.keyword_provider().empty())
[email protected]52d08b12009-10-19 18:42:361149 return 250;
[email protected]dab8d52d2013-03-05 07:35:281150 return CalculateRelevanceForVerbatimIgnoringKeywordModeState();
1151}
[email protected]52d08b12009-10-19 18:42:361152
[email protected]dab8d52d2013-03-05 07:35:281153int SearchProvider::
1154 CalculateRelevanceForVerbatimIgnoringKeywordModeState() const {
initial.commit09911bf2008-07-26 23:55:291155 switch (input_.type()) {
1156 case AutocompleteInput::UNKNOWN:
[email protected]52d08b12009-10-19 18:42:361157 case AutocompleteInput::QUERY:
1158 case AutocompleteInput::FORCED_QUERY:
[email protected]90fe2bb2013-01-15 03:42:131159 return kNonURLVerbatimRelevance;
initial.commit09911bf2008-07-26 23:55:291160
initial.commit09911bf2008-07-26 23:55:291161 case AutocompleteInput::URL:
[email protected]52d08b12009-10-19 18:42:361162 return 850;
initial.commit09911bf2008-07-26 23:55:291163
1164 default:
1165 NOTREACHED();
1166 return 0;
1167 }
1168}
1169
[email protected]d30268a2013-06-25 22:31:071170int SearchProvider::GetKeywordVerbatimRelevance(
1171 bool* relevance_from_server) const {
[email protected]dab8d52d2013-03-05 07:35:281172 // Use the suggested verbatim relevance score if it is non-negative (valid),
1173 // if inline autocomplete isn't prevented (always show verbatim on backspace),
1174 // and if it won't suppress verbatim, leaving no keyword provider matches.
1175 // Otherwise, if the keyword provider returned no matches and was still able
1176 // to suppress verbatim, the user would have no search/nav matches and may be
1177 // left unable to search using their keyword provider from the omnibox.
1178 // Check for results on each verbatim calculation, as results from older
1179 // queries (on previous input) may be trimmed for failing to inline new input.
[email protected]bc8bb0cd2013-06-24 21:50:231180 bool use_server_relevance =
1181 (keyword_results_.verbatim_relevance >= 0) &&
[email protected]dab8d52d2013-03-05 07:35:281182 !input_.prevent_inline_autocomplete() &&
[email protected]bc8bb0cd2013-06-24 21:50:231183 ((keyword_results_.verbatim_relevance > 0) ||
[email protected]cc1526e2013-05-17 04:04:241184 !keyword_results_.suggest_results.empty() ||
[email protected]bc8bb0cd2013-06-24 21:50:231185 !keyword_results_.navigation_results.empty());
[email protected]d30268a2013-06-25 22:31:071186 if (relevance_from_server)
1187 *relevance_from_server = use_server_relevance;
[email protected]bc8bb0cd2013-06-24 21:50:231188 return use_server_relevance ?
1189 keyword_results_.verbatim_relevance :
1190 CalculateRelevanceForKeywordVerbatim(keyword_input_.type(),
1191 keyword_input_.prefer_keyword());
[email protected]5423e562013-02-07 03:58:451192}
1193
[email protected]51124552011-07-16 01:37:101194int SearchProvider::CalculateRelevanceForHistory(
[email protected]bc8bb0cd2013-06-24 21:50:231195 const base::Time& time,
[email protected]51124552011-07-16 01:37:101196 bool is_keyword,
[email protected]78e5e432013-08-03 02:10:101197 bool use_aggressive_method,
1198 bool prevent_search_history_inlining) const {
[email protected]aa613d62010-11-09 20:40:181199 // The relevance of past searches falls off over time. There are two distinct
1200 // equations used. If the first equation is used (searches to the primary
[email protected]78e5e432013-08-03 02:10:101201 // provider that we want to score aggressively), the score is in the range
1202 // 1300-1599 (unless |prevent_search_history_inlining|, in which case
[email protected]d8cd76b2013-07-10 09:46:161203 // it's in the range 1200-1299). If the second equation is used the
1204 // relevance of a search 15 minutes ago is discounted 50 points, while the
1205 // relevance of a search two weeks ago is discounted 450 points.
[email protected]bc8bb0cd2013-06-24 21:50:231206 double elapsed_time = std::max((base::Time::Now() - time).InSecondsF(), 0.0);
[email protected]188b50c2013-03-28 07:19:421207 bool is_primary_provider = is_keyword || !providers_.has_keyword_provider();
[email protected]78e5e432013-08-03 02:10:101208 if (is_primary_provider && use_aggressive_method) {
[email protected]aa613d62010-11-09 20:40:181209 // Searches with the past two days get a different curve.
[email protected]51124552011-07-16 01:37:101210 const double autocomplete_time = 2 * 24 * 60 * 60;
[email protected]aa613d62010-11-09 20:40:181211 if (elapsed_time < autocomplete_time) {
[email protected]d8cd76b2013-07-10 09:46:161212 int max_score = is_keyword ? 1599 : 1399;
[email protected]78e5e432013-08-03 02:10:101213 if (prevent_search_history_inlining)
[email protected]d8cd76b2013-07-10 09:46:161214 max_score = 1299;
1215 return max_score - static_cast<int>(99 *
[email protected]aa613d62010-11-09 20:40:181216 std::pow(elapsed_time / autocomplete_time, 2.5));
1217 }
1218 elapsed_time -= autocomplete_time;
1219 }
1220
[email protected]c3a4bd992010-08-18 20:25:011221 const int score_discount =
1222 static_cast<int>(6.5 * std::pow(elapsed_time, 0.3));
initial.commit09911bf2008-07-26 23:55:291223
[email protected]6c85aa02009-02-27 12:08:091224 // Don't let scores go below 0. Negative relevance scores are meaningful in
1225 // a different way.
initial.commit09911bf2008-07-26 23:55:291226 int base_score;
[email protected]51124552011-07-16 01:37:101227 if (is_primary_provider)
[email protected]52d08b12009-10-19 18:42:361228 base_score = (input_.type() == AutocompleteInput::URL) ? 750 : 1050;
[email protected]51124552011-07-16 01:37:101229 else
1230 base_score = 200;
initial.commit09911bf2008-07-26 23:55:291231 return std::max(0, base_score - score_discount);
1232}
1233
initial.commit09911bf2008-07-26 23:55:291234AutocompleteMatch SearchProvider::NavigationToMatch(
[email protected]188b50c2013-03-28 07:19:421235 const NavigationResult& navigation) {
[email protected]5889bfb2014-03-19 00:26:481236 base::string16 input;
1237 const bool trimmed_whitespace = base::TrimWhitespace(
1238 navigation.from_keyword_provider() ?
1239 keyword_input_.text() : input_.text(),
1240 base::TRIM_TRAILING, &input) != base::TRIM_NONE;
[email protected]55ce8f12012-05-09 04:44:081241 AutocompleteMatch match(this, navigation.relevance(), false,
[email protected]b7f64d742013-05-21 04:04:041242 AutocompleteMatchType::NAVSUGGEST);
[email protected]55ce8f12012-05-09 04:44:081243 match.destination_url = navigation.url();
[email protected]371dab12012-06-01 03:23:551244
[email protected]23db6492014-01-16 02:35:301245 // First look for the user's input inside the formatted url as it would be
[email protected]371dab12012-06-01 03:23:551246 // without trimming the scheme, so we can find matches at the beginning of the
1247 // scheme.
[email protected]371dab12012-06-01 03:23:551248 const URLPrefix* prefix =
[email protected]23db6492014-01-16 02:35:301249 URLPrefix::BestURLPrefix(navigation.formatted_url(), input);
[email protected]371dab12012-06-01 03:23:551250 size_t match_start = (prefix == NULL) ?
[email protected]23db6492014-01-16 02:35:301251 navigation.formatted_url().find(input) : prefix->prefix.length();
[email protected]d2445c82013-11-04 22:28:351252 bool trim_http = !AutocompleteInput::HasHTTPScheme(input) &&
1253 (!prefix || (match_start != 0));
[email protected]23db6492014-01-16 02:35:301254 const net::FormatUrlTypes format_types =
1255 net::kFormatUrlOmitAll & ~(trim_http ? 0 : net::kFormatUrlOmitHTTP);
[email protected]371dab12012-06-01 03:23:551256
[email protected]371dab12012-06-01 03:23:551257 const std::string languages(
1258 profile_->GetPrefs()->GetString(prefs::kAcceptLanguages));
[email protected]23db6492014-01-16 02:35:301259 size_t inline_autocomplete_offset = (prefix == NULL) ?
1260 base::string16::npos : (match_start + input.length());
[email protected]371dab12012-06-01 03:23:551261 match.fill_into_edit +=
1262 AutocompleteInput::FormattedStringWithEquivalentMeaning(navigation.url(),
1263 net::FormatUrl(navigation.url(), languages, format_types,
1264 net::UnescapeRule::SPACES, NULL, NULL,
1265 &inline_autocomplete_offset));
[email protected]14119032013-11-07 08:14:261266 // Preserve the forced query '?' prefix in |match.fill_into_edit|.
1267 // Otherwise, user edits to a suggestion would show non-Search results.
1268 if (input_.type() == AutocompleteInput::FORCED_QUERY) {
[email protected]670d3232013-12-24 17:58:581269 match.fill_into_edit.insert(0, base::ASCIIToUTF16("?"));
[email protected]0085863a2013-12-06 21:19:031270 if (inline_autocomplete_offset != base::string16::npos)
[email protected]14119032013-11-07 08:14:261271 ++inline_autocomplete_offset;
1272 }
[email protected]6c94a1022014-02-21 03:48:041273 if (inline_autocomplete_offset != base::string16::npos) {
[email protected]518024c2013-07-19 23:40:251274 DCHECK(inline_autocomplete_offset <= match.fill_into_edit.length());
1275 match.inline_autocompletion =
1276 match.fill_into_edit.substr(inline_autocomplete_offset);
1277 }
[email protected]6c94a1022014-02-21 03:48:041278 // An inlineable navsuggestion can only be the default match when there
1279 // is no keyword provider active, lest it appear first and break the user
[email protected]5889bfb2014-03-19 00:26:481280 // out of keyword mode. It can also only be default if either the inline
1281 // autocompletion is empty or we're not preventing inline autocompletion.
1282 // Finally, if we have an inlineable navsuggestion with an inline completion
1283 // that we're not preventing, make sure we didn't trim any whitespace.
1284 // We don't want to claim http://foo.com/bar is inlineable against the
1285 // input "foo.com/b ".
[email protected]6c94a1022014-02-21 03:48:041286 match.allowed_to_be_default_match = navigation.IsInlineable(input) &&
1287 (providers_.GetKeywordProviderURL() == NULL) &&
[email protected]5889bfb2014-03-19 00:26:481288 (match.inline_autocompletion.empty() ||
1289 (!input_.prevent_inline_autocomplete() && !trimmed_whitespace));
[email protected]371dab12012-06-01 03:23:551290
[email protected]23db6492014-01-16 02:35:301291 match.contents = navigation.match_contents();
1292 match.contents_class = navigation.match_contents_class();
[email protected]55ce8f12012-05-09 04:44:081293 match.description = navigation.description();
[email protected]371dab12012-06-01 03:23:551294 AutocompleteMatch::ClassifyMatchInString(input, match.description,
1295 ACMatchClassification::NONE, &match.description_class);
[email protected]d30268a2013-06-25 22:31:071296
1297 match.RecordAdditionalInfo(
1298 kRelevanceFromServerKey,
1299 navigation.relevance_from_server() ? kTrue : kFalse);
[email protected]987fad782013-08-28 06:23:181300 match.RecordAdditionalInfo(kShouldPrefetchKey, kFalse);
[email protected]d30268a2013-06-25 22:31:071301
initial.commit09911bf2008-07-26 23:55:291302 return match;
1303}
[email protected]4ab4c7c2010-11-24 04:49:341304
[email protected]9dfb4d362013-04-05 02:15:121305void SearchProvider::DemoteKeywordNavigationMatchesPastTopQuery() {
[email protected]d519d392013-03-27 09:24:461306 // First, determine the maximum score of any keyword query match (verbatim or
1307 // query suggestion).
[email protected]d30268a2013-06-25 22:31:071308 bool relevance_from_server;
1309 int max_query_relevance = GetKeywordVerbatimRelevance(&relevance_from_server);
[email protected]cc1526e2013-05-17 04:04:241310 if (!keyword_results_.suggest_results.empty()) {
[email protected]d30268a2013-06-25 22:31:071311 const SuggestResult& top_keyword = keyword_results_.suggest_results.front();
1312 const int suggest_relevance = top_keyword.relevance();
1313 if (suggest_relevance > max_query_relevance) {
1314 max_query_relevance = suggest_relevance;
1315 relevance_from_server = top_keyword.relevance_from_server();
1316 } else if (suggest_relevance == max_query_relevance) {
1317 relevance_from_server |= top_keyword.relevance_from_server();
1318 }
[email protected]d519d392013-03-27 09:24:461319 }
1320 // If no query is supposed to appear, then navigational matches cannot
[email protected]9dfb4d362013-04-05 02:15:121321 // be demoted past it. Get rid of suggested relevance scores for
1322 // navsuggestions and introduce the verbatim results again. The keyword
1323 // verbatim match will outscore the navsuggest matches.
1324 if (max_query_relevance == 0) {
[email protected]cc1526e2013-05-17 04:04:241325 ApplyCalculatedNavigationRelevance(&keyword_results_.navigation_results);
1326 ApplyCalculatedNavigationRelevance(&default_results_.navigation_results);
1327 keyword_results_.verbatim_relevance = -1;
1328 default_results_.verbatim_relevance = -1;
[email protected]9dfb4d362013-04-05 02:15:121329 return;
1330 }
[email protected]d519d392013-03-27 09:24:461331 // Now we know we can enforce the minimum score constraint even after
1332 // the navigation matches are demoted. Proceed to demote the navigation
1333 // matches to enforce the query-must-come-first constraint.
[email protected]d519d392013-03-27 09:24:461334 // Cap the relevance score of all results.
[email protected]cc1526e2013-05-17 04:04:241335 for (NavigationResults::iterator it =
1336 keyword_results_.navigation_results.begin();
1337 it != keyword_results_.navigation_results.end(); ++it) {
[email protected]9dfb4d362013-04-05 02:15:121338 if (it->relevance() < max_query_relevance)
1339 return;
1340 max_query_relevance = std::max(max_query_relevance - 1, 0);
1341 it->set_relevance(max_query_relevance);
[email protected]d30268a2013-06-25 22:31:071342 it->set_relevance_from_server(relevance_from_server);
[email protected]d519d392013-03-27 09:24:461343 }
[email protected]d519d392013-03-27 09:24:461344}
1345
[email protected]4ab4c7c2010-11-24 04:49:341346void SearchProvider::UpdateDone() {
[email protected]2cdf1172012-08-26 12:21:331347 // We're done when the timer isn't running, there are no suggest queries
[email protected]5fac3782013-03-06 09:32:311348 // pending, and we're not waiting on Instant.
[email protected]e1290ee62013-06-26 18:31:151349 done_ = !timer_.IsRunning() && (suggest_results_pending_ == 0);
[email protected]4ab4c7c2010-11-24 04:49:341350}