blob: 3d1c8cf3ce9d043eb931ae862be7b7022a70d925 [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() {
[email protected]cfa164bf2014-03-19 11:51:15414 ConvertResultsToAutocompleteMatches();
415
416 // Check constraints that may be violated by suggested relevances.
417 if (!matches_.empty() &&
418 (default_results_.HasServerProvidedScores() ||
419 keyword_results_.HasServerProvidedScores())) {
420 // These blocks attempt to repair undesirable behavior by suggested
421 // relevances with minimal impact, preserving other suggested relevances.
422
423 // True if the omnibox will reorder matches as necessary to make the first
424 // one something that is allowed to be the default match.
425 const bool omnibox_will_reorder_for_legal_default_match =
426 OmniboxFieldTrial::ReorderForLegalDefaultMatch(
427 input_.current_page_classification());
428 if (IsTopMatchNavigationInKeywordMode(
429 omnibox_will_reorder_for_legal_default_match)) {
430 // Correct the suggested relevance scores if the top match is a
431 // navigation in keyword mode, since inlining a navigation match
432 // would break the user out of keyword mode. This will only be
433 // triggered in regular (non-reorder) mode; in reorder mode,
434 // navigation matches are marked as not allowed to be the default
435 // match and hence IsTopMatchNavigation() will always return false.
436 DCHECK(!omnibox_will_reorder_for_legal_default_match);
437 DemoteKeywordNavigationMatchesPastTopQuery();
438 ConvertResultsToAutocompleteMatches();
439 DCHECK(!IsTopMatchNavigationInKeywordMode(
440 omnibox_will_reorder_for_legal_default_match));
441 }
442 if (!HasKeywordDefaultMatchInKeywordMode()) {
443 // In keyword mode, disregard the keyword verbatim suggested relevance
444 // if necessary so there at least one keyword match that's allowed to
445 // be the default match.
446 keyword_results_.verbatim_relevance = -1;
447 ConvertResultsToAutocompleteMatches();
448 }
449 if (IsTopMatchScoreTooLow(omnibox_will_reorder_for_legal_default_match)) {
450 // Disregard the suggested verbatim relevance if the top score is below
451 // the usual verbatim value. For example, a BarProvider may rely on
452 // SearchProvider's verbatim or inlineable matches for input "foo" (all
453 // allowed to be default match) to always outrank its own lowly-ranked
454 // "bar" matches that shouldn't be the default match.
455 default_results_.verbatim_relevance = -1;
456 keyword_results_.verbatim_relevance = -1;
457 ConvertResultsToAutocompleteMatches();
458 }
459 if (IsTopMatchSearchWithURLInput(
460 omnibox_will_reorder_for_legal_default_match)) {
461 // Disregard the suggested search and verbatim relevances if the input
462 // type is URL and the top match is a highly-ranked search suggestion.
463 // For example, prevent a search for "foo.com" from outranking another
464 // provider's navigation for "foo.com" or "foo.com/url_from_history".
465 ApplyCalculatedSuggestRelevance(&keyword_results_.suggest_results);
466 ApplyCalculatedSuggestRelevance(&default_results_.suggest_results);
467 default_results_.verbatim_relevance = -1;
468 keyword_results_.verbatim_relevance = -1;
469 ConvertResultsToAutocompleteMatches();
470 }
471 if (!HasValidDefaultMatch(omnibox_will_reorder_for_legal_default_match)) {
472 // If the omnibox is not going to reorder results to put a legal default
473 // match at the top, then this provider needs to guarantee that its top
474 // scoring result is a legal default match (i.e., it's either a verbatim
475 // match or inlinable). For example, input "foo" should not invoke a
476 // search for "bar", which would happen if the "bar" search match
477 // outranked all other matches. On the other hand, if the omnibox will
478 // reorder matches as necessary to put a legal default match at the top,
479 // all we need to guarantee is that SearchProvider returns a legal
480 // default match. (The omnibox always needs at least one legal default
481 // match, and it relies on SearchProvider to always return one.)
482 ApplyCalculatedRelevance();
483 ConvertResultsToAutocompleteMatches();
484 }
485 DCHECK(!IsTopMatchNavigationInKeywordMode(
486 omnibox_will_reorder_for_legal_default_match));
487 DCHECK(HasKeywordDefaultMatchInKeywordMode());
488 DCHECK(!IsTopMatchScoreTooLow(
489 omnibox_will_reorder_for_legal_default_match));
490 DCHECK(!IsTopMatchSearchWithURLInput(
491 omnibox_will_reorder_for_legal_default_match));
492 DCHECK(HasValidDefaultMatch(omnibox_will_reorder_for_legal_default_match));
493 }
494 UMA_HISTOGRAM_CUSTOM_COUNTS(
495 "Omnibox.SearchProviderMatches", matches_.size(), 1, 6, 7);
496
497 const TemplateURL* keyword_url = providers_.GetKeywordProviderURL();
498 if ((keyword_url != NULL) && HasKeywordDefaultMatchInKeywordMode()) {
499 // If there is a keyword match that is allowed to be the default match,
500 // then prohibit default provider matches from being the default match lest
501 // such matches cause the user to break out of keyword mode.
502 for (ACMatches::iterator it = matches_.begin(); it != matches_.end();
503 ++it) {
504 if (it->keyword != keyword_url->keyword())
505 it->allowed_to_be_default_match = false;
506 }
507 }
508
509 base::TimeTicks update_starred_start_time(base::TimeTicks::Now());
510 UpdateStarredStateOfMatches();
511 UMA_HISTOGRAM_TIMES("Omnibox.SearchProvider.UpdateStarredTime",
512 base::TimeTicks::Now() - update_starred_start_time);
513 UpdateDone();
[email protected]cfa164bf2014-03-19 11:51:15514}
515
[email protected]bc8bb0cd2013-06-24 21:50:23516void SearchProvider::Run() {
517 // Start a new request with the current input.
518 suggest_results_pending_ = 0;
519 time_suggest_request_sent_ = base::TimeTicks::Now();
[email protected]abe441e2013-05-06 12:35:05520
[email protected]bc8bb0cd2013-06-24 21:50:23521 default_fetcher_.reset(CreateSuggestFetcher(kDefaultProviderURLFetcherID,
522 providers_.GetDefaultProviderURL(), input_));
523 keyword_fetcher_.reset(CreateSuggestFetcher(kKeywordProviderURLFetcherID,
524 providers_.GetKeywordProviderURL(), keyword_input_));
525
526 // Both the above can fail if the providers have been modified or deleted
527 // since the query began.
528 if (suggest_results_pending_ == 0) {
529 UpdateDone();
530 // We only need to update the listener if we're actually done.
531 if (done_)
532 listener_->OnProviderUpdate(false);
533 }
[email protected]601858c02010-09-01 17:08:20534}
535
[email protected]8d457132010-11-04 18:13:40536void SearchProvider::DoHistoryQuery(bool minimal_changes) {
537 // The history query results are synchronous, so if minimal_changes is true,
538 // we still have the last results and don't need to do anything.
539 if (minimal_changes)
initial.commit09911bf2008-07-26 23:55:29540 return;
541
[email protected]8d457132010-11-04 18:13:40542 keyword_history_results_.clear();
543 default_history_results_.clear();
initial.commit09911bf2008-07-26 23:55:29544
[email protected]78e5e432013-08-03 02:10:10545 if (OmniboxFieldTrial::SearchHistoryDisable(
546 input_.current_page_classification()))
[email protected]d8cd76b2013-07-10 09:46:16547 return;
548
[email protected]8d457132010-11-04 18:13:40549 HistoryService* const history_service =
[email protected]9d2db762012-06-19 00:01:10550 HistoryServiceFactory::GetForProfile(profile_, Profile::EXPLICIT_ACCESS);
[email protected]8d457132010-11-04 18:13:40551 history::URLDatabase* url_db = history_service ?
552 history_service->InMemoryDatabase() : NULL;
[email protected]8d457132010-11-04 18:13:40553 if (!url_db)
initial.commit09911bf2008-07-26 23:55:29554 return;
555
[email protected]51124552011-07-16 01:37:10556 // Request history for both the keyword and default provider. We grab many
557 // more matches than we'll ultimately clamp to so that if there are several
558 // recent multi-word matches who scores are lowered (see
559 // AddHistoryResultsToMap()), they won't crowd out older, higher-scoring
560 // matches. Note that this doesn't fix the problem entirely, but merely
561 // limits it to cases with a very large number of such multi-word matches; for
562 // now, this seems OK compared with the complexity of a real fix, which would
563 // require multiple searches and tracking of "single- vs. multi-word" in the
564 // database.
565 int num_matches = kMaxMatches * 5;
[email protected]85b8d6f2012-05-08 20:53:47566 const TemplateURL* default_url = providers_.GetDefaultProviderURL();
567 if (default_url) {
[email protected]b4bec972014-04-05 18:07:15568 const base::TimeTicks start_time = base::TimeTicks::Now();
[email protected]85b8d6f2012-05-08 20:53:47569 url_db->GetMostRecentKeywordSearchTerms(default_url->id(), input_.text(),
570 num_matches, &default_history_results_);
[email protected]31afdf72013-09-26 04:29:36571 UMA_HISTOGRAM_TIMES(
572 "Omnibox.SearchProvider.GetMostRecentKeywordTermsDefaultProviderTime",
573 base::TimeTicks::Now() - start_time);
[email protected]257ab712009-04-14 17:16:24574 }
[email protected]85b8d6f2012-05-08 20:53:47575 const TemplateURL* keyword_url = providers_.GetKeywordProviderURL();
576 if (keyword_url) {
577 url_db->GetMostRecentKeywordSearchTerms(keyword_url->id(),
[email protected]14710852013-02-05 23:45:41578 keyword_input_.text(), num_matches, &keyword_history_results_);
[email protected]3954c3a2012-04-10 20:17:55579 }
initial.commit09911bf2008-07-26 23:55:29580}
581
[email protected]6dc950f2012-07-16 19:49:08582void SearchProvider::StartOrStopSuggestQuery(bool minimal_changes) {
[email protected]83c726482008-09-10 06:36:34583 if (!IsQuerySuitableForSuggest()) {
initial.commit09911bf2008-07-26 23:55:29584 StopSuggest();
[email protected]71b46152013-05-03 16:39:20585 ClearAllResults();
initial.commit09911bf2008-07-26 23:55:29586 return;
587 }
588
589 // For the minimal_changes case, if we finished the previous query and still
590 // have its results, or are allowed to keep running it, just do that, rather
591 // than starting a new query.
592 if (minimal_changes &&
[email protected]cc1526e2013-05-17 04:04:24593 (!default_results_.suggest_results.empty() ||
594 !default_results_.navigation_results.empty() ||
595 !keyword_results_.suggest_results.empty() ||
596 !keyword_results_.navigation_results.empty() ||
[email protected]ea3b9a502011-04-04 14:19:37597 (!done_ &&
598 input_.matches_requested() == AutocompleteInput::ALL_MATCHES)))
initial.commit09911bf2008-07-26 23:55:29599 return;
600
601 // We can't keep running any previous query, so halt it.
602 StopSuggest();
[email protected]d1f0a7f2012-06-05 10:26:42603
604 // Remove existing results that cannot inline autocomplete the new input.
[email protected]71b46152013-05-03 16:39:20605 RemoveAllStaleResults();
initial.commit09911bf2008-07-26 23:55:29606
[email protected]ee6110b2014-01-09 22:26:31607 // Update the content classifications of remaining results so they look good
608 // against the current input.
[email protected]23db6492014-01-16 02:35:30609 UpdateMatchContentsClass(input_.text(), &default_results_);
610 if (!keyword_input_.text().empty())
611 UpdateMatchContentsClass(keyword_input_.text(), &keyword_results_);
[email protected]ee6110b2014-01-09 22:26:31612
initial.commit09911bf2008-07-26 23:55:29613 // We can't start a new query if we're only allowed synchronous results.
[email protected]ea3b9a502011-04-04 14:19:37614 if (input_.matches_requested() != AutocompleteInput::ALL_MATCHES)
initial.commit09911bf2008-07-26 23:55:29615 return;
616
[email protected]24dbf2302013-04-05 16:59:25617 // To avoid flooding the suggest server, don't send a query until at
618 // least 100 ms since the last query.
[email protected]515ffa942012-11-27 20:18:24619 base::TimeTicks next_suggest_time(time_suggest_request_sent_ +
[email protected]bc8bb0cd2013-06-24 21:50:23620 base::TimeDelta::FromMilliseconds(kMinimumTimeBetweenSuggestQueriesMs));
[email protected]515ffa942012-11-27 20:18:24621 base::TimeTicks now(base::TimeTicks::Now());
622 if (now >= next_suggest_time) {
623 Run();
624 return;
625 }
626 timer_.Start(FROM_HERE, next_suggest_time - now, this, &SearchProvider::Run);
initial.commit09911bf2008-07-26 23:55:29627}
628
[email protected]83c726482008-09-10 06:36:34629bool SearchProvider::IsQuerySuitableForSuggest() const {
[email protected]3954c3a2012-04-10 20:17:55630 // Don't run Suggest in incognito mode, if the engine doesn't support it, or
631 // if the user has disabled it.
[email protected]85b8d6f2012-05-08 20:53:47632 const TemplateURL* default_url = providers_.GetDefaultProviderURL();
633 const TemplateURL* keyword_url = providers_.GetKeywordProviderURL();
[email protected]83c726482008-09-10 06:36:34634 if (profile_->IsOffTheRecord() ||
[email protected]85b8d6f2012-05-08 20:53:47635 ((!default_url || default_url->suggestions_url().empty()) &&
636 (!keyword_url || keyword_url->suggestions_url().empty())) ||
[email protected]83c726482008-09-10 06:36:34637 !profile_->GetPrefs()->GetBoolean(prefs::kSearchSuggestEnabled))
638 return false;
639
[email protected]cac59d32010-08-09 23:23:14640 // If the input type might be a URL, we take extra care so that private data
[email protected]83c726482008-09-10 06:36:34641 // isn't sent to the server.
[email protected]83c726482008-09-10 06:36:34642
[email protected]cac59d32010-08-09 23:23:14643 // FORCED_QUERY means the user is explicitly asking us to search for this, so
644 // we assume it isn't a URL and/or there isn't private data.
645 if (input_.type() == AutocompleteInput::FORCED_QUERY)
646 return true;
[email protected]83c726482008-09-10 06:36:34647
[email protected]f608ea102013-03-18 15:08:09648 // Next we check the scheme. If this is UNKNOWN/URL with a scheme that isn't
649 // http/https/ftp, we shouldn't send it. Sending things like file: and data:
650 // is both a waste of time and a disclosure of potentially private, local
651 // data. Other "schemes" may actually be usernames, and we don't want to send
652 // passwords. If the scheme is OK, we still need to check other cases below.
653 // If this is QUERY, then the presence of these schemes means the user
654 // explicitly typed one, and thus this is probably a URL that's being entered
655 // and happens to currently be invalid -- in which case we again want to run
656 // our checks below. Other QUERY cases are less likely to be URLs and thus we
657 // assume we're OK.
[email protected]e9a82042013-09-15 03:38:29658 if (!LowerCaseEqualsASCII(input_.scheme(), content::kHttpScheme) &&
[email protected]4654bfe2013-08-26 03:36:58659 !LowerCaseEqualsASCII(input_.scheme(), content::kHttpsScheme) &&
[email protected]72aa4c22013-12-01 15:09:35660 !LowerCaseEqualsASCII(input_.scheme(), content::kFtpScheme))
[email protected]cac59d32010-08-09 23:23:14661 return (input_.type() == AutocompleteInput::QUERY);
662
663 // Don't send URLs with usernames, queries or refs. Some of these are
664 // private, and the Suggest server is unlikely to have any useful results
665 // for any of them. Also don't send URLs with ports, as we may initially
666 // think that a username + password is a host + port (and we don't want to
667 // send usernames/passwords), and even if the port really is a port, the
668 // server is once again unlikely to have and useful results.
[email protected]825e16f2013-09-30 23:52:58669 // Note that we only block based on refs if the input is URL-typed, as search
670 // queries can legitimately have #s in them which the URL parser
671 // overaggressively categorizes as a url with a ref.
[email protected]cac59d32010-08-09 23:23:14672 const url_parse::Parsed& parts = input_.parts();
673 if (parts.username.is_nonempty() || parts.port.is_nonempty() ||
[email protected]825e16f2013-09-30 23:52:58674 parts.query.is_nonempty() ||
675 (parts.ref.is_nonempty() && (input_.type() == AutocompleteInput::URL)))
[email protected]cac59d32010-08-09 23:23:14676 return false;
677
678 // Don't send anything for https except the hostname. Hostnames are OK
679 // because they are visible when the TCP connection is established, but the
680 // specific path may reveal private information.
[email protected]4654bfe2013-08-26 03:36:58681 if (LowerCaseEqualsASCII(input_.scheme(), content::kHttpsScheme) &&
[email protected]a2fedb1e2011-01-25 15:23:36682 parts.path.is_nonempty())
[email protected]cac59d32010-08-09 23:23:14683 return false;
[email protected]83c726482008-09-10 06:36:34684
685 return true;
686}
687
[email protected]71b46152013-05-03 16:39:20688void SearchProvider::RemoveAllStaleResults() {
[email protected]dc735c02013-11-12 23:23:41689 // We only need to remove stale results (which ensures the top-scoring
690 // match is inlineable) if the user is not in reorder mode. In reorder
691 // mode, the autocomplete system will reorder results to make sure the
692 // top result is inlineable.
693 const bool omnibox_will_reorder_for_legal_default_match =
694 OmniboxFieldTrial::ReorderForLegalDefaultMatch(
695 input_.current_page_classification());
[email protected]1e1550e2013-05-02 17:37:51696 // In theory it would be better to run an algorithm like that in
697 // RemoveStaleResults(...) below that uses all four results lists
698 // and both verbatim scores at once. However, that will be much
699 // more complicated for little obvious gain. For code simplicity
700 // and ease in reasoning about the invariants involved, this code
701 // removes stales results from the keyword provider and default
702 // provider independently.
[email protected]dc735c02013-11-12 23:23:41703 if (!omnibox_will_reorder_for_legal_default_match) {
704 RemoveStaleResults(input_.text(), GetVerbatimRelevance(NULL),
705 &default_results_.suggest_results,
706 &default_results_.navigation_results);
707 if (!keyword_input_.text().empty()) {
708 RemoveStaleResults(keyword_input_.text(),
709 GetKeywordVerbatimRelevance(NULL),
710 &keyword_results_.suggest_results,
711 &keyword_results_.navigation_results);
712 }
713 }
714 if (keyword_input_.text().empty()) {
[email protected]1e1550e2013-05-02 17:37:51715 // User is either in keyword mode with a blank input or out of
716 // keyword mode entirely.
[email protected]cc1526e2013-05-17 04:04:24717 keyword_results_.Clear();
[email protected]1e1550e2013-05-02 17:37:51718 }
[email protected]d1f0a7f2012-06-05 10:26:42719}
720
[email protected]d1f0a7f2012-06-05 10:26:42721void SearchProvider::ApplyCalculatedRelevance() {
[email protected]cc1526e2013-05-17 04:04:24722 ApplyCalculatedSuggestRelevance(&keyword_results_.suggest_results);
723 ApplyCalculatedSuggestRelevance(&default_results_.suggest_results);
724 ApplyCalculatedNavigationRelevance(&keyword_results_.navigation_results);
725 ApplyCalculatedNavigationRelevance(&default_results_.navigation_results);
[email protected]cc1526e2013-05-17 04:04:24726 default_results_.verbatim_relevance = -1;
727 keyword_results_.verbatim_relevance = -1;
[email protected]d1f0a7f2012-06-05 10:26:42728}
729
[email protected]188b50c2013-03-28 07:19:42730void SearchProvider::ApplyCalculatedSuggestRelevance(SuggestResults* list) {
[email protected]d1f0a7f2012-06-05 10:26:42731 for (size_t i = 0; i < list->size(); ++i) {
[email protected]188b50c2013-03-28 07:19:42732 SuggestResult& result = (*list)[i];
733 result.set_relevance(
734 result.CalculateRelevance(input_, providers_.has_keyword_provider()) +
735 (list->size() - i - 1));
[email protected]d30268a2013-06-25 22:31:07736 result.set_relevance_from_server(false);
[email protected]d1f0a7f2012-06-05 10:26:42737 }
738}
739
[email protected]188b50c2013-03-28 07:19:42740void SearchProvider::ApplyCalculatedNavigationRelevance(
741 NavigationResults* list) {
[email protected]d1f0a7f2012-06-05 10:26:42742 for (size_t i = 0; i < list->size(); ++i) {
[email protected]188b50c2013-03-28 07:19:42743 NavigationResult& result = (*list)[i];
744 result.set_relevance(
745 result.CalculateRelevance(input_, providers_.has_keyword_provider()) +
746 (list->size() - i - 1));
[email protected]d30268a2013-06-25 22:31:07747 result.set_relevance_from_server(false);
[email protected]d1f0a7f2012-06-05 10:26:42748 }
749}
750
[email protected]15fb2aa2012-05-22 22:52:59751net::URLFetcher* SearchProvider::CreateSuggestFetcher(
[email protected]7cc6e5632011-10-25 17:56:12752 int id,
[email protected]9ff91722012-09-07 05:29:12753 const TemplateURL* template_url,
[email protected]14710852013-02-05 23:45:41754 const AutocompleteInput& input) {
[email protected]9ff91722012-09-07 05:29:12755 if (!template_url || template_url->suggestions_url().empty())
756 return NULL;
757
758 // Bail if the suggestion URL is invalid with the given replacements.
[email protected]14710852013-02-05 23:45:41759 TemplateURLRef::SearchTermsArgs search_term_args(input.text());
760 search_term_args.cursor_position = input.cursor_position();
[email protected]d5015ca2013-08-08 22:04:18761 search_term_args.page_classification = input.current_page_classification();
[email protected]9ff91722012-09-07 05:29:12762 GURL suggest_url(template_url->suggestions_url_ref().ReplaceSearchTerms(
[email protected]00790562012-12-14 09:57:16763 search_term_args));
[email protected]9ff91722012-09-07 05:29:12764 if (!suggest_url.is_valid())
765 return NULL;
[email protected]9b9fa672013-11-07 06:04:52766 // Send the current page URL if user setting and URL requirements are met and
767 // the user is in the field trial.
768 if (CanSendURL(current_page_url_, suggest_url, template_url,
769 input.current_page_classification(), profile_) &&
770 OmniboxFieldTrial::InZeroSuggestAfterTypingFieldTrial()) {
771 search_term_args.current_page_url = current_page_url_.spec();
772 // Create the suggest URL again with the current page URL.
773 suggest_url = GURL(template_url->suggestions_url_ref().ReplaceSearchTerms(
774 search_term_args));
775 }
[email protected]9ff91722012-09-07 05:29:12776
777 suggest_results_pending_++;
778 LogOmniboxSuggestRequest(REQUEST_SENT);
779
780 net::URLFetcher* fetcher =
781 net::URLFetcher::Create(id, suggest_url, net::URLFetcher::GET, this);
[email protected]7cc6e5632011-10-25 17:56:12782 fetcher->SetRequestContext(profile_->GetRequestContext());
[email protected]d3cf8682f02012-02-29 23:29:34783 fetcher->SetLoadFlags(net::LOAD_DO_NOT_SAVE_COOKIES);
[email protected]bd3b4712012-12-18 17:01:30784 // Add Chrome experiment state to the request headers.
785 net::HttpRequestHeaders headers;
[email protected]ab7780792013-01-10 01:26:09786 chrome_variations::VariationsHttpHeaderProvider::GetInstance()->AppendHeaders(
[email protected]bd3b4712012-12-18 17:01:30787 fetcher->GetOriginalURL(), profile_->IsOffTheRecord(), false, &headers);
788 fetcher->SetExtraRequestHeaders(headers.ToString());
[email protected]257ab712009-04-14 17:16:24789 fetcher->Start();
790 return fetcher;
791}
792
[email protected]344946a12012-12-20 12:03:42793void SearchProvider::ConvertResultsToAutocompleteMatches() {
initial.commit09911bf2008-07-26 23:55:29794 // Convert all the results to matches and add them to a map, so we can keep
795 // the most relevant match for each result.
[email protected]31afdf72013-09-26 04:29:36796 base::TimeTicks start_time(base::TimeTicks::Now());
initial.commit09911bf2008-07-26 23:55:29797 MatchMap map;
[email protected]bc8bb0cd2013-06-24 21:50:23798 const base::Time no_time;
[email protected]cc1526e2013-05-17 04:04:24799 int did_not_accept_keyword_suggestion =
800 keyword_results_.suggest_results.empty() ?
initial.commit09911bf2008-07-26 23:55:29801 TemplateURLRef::NO_SUGGESTIONS_AVAILABLE :
802 TemplateURLRef::NO_SUGGESTION_CHOSEN;
initial.commit09911bf2008-07-26 23:55:29803
[email protected]d30268a2013-06-25 22:31:07804 bool relevance_from_server;
805 int verbatim_relevance = GetVerbatimRelevance(&relevance_from_server);
[email protected]cc1526e2013-05-17 04:04:24806 int did_not_accept_default_suggestion =
807 default_results_.suggest_results.empty() ?
[email protected]55ce8f12012-05-09 04:44:08808 TemplateURLRef::NO_SUGGESTIONS_AVAILABLE :
809 TemplateURLRef::NO_SUGGESTION_CHOSEN;
[email protected]d1f0a7f2012-06-05 10:26:42810 if (verbatim_relevance > 0) {
[email protected]c2ca3fd2014-03-22 03:07:44811 const base::string16& trimmed_verbatim =
812 base::CollapseWhitespace(input_.text(), false);
[email protected]2c03c06b2013-12-11 20:45:02813 SuggestResult verbatim(
[email protected]c2ca3fd2014-03-22 03:07:44814 trimmed_verbatim, AutocompleteMatchType::SEARCH_WHAT_YOU_TYPED,
815 trimmed_verbatim, base::string16(), base::string16(), std::string(),
[email protected]61f99082014-02-24 02:17:49816 std::string(), false, verbatim_relevance, relevance_from_server, false,
[email protected]c2ca3fd2014-03-22 03:07:44817 trimmed_verbatim);
[email protected]57482a72014-03-14 22:27:37818 AddMatchToMap(verbatim, std::string(), did_not_accept_default_suggestion,
819 false, &map);
[email protected]d1f0a7f2012-06-05 10:26:42820 }
[email protected]5423e562013-02-07 03:58:45821 if (!keyword_input_.text().empty()) {
822 const TemplateURL* keyword_url = providers_.GetKeywordProviderURL();
823 // We only create the verbatim search query match for a keyword
824 // if it's not an extension keyword. Extension keywords are handled
825 // in KeywordProvider::Start(). (Extensions are complicated...)
826 // Note: in this provider, SEARCH_OTHER_ENGINE must correspond
827 // to the keyword verbatim search query. Do not create other matches
828 // of type SEARCH_OTHER_ENGINE.
[email protected]bdcbcd82013-10-28 13:40:25829 if (keyword_url &&
830 (keyword_url->GetType() != TemplateURL::OMNIBOX_API_EXTENSION)) {
[email protected]d30268a2013-06-25 22:31:07831 bool keyword_relevance_from_server;
832 const int keyword_verbatim_relevance =
833 GetKeywordVerbatimRelevance(&keyword_relevance_from_server);
[email protected]dab8d52d2013-03-05 07:35:28834 if (keyword_verbatim_relevance > 0) {
[email protected]c2ca3fd2014-03-22 03:07:44835 const base::string16& trimmed_verbatim =
836 base::CollapseWhitespace(keyword_input_.text(), false);
[email protected]2c03c06b2013-12-11 20:45:02837 SuggestResult verbatim(
[email protected]c2ca3fd2014-03-22 03:07:44838 trimmed_verbatim, AutocompleteMatchType::SEARCH_OTHER_ENGINE,
839 trimmed_verbatim, base::string16(), base::string16(),
[email protected]61f99082014-02-24 02:17:49840 std::string(), std::string(), true, keyword_verbatim_relevance,
[email protected]c2ca3fd2014-03-22 03:07:44841 keyword_relevance_from_server, false, trimmed_verbatim);
[email protected]57482a72014-03-14 22:27:37842 AddMatchToMap(verbatim, std::string(),
843 did_not_accept_keyword_suggestion, false, &map);
[email protected]dab8d52d2013-03-05 07:35:28844 }
[email protected]5423e562013-02-07 03:58:45845 }
846 }
[email protected]257ab712009-04-14 17:16:24847 AddHistoryResultsToMap(keyword_history_results_, true,
848 did_not_accept_keyword_suggestion, &map);
849 AddHistoryResultsToMap(default_history_results_, false,
850 did_not_accept_default_suggestion, &map);
851
[email protected]d1cb6a822013-09-18 19:43:00852 AddSuggestResultsToMap(keyword_results_.suggest_results,
853 keyword_results_.metadata, &map);
[email protected]987fad782013-08-28 06:23:18854 AddSuggestResultsToMap(default_results_.suggest_results,
855 default_results_.metadata, &map);
initial.commit09911bf2008-07-26 23:55:29856
[email protected]d30268a2013-06-25 22:31:07857 ACMatches matches;
initial.commit09911bf2008-07-26 23:55:29858 for (MatchMap::const_iterator i(map.begin()); i != map.end(); ++i)
[email protected]d30268a2013-06-25 22:31:07859 matches.push_back(i->second);
initial.commit09911bf2008-07-26 23:55:29860
[email protected]d30268a2013-06-25 22:31:07861 AddNavigationResultsToMatches(keyword_results_.navigation_results, &matches);
862 AddNavigationResultsToMatches(default_results_.navigation_results, &matches);
initial.commit09911bf2008-07-26 23:55:29863
[email protected]d30268a2013-06-25 22:31:07864 // Now add the most relevant matches to |matches_|. We take up to kMaxMatches
865 // suggest/navsuggest matches, regardless of origin. If Instant Extended is
866 // enabled and we have server-provided (and thus hopefully more accurate)
867 // scores for some suggestions, we allow more of those, until we reach
868 // AutocompleteResult::kMaxMatches total matches (that is, enough to fill the
869 // whole popup).
870 //
871 // We will always return any verbatim matches, no matter how we obtained their
872 // scores, unless we have already accepted AutocompleteResult::kMaxMatches
873 // higher-scoring matches under the conditions above.
[email protected]d30268a2013-06-25 22:31:07874 std::sort(matches.begin(), matches.end(), &AutocompleteMatch::MoreRelevant);
875 matches_.clear();
[email protected]3723e6e2012-06-11 21:06:56876
[email protected]d30268a2013-06-25 22:31:07877 size_t num_suggestions = 0;
878 for (ACMatches::const_iterator i(matches.begin());
879 (i != matches.end()) &&
880 (matches_.size() < AutocompleteResult::kMaxMatches);
881 ++i) {
882 // SEARCH_OTHER_ENGINE is only used in the SearchProvider for the keyword
883 // verbatim result, so this condition basically means "if this match is a
884 // suggestion of some sort".
885 if ((i->type != AutocompleteMatchType::SEARCH_WHAT_YOU_TYPED) &&
886 (i->type != AutocompleteMatchType::SEARCH_OTHER_ENGINE)) {
887 // If we've already hit the limit on non-server-scored suggestions, and
888 // this isn't a server-scored suggestion we can add, skip it.
889 if ((num_suggestions >= kMaxMatches) &&
890 (!chrome::IsInstantExtendedAPIEnabled() ||
891 (i->GetAdditionalInfo(kRelevanceFromServerKey) != kTrue))) {
892 continue;
893 }
894
895 ++num_suggestions;
896 }
897
898 matches_.push_back(*i);
899 }
[email protected]31afdf72013-09-26 04:29:36900 UMA_HISTOGRAM_TIMES("Omnibox.SearchProvider.ConvertResultsTime",
901 base::TimeTicks::Now() - start_time);
[email protected]344946a12012-12-20 12:03:42902}
903
[email protected]0a8718b12013-11-13 18:41:31904ACMatches::const_iterator SearchProvider::FindTopMatch(
905 bool autocomplete_result_will_reorder_for_default_match) const {
906 if (!autocomplete_result_will_reorder_for_default_match)
907 return matches_.begin();
908 ACMatches::const_iterator it = matches_.begin();
909 while ((it != matches_.end()) && !it->allowed_to_be_default_match)
910 ++it;
911 return it;
[email protected]9dfb4d362013-04-05 02:15:12912}
913
[email protected]0a8718b12013-11-13 18:41:31914bool SearchProvider::IsTopMatchNavigationInKeywordMode(
915 bool autocomplete_result_will_reorder_for_default_match) const {
916 ACMatches::const_iterator first_match =
917 FindTopMatch(autocomplete_result_will_reorder_for_default_match);
918 return !providers_.keyword_provider().empty() &&
919 (first_match != matches_.end()) &&
920 (first_match->type == AutocompleteMatchType::NAVSUGGEST);
921}
922
[email protected]1c1e7842013-11-22 16:28:16923bool SearchProvider::HasKeywordDefaultMatchInKeywordMode() const {
924 const TemplateURL* keyword_url = providers_.GetKeywordProviderURL();
925 // If the user is not in keyword mode, return true to say that this
926 // constraint is not violated.
927 if (keyword_url == NULL)
928 return true;
929 for (ACMatches::const_iterator it = matches_.begin(); it != matches_.end();
930 ++it) {
931 if ((it->keyword == keyword_url->keyword()) &&
932 it->allowed_to_be_default_match)
933 return true;
934 }
935 return false;
936}
937
[email protected]0a8718b12013-11-13 18:41:31938bool SearchProvider::IsTopMatchScoreTooLow(
939 bool autocomplete_result_will_reorder_for_default_match) const {
940 // In reorder mode, there's no such thing as a score that's too low.
941 if (autocomplete_result_will_reorder_for_default_match)
942 return false;
943
[email protected]dab8d52d2013-03-05 07:35:28944 // Here we use CalculateRelevanceForVerbatimIgnoringKeywordModeState()
945 // rather than CalculateRelevanceForVerbatim() because the latter returns
946 // a very low score (250) if keyword mode is active. This is because
947 // when keyword mode is active the user probably wants the keyword matches,
948 // not matches from the default provider. Hence, we use the version of
949 // the function that ignores whether keyword mode is active. This allows
950 // SearchProvider to maintain its contract with the AutocompleteController
951 // that it will always provide an inlineable match with a reasonable
952 // score.
953 return matches_.front().relevance <
954 CalculateRelevanceForVerbatimIgnoringKeywordModeState();
[email protected]344946a12012-12-20 12:03:42955}
956
[email protected]0a8718b12013-11-13 18:41:31957bool SearchProvider::IsTopMatchSearchWithURLInput(
958 bool autocomplete_result_will_reorder_for_default_match) const {
959 ACMatches::const_iterator first_match =
960 FindTopMatch(autocomplete_result_will_reorder_for_default_match);
961 return (input_.type() == AutocompleteInput::URL) &&
962 (first_match != matches_.end()) &&
963 (first_match->relevance > CalculateRelevanceForVerbatim()) &&
964 (first_match->type != AutocompleteMatchType::NAVSUGGEST);
[email protected]344946a12012-12-20 12:03:42965}
966
[email protected]45f89a92013-08-12 13:41:36967bool SearchProvider::HasValidDefaultMatch(
968 bool autocomplete_result_will_reorder_for_default_match) const {
969 // One of the SearchProvider matches may need to be the overall default. If
970 // AutocompleteResult is allowed to reorder matches, this means we simply
971 // need at least one match in the list to be |allowed_to_be_default_match|.
972 // If no reordering is possible, however, then our first match needs to have
973 // this flag.
974 for (ACMatches::const_iterator it = matches_.begin(); it != matches_.end();
975 ++it) {
976 if (it->allowed_to_be_default_match)
977 return true;
978 if (!autocomplete_result_will_reorder_for_default_match)
979 return false;
980 }
981 return false;
[email protected]344946a12012-12-20 12:03:42982}
983
[email protected]257ab712009-04-14 17:16:24984
985void SearchProvider::AddNavigationResultsToMatches(
[email protected]d30268a2013-06-25 22:31:07986 const NavigationResults& navigation_results,
987 ACMatches* matches) {
[email protected]bc8bb0cd2013-06-24 21:50:23988 for (NavigationResults::const_iterator it = navigation_results.begin();
989 it != navigation_results.end(); ++it) {
[email protected]d30268a2013-06-25 22:31:07990 matches->push_back(NavigationToMatch(*it));
[email protected]bc8bb0cd2013-06-24 21:50:23991 // In the absence of suggested relevance scores, use only the single
992 // highest-scoring result. (The results are already sorted by relevance.)
[email protected]d30268a2013-06-25 22:31:07993 if (!it->relevance_from_server())
[email protected]bc8bb0cd2013-06-24 21:50:23994 return;
[email protected]257ab712009-04-14 17:16:24995 }
996}
997
998void SearchProvider::AddHistoryResultsToMap(const HistoryResults& results,
999 bool is_keyword,
1000 int did_not_accept_suggestion,
1001 MatchMap* map) {
[email protected]51124552011-07-16 01:37:101002 if (results.empty())
1003 return;
1004
[email protected]31afdf72013-09-26 04:29:361005 base::TimeTicks start_time(base::TimeTicks::Now());
[email protected]d7ad4772012-06-01 03:12:541006 bool prevent_inline_autocomplete = input_.prevent_inline_autocomplete() ||
1007 (input_.type() == AutocompleteInput::URL);
[email protected]0085863a2013-12-06 21:19:031008 const base::string16& input_text =
[email protected]14710852013-02-05 23:45:411009 is_keyword ? keyword_input_.text() : input_.text();
[email protected]51124552011-07-16 01:37:101010 bool input_multiple_words = HasMultipleWords(input_text);
1011
[email protected]55ce8f12012-05-09 04:44:081012 SuggestResults scored_results;
1013 if (!prevent_inline_autocomplete && input_multiple_words) {
1014 // ScoreHistoryResults() allows autocompletion of multi-word, 1-visit
1015 // queries if the input also has multiple words. But if we were already
[email protected]51124552011-07-16 01:37:101016 // autocompleting a multi-word, multi-visit query, and the current input is
1017 // still a prefix of it, then changing the autocompletion suddenly feels
1018 // wrong. To detect this case, first score as if only one word has been
1019 // typed, then check for a best result that is an autocompleted, multi-word
1020 // query. If we find one, then just keep that score set.
[email protected]55ce8f12012-05-09 04:44:081021 scored_results = ScoreHistoryResults(results, prevent_inline_autocomplete,
1022 false, input_text, is_keyword);
[email protected]9dfb4d362013-04-05 02:15:121023 if ((scored_results.front().relevance() <
[email protected]55ce8f12012-05-09 04:44:081024 AutocompleteResult::kLowestDefaultScore) ||
[email protected]9dfb4d362013-04-05 02:15:121025 !HasMultipleWords(scored_results.front().suggestion()))
[email protected]55ce8f12012-05-09 04:44:081026 scored_results.clear(); // Didn't detect the case above, score normally.
[email protected]51124552011-07-16 01:37:101027 }
[email protected]55ce8f12012-05-09 04:44:081028 if (scored_results.empty())
1029 scored_results = ScoreHistoryResults(results, prevent_inline_autocomplete,
1030 input_multiple_words, input_text,
1031 is_keyword);
1032 for (SuggestResults::const_iterator i(scored_results.begin());
1033 i != scored_results.end(); ++i) {
[email protected]57482a72014-03-14 22:27:371034 AddMatchToMap(*i, std::string(), did_not_accept_suggestion, true, map);
[email protected]51124552011-07-16 01:37:101035 }
[email protected]31afdf72013-09-26 04:29:361036 UMA_HISTOGRAM_TIMES("Omnibox.SearchProvider.AddHistoryResultsTime",
1037 base::TimeTicks::Now() - start_time);
[email protected]51124552011-07-16 01:37:101038}
1039
[email protected]55ce8f12012-05-09 04:44:081040SearchProvider::SuggestResults SearchProvider::ScoreHistoryResults(
[email protected]51124552011-07-16 01:37:101041 const HistoryResults& results,
1042 bool base_prevent_inline_autocomplete,
1043 bool input_multiple_words,
[email protected]0085863a2013-12-06 21:19:031044 const base::string16& input_text,
[email protected]51124552011-07-16 01:37:101045 bool is_keyword) {
[email protected]810ffba2012-06-12 01:07:481046 AutocompleteClassifier* classifier =
1047 AutocompleteClassifierFactory::GetForProfile(profile_);
[email protected]55ce8f12012-05-09 04:44:081048 SuggestResults scored_results;
[email protected]78e5e432013-08-03 02:10:101049 const bool prevent_search_history_inlining =
1050 OmniboxFieldTrial::SearchHistoryPreventInlining(
1051 input_.current_page_classification());
[email protected]c2ca3fd2014-03-22 03:07:441052 const base::string16& trimmed_input =
1053 base::CollapseWhitespace(input_text, false);
[email protected]257ab712009-04-14 17:16:241054 for (HistoryResults::const_iterator i(results.begin()); i != results.end();
1055 ++i) {
[email protected]c2ca3fd2014-03-22 03:07:441056 const base::string16& trimmed_suggestion =
1057 base::CollapseWhitespace(i->term, false);
1058
[email protected]51124552011-07-16 01:37:101059 // Don't autocomplete multi-word queries that have only been seen once
1060 // unless the user has typed more than one word.
1061 bool prevent_inline_autocomplete = base_prevent_inline_autocomplete ||
[email protected]c2ca3fd2014-03-22 03:07:441062 (!input_multiple_words && (i->visits < 2) &&
1063 HasMultipleWords(trimmed_suggestion));
[email protected]51124552011-07-16 01:37:101064
[email protected]ea3b9a502011-04-04 14:19:371065 // Don't autocomplete search terms that would normally be treated as URLs
[email protected]51124552011-07-16 01:37:101066 // when typed. For example, if the user searched for "google.com" and types
1067 // "goog", don't autocomplete to the search term "google.com". Otherwise,
1068 // the input will look like a URL but act like a search, which is confusing.
[email protected]cc447362011-04-06 03:57:481069 // NOTE: We don't check this in the following cases:
1070 // * When inline autocomplete is disabled, we won't be inline
1071 // autocompleting this term, so we don't need to worry about confusion as
1072 // much. This also prevents calling Classify() again from inside the
1073 // classifier (which will corrupt state and likely crash), since the
[email protected]51124552011-07-16 01:37:101074 // classifier always disables inline autocomplete.
[email protected]cc447362011-04-06 03:57:481075 // * When the user has typed the whole term, the "what you typed" history
1076 // match will outrank us for URL-like inputs anyway, so we need not do
1077 // anything special.
[email protected]c2ca3fd2014-03-22 03:07:441078 if (!prevent_inline_autocomplete && classifier &&
1079 (trimmed_suggestion != trimmed_input)) {
[email protected]ea3b9a502011-04-04 14:19:371080 AutocompleteMatch match;
[email protected]c2ca3fd2014-03-22 03:07:441081 classifier->Classify(trimmed_suggestion, false, false,
[email protected]51abb7b2014-02-09 23:00:081082 input_.current_page_classification(), &match, NULL);
[email protected]2905f742011-10-13 03:51:581083 prevent_inline_autocomplete =
[email protected]749e7ae02012-09-05 18:47:461084 !AutocompleteMatch::IsSearchType(match.type);
[email protected]ea3b9a502011-04-04 14:19:371085 }
[email protected]51124552011-07-16 01:37:101086
[email protected]78e5e432013-08-03 02:10:101087 int relevance = CalculateRelevanceForHistory(
1088 i->time, is_keyword, !prevent_inline_autocomplete,
1089 prevent_search_history_inlining);
[email protected]2c03c06b2013-12-11 20:45:021090 scored_results.push_back(SuggestResult(
[email protected]c2ca3fd2014-03-22 03:07:441091 trimmed_suggestion, AutocompleteMatchType::SEARCH_HISTORY,
1092 trimmed_suggestion, base::string16(), base::string16(), std::string(),
1093 std::string(), is_keyword, relevance, false, false, trimmed_input));
[email protected]257ab712009-04-14 17:16:241094 }
[email protected]51124552011-07-16 01:37:101095
1096 // History returns results sorted for us. However, we may have docked some
1097 // results' scores, so things are no longer in order. Do a stable sort to get
1098 // things back in order without otherwise disturbing results with equal
1099 // scores, then force the scores to be unique, so that the order in which
1100 // they're shown is deterministic.
[email protected]55ce8f12012-05-09 04:44:081101 std::stable_sort(scored_results.begin(), scored_results.end(),
1102 CompareScoredResults());
[email protected]51124552011-07-16 01:37:101103 int last_relevance = 0;
[email protected]55ce8f12012-05-09 04:44:081104 for (SuggestResults::iterator i(scored_results.begin());
1105 i != scored_results.end(); ++i) {
1106 if ((i != scored_results.begin()) && (i->relevance() >= last_relevance))
1107 i->set_relevance(last_relevance - 1);
1108 last_relevance = i->relevance();
[email protected]51124552011-07-16 01:37:101109 }
1110
[email protected]55ce8f12012-05-09 04:44:081111 return scored_results;
[email protected]257ab712009-04-14 17:16:241112}
1113
[email protected]55ce8f12012-05-09 04:44:081114void SearchProvider::AddSuggestResultsToMap(const SuggestResults& results,
[email protected]987fad782013-08-28 06:23:181115 const std::string& metadata,
[email protected]55ce8f12012-05-09 04:44:081116 MatchMap* map) {
[email protected]9487b392014-02-14 02:48:181117 for (size_t i = 0; i < results.size(); ++i)
[email protected]57482a72014-03-14 22:27:371118 AddMatchToMap(results[i], metadata, i, false, map);
initial.commit09911bf2008-07-26 23:55:291119}
1120
[email protected]d30268a2013-06-25 22:31:071121int SearchProvider::GetVerbatimRelevance(bool* relevance_from_server) const {
[email protected]dc6943b2012-06-19 06:39:561122 // Use the suggested verbatim relevance score if it is non-negative (valid),
1123 // if inline autocomplete isn't prevented (always show verbatim on backspace),
[email protected]1beee342012-06-19 22:22:281124 // and if it won't suppress verbatim, leaving no default provider matches.
1125 // Otherwise, if the default provider returned no matches and was still able
[email protected]dc6943b2012-06-19 06:39:561126 // to suppress verbatim, the user would have no search/nav matches and may be
[email protected]1beee342012-06-19 22:22:281127 // left unable to search using their default provider from the omnibox.
[email protected]dc6943b2012-06-19 06:39:561128 // Check for results on each verbatim calculation, as results from older
1129 // queries (on previous input) may be trimmed for failing to inline new input.
[email protected]bc8bb0cd2013-06-24 21:50:231130 bool use_server_relevance =
1131 (default_results_.verbatim_relevance >= 0) &&
[email protected]dab8d52d2013-03-05 07:35:281132 !input_.prevent_inline_autocomplete() &&
[email protected]bc8bb0cd2013-06-24 21:50:231133 ((default_results_.verbatim_relevance > 0) ||
[email protected]cc1526e2013-05-17 04:04:241134 !default_results_.suggest_results.empty() ||
[email protected]bc8bb0cd2013-06-24 21:50:231135 !default_results_.navigation_results.empty());
[email protected]d30268a2013-06-25 22:31:071136 if (relevance_from_server)
1137 *relevance_from_server = use_server_relevance;
[email protected]bc8bb0cd2013-06-24 21:50:231138 return use_server_relevance ?
1139 default_results_.verbatim_relevance : CalculateRelevanceForVerbatim();
[email protected]382a0642012-06-06 06:13:521140}
[email protected]d1f0a7f2012-06-05 10:26:421141
[email protected]382a0642012-06-06 06:13:521142int SearchProvider::CalculateRelevanceForVerbatim() const {
[email protected]85b8d6f2012-05-08 20:53:471143 if (!providers_.keyword_provider().empty())
[email protected]52d08b12009-10-19 18:42:361144 return 250;
[email protected]dab8d52d2013-03-05 07:35:281145 return CalculateRelevanceForVerbatimIgnoringKeywordModeState();
1146}
[email protected]52d08b12009-10-19 18:42:361147
[email protected]dab8d52d2013-03-05 07:35:281148int SearchProvider::
1149 CalculateRelevanceForVerbatimIgnoringKeywordModeState() const {
initial.commit09911bf2008-07-26 23:55:291150 switch (input_.type()) {
1151 case AutocompleteInput::UNKNOWN:
[email protected]52d08b12009-10-19 18:42:361152 case AutocompleteInput::QUERY:
1153 case AutocompleteInput::FORCED_QUERY:
[email protected]90fe2bb2013-01-15 03:42:131154 return kNonURLVerbatimRelevance;
initial.commit09911bf2008-07-26 23:55:291155
initial.commit09911bf2008-07-26 23:55:291156 case AutocompleteInput::URL:
[email protected]52d08b12009-10-19 18:42:361157 return 850;
initial.commit09911bf2008-07-26 23:55:291158
1159 default:
1160 NOTREACHED();
1161 return 0;
1162 }
1163}
1164
[email protected]d30268a2013-06-25 22:31:071165int SearchProvider::GetKeywordVerbatimRelevance(
1166 bool* relevance_from_server) const {
[email protected]dab8d52d2013-03-05 07:35:281167 // Use the suggested verbatim relevance score if it is non-negative (valid),
1168 // if inline autocomplete isn't prevented (always show verbatim on backspace),
1169 // and if it won't suppress verbatim, leaving no keyword provider matches.
1170 // Otherwise, if the keyword provider returned no matches and was still able
1171 // to suppress verbatim, the user would have no search/nav matches and may be
1172 // left unable to search using their keyword provider from the omnibox.
1173 // Check for results on each verbatim calculation, as results from older
1174 // queries (on previous input) may be trimmed for failing to inline new input.
[email protected]bc8bb0cd2013-06-24 21:50:231175 bool use_server_relevance =
1176 (keyword_results_.verbatim_relevance >= 0) &&
[email protected]dab8d52d2013-03-05 07:35:281177 !input_.prevent_inline_autocomplete() &&
[email protected]bc8bb0cd2013-06-24 21:50:231178 ((keyword_results_.verbatim_relevance > 0) ||
[email protected]cc1526e2013-05-17 04:04:241179 !keyword_results_.suggest_results.empty() ||
[email protected]bc8bb0cd2013-06-24 21:50:231180 !keyword_results_.navigation_results.empty());
[email protected]d30268a2013-06-25 22:31:071181 if (relevance_from_server)
1182 *relevance_from_server = use_server_relevance;
[email protected]bc8bb0cd2013-06-24 21:50:231183 return use_server_relevance ?
1184 keyword_results_.verbatim_relevance :
1185 CalculateRelevanceForKeywordVerbatim(keyword_input_.type(),
1186 keyword_input_.prefer_keyword());
[email protected]5423e562013-02-07 03:58:451187}
1188
[email protected]51124552011-07-16 01:37:101189int SearchProvider::CalculateRelevanceForHistory(
[email protected]bc8bb0cd2013-06-24 21:50:231190 const base::Time& time,
[email protected]51124552011-07-16 01:37:101191 bool is_keyword,
[email protected]78e5e432013-08-03 02:10:101192 bool use_aggressive_method,
1193 bool prevent_search_history_inlining) const {
[email protected]aa613d62010-11-09 20:40:181194 // The relevance of past searches falls off over time. There are two distinct
1195 // equations used. If the first equation is used (searches to the primary
[email protected]78e5e432013-08-03 02:10:101196 // provider that we want to score aggressively), the score is in the range
1197 // 1300-1599 (unless |prevent_search_history_inlining|, in which case
[email protected]d8cd76b2013-07-10 09:46:161198 // it's in the range 1200-1299). If the second equation is used the
1199 // relevance of a search 15 minutes ago is discounted 50 points, while the
1200 // relevance of a search two weeks ago is discounted 450 points.
[email protected]bc8bb0cd2013-06-24 21:50:231201 double elapsed_time = std::max((base::Time::Now() - time).InSecondsF(), 0.0);
[email protected]188b50c2013-03-28 07:19:421202 bool is_primary_provider = is_keyword || !providers_.has_keyword_provider();
[email protected]78e5e432013-08-03 02:10:101203 if (is_primary_provider && use_aggressive_method) {
[email protected]aa613d62010-11-09 20:40:181204 // Searches with the past two days get a different curve.
[email protected]51124552011-07-16 01:37:101205 const double autocomplete_time = 2 * 24 * 60 * 60;
[email protected]aa613d62010-11-09 20:40:181206 if (elapsed_time < autocomplete_time) {
[email protected]d8cd76b2013-07-10 09:46:161207 int max_score = is_keyword ? 1599 : 1399;
[email protected]78e5e432013-08-03 02:10:101208 if (prevent_search_history_inlining)
[email protected]d8cd76b2013-07-10 09:46:161209 max_score = 1299;
1210 return max_score - static_cast<int>(99 *
[email protected]aa613d62010-11-09 20:40:181211 std::pow(elapsed_time / autocomplete_time, 2.5));
1212 }
1213 elapsed_time -= autocomplete_time;
1214 }
1215
[email protected]c3a4bd992010-08-18 20:25:011216 const int score_discount =
1217 static_cast<int>(6.5 * std::pow(elapsed_time, 0.3));
initial.commit09911bf2008-07-26 23:55:291218
[email protected]6c85aa02009-02-27 12:08:091219 // Don't let scores go below 0. Negative relevance scores are meaningful in
1220 // a different way.
initial.commit09911bf2008-07-26 23:55:291221 int base_score;
[email protected]51124552011-07-16 01:37:101222 if (is_primary_provider)
[email protected]52d08b12009-10-19 18:42:361223 base_score = (input_.type() == AutocompleteInput::URL) ? 750 : 1050;
[email protected]51124552011-07-16 01:37:101224 else
1225 base_score = 200;
initial.commit09911bf2008-07-26 23:55:291226 return std::max(0, base_score - score_discount);
1227}
1228
initial.commit09911bf2008-07-26 23:55:291229AutocompleteMatch SearchProvider::NavigationToMatch(
[email protected]188b50c2013-03-28 07:19:421230 const NavigationResult& navigation) {
[email protected]5889bfb2014-03-19 00:26:481231 base::string16 input;
1232 const bool trimmed_whitespace = base::TrimWhitespace(
1233 navigation.from_keyword_provider() ?
1234 keyword_input_.text() : input_.text(),
1235 base::TRIM_TRAILING, &input) != base::TRIM_NONE;
[email protected]55ce8f12012-05-09 04:44:081236 AutocompleteMatch match(this, navigation.relevance(), false,
[email protected]b7f64d742013-05-21 04:04:041237 AutocompleteMatchType::NAVSUGGEST);
[email protected]55ce8f12012-05-09 04:44:081238 match.destination_url = navigation.url();
[email protected]371dab12012-06-01 03:23:551239
[email protected]23db6492014-01-16 02:35:301240 // First look for the user's input inside the formatted url as it would be
[email protected]371dab12012-06-01 03:23:551241 // without trimming the scheme, so we can find matches at the beginning of the
1242 // scheme.
[email protected]371dab12012-06-01 03:23:551243 const URLPrefix* prefix =
[email protected]23db6492014-01-16 02:35:301244 URLPrefix::BestURLPrefix(navigation.formatted_url(), input);
[email protected]371dab12012-06-01 03:23:551245 size_t match_start = (prefix == NULL) ?
[email protected]23db6492014-01-16 02:35:301246 navigation.formatted_url().find(input) : prefix->prefix.length();
[email protected]d2445c82013-11-04 22:28:351247 bool trim_http = !AutocompleteInput::HasHTTPScheme(input) &&
1248 (!prefix || (match_start != 0));
[email protected]23db6492014-01-16 02:35:301249 const net::FormatUrlTypes format_types =
1250 net::kFormatUrlOmitAll & ~(trim_http ? 0 : net::kFormatUrlOmitHTTP);
[email protected]371dab12012-06-01 03:23:551251
[email protected]371dab12012-06-01 03:23:551252 const std::string languages(
1253 profile_->GetPrefs()->GetString(prefs::kAcceptLanguages));
[email protected]23db6492014-01-16 02:35:301254 size_t inline_autocomplete_offset = (prefix == NULL) ?
1255 base::string16::npos : (match_start + input.length());
[email protected]371dab12012-06-01 03:23:551256 match.fill_into_edit +=
1257 AutocompleteInput::FormattedStringWithEquivalentMeaning(navigation.url(),
1258 net::FormatUrl(navigation.url(), languages, format_types,
1259 net::UnescapeRule::SPACES, NULL, NULL,
1260 &inline_autocomplete_offset));
[email protected]14119032013-11-07 08:14:261261 // Preserve the forced query '?' prefix in |match.fill_into_edit|.
1262 // Otherwise, user edits to a suggestion would show non-Search results.
1263 if (input_.type() == AutocompleteInput::FORCED_QUERY) {
[email protected]670d3232013-12-24 17:58:581264 match.fill_into_edit.insert(0, base::ASCIIToUTF16("?"));
[email protected]0085863a2013-12-06 21:19:031265 if (inline_autocomplete_offset != base::string16::npos)
[email protected]14119032013-11-07 08:14:261266 ++inline_autocomplete_offset;
1267 }
[email protected]6c94a1022014-02-21 03:48:041268 if (inline_autocomplete_offset != base::string16::npos) {
[email protected]518024c2013-07-19 23:40:251269 DCHECK(inline_autocomplete_offset <= match.fill_into_edit.length());
1270 match.inline_autocompletion =
1271 match.fill_into_edit.substr(inline_autocomplete_offset);
1272 }
[email protected]6c94a1022014-02-21 03:48:041273 // An inlineable navsuggestion can only be the default match when there
1274 // is no keyword provider active, lest it appear first and break the user
[email protected]5889bfb2014-03-19 00:26:481275 // out of keyword mode. It can also only be default if either the inline
1276 // autocompletion is empty or we're not preventing inline autocompletion.
1277 // Finally, if we have an inlineable navsuggestion with an inline completion
1278 // that we're not preventing, make sure we didn't trim any whitespace.
1279 // We don't want to claim http://foo.com/bar is inlineable against the
1280 // input "foo.com/b ".
[email protected]6c94a1022014-02-21 03:48:041281 match.allowed_to_be_default_match = navigation.IsInlineable(input) &&
1282 (providers_.GetKeywordProviderURL() == NULL) &&
[email protected]5889bfb2014-03-19 00:26:481283 (match.inline_autocompletion.empty() ||
1284 (!input_.prevent_inline_autocomplete() && !trimmed_whitespace));
[email protected]371dab12012-06-01 03:23:551285
[email protected]23db6492014-01-16 02:35:301286 match.contents = navigation.match_contents();
1287 match.contents_class = navigation.match_contents_class();
[email protected]55ce8f12012-05-09 04:44:081288 match.description = navigation.description();
[email protected]371dab12012-06-01 03:23:551289 AutocompleteMatch::ClassifyMatchInString(input, match.description,
1290 ACMatchClassification::NONE, &match.description_class);
[email protected]d30268a2013-06-25 22:31:071291
1292 match.RecordAdditionalInfo(
1293 kRelevanceFromServerKey,
1294 navigation.relevance_from_server() ? kTrue : kFalse);
[email protected]987fad782013-08-28 06:23:181295 match.RecordAdditionalInfo(kShouldPrefetchKey, kFalse);
[email protected]d30268a2013-06-25 22:31:071296
initial.commit09911bf2008-07-26 23:55:291297 return match;
1298}
[email protected]4ab4c7c2010-11-24 04:49:341299
[email protected]9dfb4d362013-04-05 02:15:121300void SearchProvider::DemoteKeywordNavigationMatchesPastTopQuery() {
[email protected]d519d392013-03-27 09:24:461301 // First, determine the maximum score of any keyword query match (verbatim or
1302 // query suggestion).
[email protected]d30268a2013-06-25 22:31:071303 bool relevance_from_server;
1304 int max_query_relevance = GetKeywordVerbatimRelevance(&relevance_from_server);
[email protected]cc1526e2013-05-17 04:04:241305 if (!keyword_results_.suggest_results.empty()) {
[email protected]d30268a2013-06-25 22:31:071306 const SuggestResult& top_keyword = keyword_results_.suggest_results.front();
1307 const int suggest_relevance = top_keyword.relevance();
1308 if (suggest_relevance > max_query_relevance) {
1309 max_query_relevance = suggest_relevance;
1310 relevance_from_server = top_keyword.relevance_from_server();
1311 } else if (suggest_relevance == max_query_relevance) {
1312 relevance_from_server |= top_keyword.relevance_from_server();
1313 }
[email protected]d519d392013-03-27 09:24:461314 }
1315 // If no query is supposed to appear, then navigational matches cannot
[email protected]9dfb4d362013-04-05 02:15:121316 // be demoted past it. Get rid of suggested relevance scores for
1317 // navsuggestions and introduce the verbatim results again. The keyword
1318 // verbatim match will outscore the navsuggest matches.
1319 if (max_query_relevance == 0) {
[email protected]cc1526e2013-05-17 04:04:241320 ApplyCalculatedNavigationRelevance(&keyword_results_.navigation_results);
1321 ApplyCalculatedNavigationRelevance(&default_results_.navigation_results);
1322 keyword_results_.verbatim_relevance = -1;
1323 default_results_.verbatim_relevance = -1;
[email protected]9dfb4d362013-04-05 02:15:121324 return;
1325 }
[email protected]d519d392013-03-27 09:24:461326 // Now we know we can enforce the minimum score constraint even after
1327 // the navigation matches are demoted. Proceed to demote the navigation
1328 // matches to enforce the query-must-come-first constraint.
[email protected]d519d392013-03-27 09:24:461329 // Cap the relevance score of all results.
[email protected]cc1526e2013-05-17 04:04:241330 for (NavigationResults::iterator it =
1331 keyword_results_.navigation_results.begin();
1332 it != keyword_results_.navigation_results.end(); ++it) {
[email protected]9dfb4d362013-04-05 02:15:121333 if (it->relevance() < max_query_relevance)
1334 return;
1335 max_query_relevance = std::max(max_query_relevance - 1, 0);
1336 it->set_relevance(max_query_relevance);
[email protected]d30268a2013-06-25 22:31:071337 it->set_relevance_from_server(relevance_from_server);
[email protected]d519d392013-03-27 09:24:461338 }
[email protected]d519d392013-03-27 09:24:461339}
1340
[email protected]4ab4c7c2010-11-24 04:49:341341void SearchProvider::UpdateDone() {
[email protected]2cdf1172012-08-26 12:21:331342 // We're done when the timer isn't running, there are no suggest queries
[email protected]5fac3782013-03-06 09:32:311343 // pending, and we're not waiting on Instant.
[email protected]e1290ee62013-06-26 18:31:151344 done_ = !timer_.IsRunning() && (suggest_results_pending_ == 0);
[email protected]4ab4c7c2010-11-24 04:49:341345}