blob: 1c81307542bf25b92ec6d633c397cac4fefa73cd [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]bb900e02013-03-14 14:15:2910#include "base/auto_reset.h"
[email protected]2041cf342010-02-19 03:15:5911#include "base/callback.h"
[email protected]51124552011-07-16 01:37:1012#include "base/i18n/break_iterator.h"
[email protected]503d03872011-05-06 08:36:2613#include "base/i18n/case_conversion.h"
[email protected]d6e58c6e2009-10-10 20:40:5014#include "base/i18n/icu_string_conversions.h"
[email protected]ffbec692012-02-26 20:26:4215#include "base/json/json_string_value_serializer.h"
initial.commit09911bf2008-07-26 23:55:2916#include "base/message_loop.h"
[email protected]f5b95ba92012-03-27 14:05:1917#include "base/metrics/histogram.h"
[email protected]3853a4c2013-02-11 17:15:5718#include "base/prefs/pref_service.h"
[email protected]dc9a6762010-08-16 07:13:5319#include "base/string16.h"
[email protected]371dab12012-06-01 03:23:5520#include "base/string_util.h"
[email protected]1cb2dac2010-03-08 21:49:1521#include "base/utf_string_conversions.h"
[email protected]ea3b9a502011-04-04 14:19:3722#include "chrome/browser/autocomplete/autocomplete_classifier.h"
[email protected]810ffba2012-06-12 01:07:4823#include "chrome/browser/autocomplete/autocomplete_classifier_factory.h"
[email protected]9ac40092010-10-27 23:05:2624#include "chrome/browser/autocomplete/autocomplete_match.h"
[email protected]5af9bc82012-06-29 00:53:4825#include "chrome/browser/autocomplete/autocomplete_provider_listener.h"
[email protected]73c2b1632012-07-02 22:51:3826#include "chrome/browser/autocomplete/autocomplete_result.h"
[email protected]2c812ba02011-07-14 00:23:1527#include "chrome/browser/autocomplete/keyword_provider.h"
[email protected]371dab12012-06-01 03:23:5528#include "chrome/browser/autocomplete/url_prefix.h"
[email protected]6a2c09f2013-01-25 04:50:0729#include "chrome/browser/history/history_service.h"
[email protected]9d2db762012-06-19 00:01:1030#include "chrome/browser/history/history_service_factory.h"
[email protected]10c2d692012-05-11 05:32:2331#include "chrome/browser/history/in_memory_database.h"
[email protected]ab7780792013-01-10 01:26:0932#include "chrome/browser/metrics/variations/variations_http_header_provider.h"
[email protected]f870a322009-01-16 21:47:2733#include "chrome/browser/net/url_fixer_upper.h"
[email protected]684fcc12013-03-08 22:50:0234#include "chrome/browser/omnibox/omnibox_field_trial.h"
[email protected]8ecad5e2010-12-02 21:18:3335#include "chrome/browser/profiles/profile.h"
[email protected]a7b8e43d2013-03-18 18:52:4336#include "chrome/browser/search/search.h"
[email protected]a0ad93ea2012-05-07 22:11:5337#include "chrome/browser/search_engines/search_engine_type.h"
[email protected]9899a612012-08-21 23:50:0438#include "chrome/browser/search_engines/template_url_prepopulate_data.h"
[email protected]8e5c89a2011-06-07 18:13:3339#include "chrome/browser/search_engines/template_url_service.h"
40#include "chrome/browser/search_engines/template_url_service_factory.h"
initial.commit09911bf2008-07-26 23:55:2941#include "chrome/common/pref_names.h"
[email protected]dcf7d352009-02-26 01:56:0242#include "chrome/common/url_constants.h"
initial.commit09911bf2008-07-26 23:55:2943#include "googleurl/src/url_util.h"
[email protected]34ac8f32009-02-22 23:03:2744#include "grit/generated_resources.h"
initial.commit09911bf2008-07-26 23:55:2945#include "net/base/escape.h"
[email protected]d3cf8682f02012-02-29 23:29:3446#include "net/base/load_flags.h"
[email protected]371dab12012-06-01 03:23:5547#include "net/base/net_util.h"
[email protected]bd3b4712012-12-18 17:01:3048#include "net/http/http_request_headers.h"
[email protected]319d9e6f2009-02-18 19:47:2149#include "net/http/http_response_headers.h"
[email protected]3dc1bc42012-06-19 08:20:5350#include "net/url_request/url_fetcher.h"
[email protected]319d9e6f2009-02-18 19:47:2151#include "net/url_request/url_request_status.h"
[email protected]c051a1b2011-01-21 23:30:1752#include "ui/base/l10n/l10n_util.h"
initial.commit09911bf2008-07-26 23:55:2953
[email protected]e1acf6f2008-10-27 20:43:3354using base::Time;
55using base::TimeDelta;
56
[email protected]51124552011-07-16 01:37:1057namespace {
58
[email protected]7706a522012-08-16 17:42:2559// We keep track in a histogram how many suggest requests we send, how
60// many suggest requests we invalidate (e.g., due to a user typing
61// another character), and how many replies we receive.
62// *** ADD NEW ENUMS AFTER ALL PREVIOUSLY DEFINED ONES! ***
63// (excluding the end-of-list enum value)
64// We do not want values of existing enums to change or else it screws
65// up the statistics.
66enum SuggestRequestsHistogramValue {
67 REQUEST_SENT = 1,
68 REQUEST_INVALIDATED,
69 REPLY_RECEIVED,
70 MAX_SUGGEST_REQUEST_HISTOGRAM_VALUE
71};
72
[email protected]90fe2bb2013-01-15 03:42:1373// The verbatim score for an input which is not an URL.
74const int kNonURLVerbatimRelevance = 1300;
75
[email protected]7706a522012-08-16 17:42:2576// Increments the appropriate value in the histogram by one.
77void LogOmniboxSuggestRequest(
78 SuggestRequestsHistogramValue request_value) {
79 UMA_HISTOGRAM_ENUMERATION("Omnibox.SuggestRequests", request_value,
80 MAX_SUGGEST_REQUEST_HISTOGRAM_VALUE);
81}
82
[email protected]51124552011-07-16 01:37:1083bool HasMultipleWords(const string16& text) {
84 base::i18n::BreakIterator i(text, base::i18n::BreakIterator::BREAK_WORD);
85 bool found_word = false;
86 if (i.Init()) {
87 while (i.Advance()) {
88 if (i.IsWord()) {
89 if (found_word)
90 return true;
91 found_word = true;
92 }
93 }
94 }
95 return false;
96}
97
[email protected]d1f0a7f2012-06-05 10:26:4298} // namespace
[email protected]51124552011-07-16 01:37:1099
[email protected]033f3422012-03-13 21:24:18100
[email protected]3954c3a2012-04-10 20:17:55101// SearchProvider::Providers --------------------------------------------------
[email protected]b547666d2009-04-23 16:37:58102
[email protected]85b8d6f2012-05-08 20:53:47103SearchProvider::Providers::Providers(TemplateURLService* template_url_service)
104 : template_url_service_(template_url_service) {
105}
106
107const TemplateURL* SearchProvider::Providers::GetDefaultProviderURL() const {
108 return default_provider_.empty() ? NULL :
109 template_url_service_->GetTemplateURLForKeyword(default_provider_);
110}
111
112const TemplateURL* SearchProvider::Providers::GetKeywordProviderURL() const {
113 return keyword_provider_.empty() ? NULL :
114 template_url_service_->GetTemplateURLForKeyword(keyword_provider_);
[email protected]257ab712009-04-14 17:16:24115}
116
[email protected]3954c3a2012-04-10 20:17:55117
118// SearchProvider -------------------------------------------------------------
119
120// static
121const int SearchProvider::kDefaultProviderURLFetcherID = 1;
122// static
123const int SearchProvider::kKeywordProviderURLFetcherID = 2;
[email protected]24dbf2302013-04-05 16:59:25124// static
125int SearchProvider::kMinimumTimeBetweenSuggestQueriesMs = 100;
[email protected]3954c3a2012-04-10 20:17:55126
[email protected]cb86ee6f2013-04-28 16:58:15127// static
128AutocompleteMatch SearchProvider::CreateSearchSuggestion(
129 Profile* profile,
130 AutocompleteProvider* autocomplete_provider,
131 const AutocompleteInput& input,
132 const string16& query_string,
133 const string16& input_text,
134 int relevance,
135 AutocompleteMatch::Type type,
136 int accepted_suggestion,
137 bool is_keyword,
138 const string16& keyword) {
139 AutocompleteMatch match(autocomplete_provider, relevance, false, type);
140
141 // Bail out now if we don't actually have a valid provider.
142 match.keyword = keyword;
143 const TemplateURL* provider_url = match.GetTemplateURL(profile, false);
144 if (provider_url == NULL)
145 return match;
146
147 match.contents.assign(query_string);
148 // We do intra-string highlighting for suggestions - the suggested segment
149 // will be highlighted, e.g. for input_text = "you" the suggestion may be
150 // "youtube", so we'll bold the "tube" section: you*tube*.
151 if (input_text != query_string) {
152 size_t input_position = match.contents.find(input_text);
153 if (input_position == string16::npos) {
154 // The input text is not a substring of the query string, e.g. input
155 // text is "slasdot" and the query string is "slashdot", so we bold the
156 // whole thing.
157 match.contents_class.push_back(
158 ACMatchClassification(0, ACMatchClassification::MATCH));
159 } else {
160 // TODO(beng): ACMatchClassification::MATCH now seems to just mean
161 // "bold" this. Consider modifying the terminology.
162 // We don't iterate over the string here annotating all matches because
163 // it looks odd to have every occurrence of a substring that may be as
164 // short as a single character highlighted in a query suggestion result,
165 // e.g. for input text "s" and query string "southwest airlines", it
166 // looks odd if both the first and last s are highlighted.
167 if (input_position != 0) {
168 match.contents_class.push_back(
169 ACMatchClassification(0, ACMatchClassification::NONE));
170 }
171 match.contents_class.push_back(
172 ACMatchClassification(input_position, ACMatchClassification::DIM));
173 size_t next_fragment_position = input_position + input_text.length();
174 if (next_fragment_position < query_string.length()) {
175 match.contents_class.push_back(
176 ACMatchClassification(next_fragment_position,
177 ACMatchClassification::NONE));
178 }
179 }
180 } else {
181 // Otherwise, we're dealing with the "default search" result which has no
182 // completion.
183 match.contents_class.push_back(
184 ACMatchClassification(0, ACMatchClassification::NONE));
185 }
186
187 // When the user forced a query, we need to make sure all the fill_into_edit
188 // values preserve that property. Otherwise, if the user starts editing a
189 // suggestion, non-Search results will suddenly appear.
190 if (input.type() == AutocompleteInput::FORCED_QUERY)
191 match.fill_into_edit.assign(ASCIIToUTF16("?"));
192 if (is_keyword)
193 match.fill_into_edit.append(match.keyword + char16(' '));
194 if (!input.prevent_inline_autocomplete() &&
195 StartsWith(query_string, input_text, false)) {
196 match.inline_autocomplete_offset =
197 match.fill_into_edit.length() + input_text.length();
198 }
199 match.fill_into_edit.append(query_string);
200
201 const TemplateURLRef& search_url = provider_url->url_ref();
202 DCHECK(search_url.SupportsReplacement());
203 match.search_terms_args.reset(
204 new TemplateURLRef::SearchTermsArgs(query_string));
205 match.search_terms_args->original_query = input_text;
206 match.search_terms_args->accepted_suggestion = accepted_suggestion;
207 // This is the destination URL sans assisted query stats. This must be set
208 // so the AutocompleteController can properly de-dupe; the controller will
209 // eventually overwrite it before it reaches the user.
210 match.destination_url =
211 GURL(search_url.ReplaceSearchTerms(*match.search_terms_args.get()));
212
213 // Search results don't look like URLs.
214 match.transition = is_keyword ?
215 content::PAGE_TRANSITION_KEYWORD : content::PAGE_TRANSITION_GENERATED;
216
217 return match;
218}
219
[email protected]30f5bc92012-06-26 04:14:55220SearchProvider::SearchProvider(AutocompleteProviderListener* listener,
221 Profile* profile)
[email protected]35f1f4f02012-09-11 13:17:00222 : AutocompleteProvider(listener, profile,
223 AutocompleteProvider::TYPE_SEARCH),
[email protected]85b8d6f2012-05-08 20:53:47224 providers_(TemplateURLServiceFactory::GetForProfile(profile)),
[email protected]601858c02010-09-01 17:08:20225 suggest_results_pending_(0),
[email protected]dab8d52d2013-03-05 07:35:28226 has_default_suggested_relevance_(false),
227 has_keyword_suggested_relevance_(false),
228 default_verbatim_relevance_(-1),
229 keyword_verbatim_relevance_(-1),
[email protected]8e5cc282010-12-05 18:11:39230 have_suggest_results_(false),
[email protected]618d6e62012-12-16 05:55:57231 instant_finalized_(false),
232 field_trial_triggered_(false),
[email protected]9a091392013-05-04 14:27:24233 field_trial_triggered_in_session_(false),
234 suppress_search_suggestions_(false) {
[email protected]4ab4c7c2010-11-24 04:49:34235}
236
[email protected]a2fedb1e2011-01-25 15:23:36237void SearchProvider::FinalizeInstantQuery(const string16& input_text,
[email protected]93b73832012-10-18 20:18:38238 const InstantSuggestion& suggestion) {
[email protected]4ab4c7c2010-11-24 04:49:34239 if (done_ || instant_finalized_)
240 return;
241
242 instant_finalized_ = true;
243 UpdateDone();
244
[email protected]e918c112010-12-08 23:03:49245 if (input_text.empty()) {
[email protected]4ab4c7c2010-11-24 04:49:34246 // We only need to update the listener if we're actually done.
247 if (done_)
248 listener_->OnProviderUpdate(false);
249 return;
250 }
251
[email protected]93b73832012-10-18 20:18:38252 default_provider_suggestion_ = suggestion;
[email protected]9e789742011-01-10 23:27:32253
[email protected]a2fedb1e2011-01-25 15:23:36254 string16 adjusted_input_text(input_text);
[email protected]e918c112010-12-08 23:03:49255 AutocompleteInput::RemoveForcedQueryStringIfNecessary(input_.type(),
256 &adjusted_input_text);
257
[email protected]93b73832012-10-18 20:18:38258 const string16 text = adjusted_input_text + suggestion.text;
[email protected]9acdcdc02012-05-21 20:58:36259 bool results_updated = false;
[email protected]4ab4c7c2010-11-24 04:49:34260 // Remove any matches that are identical to |text|. We don't use the
261 // destination_url for comparison as it varies depending upon the index passed
262 // to TemplateURL::ReplaceSearchTerms.
263 for (ACMatches::iterator i = matches_.begin(); i != matches_.end();) {
264 if (((i->type == AutocompleteMatch::SEARCH_HISTORY) ||
265 (i->type == AutocompleteMatch::SEARCH_SUGGEST)) &&
266 (i->fill_into_edit == text)) {
[email protected]e030de62010-11-24 05:41:19267 i = matches_.erase(i);
[email protected]9acdcdc02012-05-21 20:58:36268 results_updated = true;
[email protected]4ab4c7c2010-11-24 04:49:34269 } else {
270 ++i;
271 }
272 }
273
[email protected]5fac3782013-03-06 09:32:31274 // Add the new Instant suggest result.
[email protected]93b73832012-10-18 20:18:38275 if (suggestion.type == INSTANT_SUGGESTION_SEARCH) {
[email protected]90fe2bb2013-01-15 03:42:13276 // Instant has a query suggestion. Rank it higher than SEARCH_WHAT_YOU_TYPED
277 // so that it gets autocompleted.
278 const int verbatim_relevance = GetVerbatimRelevance();
[email protected]93b73832012-10-18 20:18:38279 int did_not_accept_default_suggestion = default_suggest_results_.empty() ?
[email protected]4ab4c7c2010-11-24 04:49:34280 TemplateURLRef::NO_SUGGESTIONS_AVAILABLE :
281 TemplateURLRef::NO_SUGGESTION_CHOSEN;
[email protected]93b73832012-10-18 20:18:38282 MatchMap match_map;
283 AddMatchToMap(text, adjusted_input_text, verbatim_relevance + 1,
284 AutocompleteMatch::SEARCH_SUGGEST,
285 did_not_accept_default_suggestion, false, &match_map);
286 if (!match_map.empty()) {
287 matches_.push_back(match_map.begin()->second);
288 results_updated = true;
289 }
290 } else {
[email protected]c112f0fe72013-01-18 20:30:09291 // Instant has a URL suggestion. Rank it higher than URL_WHAT_YOU_TYPED so
[email protected]90fe2bb2013-01-15 03:42:13292 // it gets autocompleted; use kNonURLVerbatimRelevance rather than
293 // verbatim_relevance so that the score does not change if the user keeps
294 // typing and the input changes from type UNKNOWN to URL.
[email protected]93b73832012-10-18 20:18:38295 matches_.push_back(NavigationToMatch(
[email protected]a1b5e862013-03-29 06:38:44296 NavigationResult(*this,
297 GURL(UTF16ToUTF8(suggestion.text)),
[email protected]93b73832012-10-18 20:18:38298 string16(),
[email protected]188b50c2013-03-28 07:19:42299 false,
300 kNonURLVerbatimRelevance + 1)));
[email protected]9acdcdc02012-05-21 20:58:36301 results_updated = true;
302 }
[email protected]4ab4c7c2010-11-24 04:49:34303
[email protected]9acdcdc02012-05-21 20:58:36304 if (results_updated || done_)
305 listener_->OnProviderUpdate(results_updated);
[email protected]601858c02010-09-01 17:08:20306}
307
[email protected]0a633ba92013-03-26 09:13:47308void SearchProvider::ClearInstantSuggestion() {
309 default_provider_suggestion_ = InstantSuggestion();
310 if (done_ || instant_finalized_)
311 return;
312 instant_finalized_ = true;
313 UpdateMatches();
314 listener_->OnProviderUpdate(true);
315}
316
[email protected]9a091392013-05-04 14:27:24317void SearchProvider::SuppressSearchSuggestions() {
318 suppress_search_suggestions_ = true;
319}
320
initial.commit09911bf2008-07-26 23:55:29321void SearchProvider::Start(const AutocompleteInput& input,
[email protected]8deeb952008-10-09 18:21:27322 bool minimal_changes) {
[email protected]9a091392013-05-04 14:27:24323 const bool suppress_search_suggestions = suppress_search_suggestions_;
324 suppress_search_suggestions_ = false;
325
[email protected]04504c242013-01-22 21:08:55326 // Do our best to load the model as early as possible. This will reduce
327 // odds of having the model not ready when really needed (a non-empty input).
328 TemplateURLService* model = providers_.template_url_service();
329 DCHECK(model);
330 model->Load();
331
initial.commit09911bf2008-07-26 23:55:29332 matches_.clear();
[email protected]618d6e62012-12-16 05:55:57333 field_trial_triggered_ = false;
initial.commit09911bf2008-07-26 23:55:29334
[email protected]ea3b9a502011-04-04 14:19:37335 instant_finalized_ =
336 (input.matches_requested() != AutocompleteInput::ALL_MATCHES);
[email protected]4ab4c7c2010-11-24 04:49:34337
[email protected]6c85aa02009-02-27 12:08:09338 // Can't return search/suggest results for bogus input or without a profile.
initial.commit09911bf2008-07-26 23:55:29339 if (!profile_ || (input.type() == AutocompleteInput::INVALID)) {
[email protected]e29249dc52012-07-19 17:33:50340 Stop(false);
initial.commit09911bf2008-07-26 23:55:29341 return;
342 }
343
[email protected]14710852013-02-05 23:45:41344 keyword_input_ = input;
[email protected]257ab712009-04-14 17:16:24345 const TemplateURL* keyword_provider =
[email protected]14710852013-02-05 23:45:41346 KeywordProvider::GetSubstitutingTemplateURLForInput(model,
347 &keyword_input_);
348 if (keyword_provider == NULL)
349 keyword_input_.Clear();
350 else if (keyword_input_.text().empty())
[email protected]257ab712009-04-14 17:16:24351 keyword_provider = NULL;
[email protected]257ab712009-04-14 17:16:24352
[email protected]85b8d6f2012-05-08 20:53:47353 const TemplateURL* default_provider = model->GetDefaultSearchProvider();
[email protected]9b74ab52012-03-30 16:08:07354 if (default_provider && !default_provider->SupportsReplacement())
[email protected]257ab712009-04-14 17:16:24355 default_provider = NULL;
356
357 if (keyword_provider == default_provider)
[email protected]e17511f2011-07-13 14:09:18358 default_provider = NULL; // No use in querying the same provider twice.
[email protected]257ab712009-04-14 17:16:24359
360 if (!default_provider && !keyword_provider) {
361 // No valid providers.
[email protected]e29249dc52012-07-19 17:33:50362 Stop(false);
initial.commit09911bf2008-07-26 23:55:29363 return;
364 }
365
366 // If we're still running an old query but have since changed the query text
[email protected]257ab712009-04-14 17:16:24367 // or the providers, abort the query.
[email protected]85b8d6f2012-05-08 20:53:47368 string16 default_provider_keyword(default_provider ?
369 default_provider->keyword() : string16());
370 string16 keyword_provider_keyword(keyword_provider ?
371 keyword_provider->keyword() : string16());
[email protected]9e789742011-01-10 23:27:32372 if (!minimal_changes ||
[email protected]85b8d6f2012-05-08 20:53:47373 !providers_.equal(default_provider_keyword, keyword_provider_keyword)) {
[email protected]bb900e02013-03-14 14:15:29374 // If Instant has not come back with a suggestion, adjust the previous
375 // suggestion if possible. If |instant_finalized| is true, we are looking
376 // for synchronous matches only, so the suggestion is cleared.
377 if (instant_finalized_)
[email protected]93b73832012-10-18 20:18:38378 default_provider_suggestion_ = InstantSuggestion();
[email protected]9e789742011-01-10 23:27:32379 else
[email protected]bb900e02013-03-14 14:15:29380 AdjustDefaultProviderSuggestion(input_.text(), input.text());
381
382 // Cancel any in-flight suggest requests.
383 if (!done_) {
384 // The Stop(false) call below clears |default_provider_suggestion_|, but
385 // in this instance we do not want to clear cached results, so we
386 // restore it.
387 base::AutoReset<InstantSuggestion> reset(&default_provider_suggestion_,
388 InstantSuggestion());
[email protected]e29249dc52012-07-19 17:33:50389 Stop(false);
[email protected]bb900e02013-03-14 14:15:29390 }
[email protected]257ab712009-04-14 17:16:24391 }
initial.commit09911bf2008-07-26 23:55:29392
[email protected]85b8d6f2012-05-08 20:53:47393 providers_.set(default_provider_keyword, keyword_provider_keyword);
initial.commit09911bf2008-07-26 23:55:29394
395 if (input.text().empty()) {
396 // User typed "?" alone. Give them a placeholder result indicating what
397 // this syntax does.
[email protected]257ab712009-04-14 17:16:24398 if (default_provider) {
[email protected]69c579e2010-04-23 20:01:00399 AutocompleteMatch match;
400 match.provider = this;
[email protected]a2fedb1e2011-01-25 15:23:36401 match.contents.assign(l10n_util::GetStringUTF16(IDS_EMPTY_KEYWORD_VALUE));
[email protected]257ab712009-04-14 17:16:24402 match.contents_class.push_back(
[email protected]2c33dd22010-02-11 21:46:35403 ACMatchClassification(0, ACMatchClassification::NONE));
[email protected]85b8d6f2012-05-08 20:53:47404 match.keyword = providers_.default_provider();
[email protected]257ab712009-04-14 17:16:24405 matches_.push_back(match);
406 }
[email protected]e29249dc52012-07-19 17:33:50407 Stop(false);
initial.commit09911bf2008-07-26 23:55:29408 return;
409 }
410
411 input_ = input;
412
[email protected]9a091392013-05-04 14:27:24413 if (!suppress_search_suggestions) {
[email protected]5cd06c3e2012-09-20 03:25:20414 DoHistoryQuery(minimal_changes);
415 StartOrStopSuggestQuery(minimal_changes);
416 }
[email protected]344946a12012-12-20 12:03:42417 UpdateMatches();
initial.commit09911bf2008-07-26 23:55:29418}
419
[email protected]188b50c2013-03-28 07:19:42420SearchProvider::Result::Result(bool from_keyword_provider, int relevance)
421 : from_keyword_provider_(from_keyword_provider),
422 relevance_(relevance) {
423}
424
[email protected]55ce8f12012-05-09 04:44:08425SearchProvider::Result::~Result() {}
426
427SearchProvider::SuggestResult::SuggestResult(const string16& suggestion,
[email protected]188b50c2013-03-28 07:19:42428 bool from_keyword_provider,
[email protected]55ce8f12012-05-09 04:44:08429 int relevance)
[email protected]188b50c2013-03-28 07:19:42430 : Result(from_keyword_provider, relevance),
[email protected]55ce8f12012-05-09 04:44:08431 suggestion_(suggestion) {
432}
433
434SearchProvider::SuggestResult::~SuggestResult() {}
435
[email protected]a1b5e862013-03-29 06:38:44436bool SearchProvider::SuggestResult::IsInlineable(const string16& input) const {
437 return StartsWith(suggestion_, input, false);
438}
439
[email protected]188b50c2013-03-28 07:19:42440int SearchProvider::SuggestResult::CalculateRelevance(
441 const AutocompleteInput& input,
442 bool keyword_provider_requested) const {
443 if (!from_keyword_provider_ && keyword_provider_requested)
444 return 100;
445 return ((input.type() == AutocompleteInput::URL) ? 300 : 600);
446}
447
448SearchProvider::NavigationResult::NavigationResult(
[email protected]a1b5e862013-03-29 06:38:44449 const AutocompleteProvider& provider,
[email protected]188b50c2013-03-28 07:19:42450 const GURL& url,
451 const string16& description,
452 bool from_keyword_provider,
453 int relevance)
454 : Result(from_keyword_provider, relevance),
[email protected]55ce8f12012-05-09 04:44:08455 url_(url),
[email protected]a1b5e862013-03-29 06:38:44456 formatted_url_(AutocompleteInput::FormattedStringWithEquivalentMeaning(
457 url, provider.StringForURLDisplay(url, true, false))),
[email protected]55ce8f12012-05-09 04:44:08458 description_(description) {
459 DCHECK(url_.is_valid());
460}
461
[email protected]a1b5e862013-03-29 06:38:44462SearchProvider::NavigationResult::~NavigationResult() {}
463
464bool SearchProvider::NavigationResult::IsInlineable(
465 const string16& input) const {
466 return URLPrefix::BestURLPrefix(formatted_url_, input) != NULL;
467}
468
[email protected]188b50c2013-03-28 07:19:42469int SearchProvider::NavigationResult::CalculateRelevance(
470 const AutocompleteInput& input,
471 bool keyword_provider_requested) const {
472 return (from_keyword_provider_ || !keyword_provider_requested) ? 800 : 150;
473}
474
[email protected]55ce8f12012-05-09 04:44:08475class SearchProvider::CompareScoredResults {
[email protected]51124552011-07-16 01:37:10476 public:
[email protected]55ce8f12012-05-09 04:44:08477 bool operator()(const Result& a, const Result& b) {
[email protected]51124552011-07-16 01:37:10478 // Sort in descending relevance order.
[email protected]55ce8f12012-05-09 04:44:08479 return a.relevance() > b.relevance();
[email protected]51124552011-07-16 01:37:10480 }
481};
482
initial.commit09911bf2008-07-26 23:55:29483void SearchProvider::Run() {
484 // Start a new request with the current input.
[email protected]257ab712009-04-14 17:16:24485 suggest_results_pending_ = 0;
[email protected]a0ad93ea2012-05-07 22:11:53486 time_suggest_request_sent_ = base::TimeTicks::Now();
[email protected]9ff91722012-09-07 05:29:12487
488 default_fetcher_.reset(CreateSuggestFetcher(kDefaultProviderURLFetcherID,
[email protected]14710852013-02-05 23:45:41489 providers_.GetDefaultProviderURL(), input_));
[email protected]9ff91722012-09-07 05:29:12490 keyword_fetcher_.reset(CreateSuggestFetcher(kKeywordProviderURLFetcherID,
[email protected]14710852013-02-05 23:45:41491 providers_.GetKeywordProviderURL(), keyword_input_));
[email protected]85b8d6f2012-05-08 20:53:47492
493 // Both the above can fail if the providers have been modified or deleted
494 // since the query began.
495 if (suggest_results_pending_ == 0) {
496 UpdateDone();
497 // We only need to update the listener if we're actually done.
498 if (done_)
499 listener_->OnProviderUpdate(false);
500 }
initial.commit09911bf2008-07-26 23:55:29501}
502
[email protected]e29249dc52012-07-19 17:33:50503void SearchProvider::Stop(bool clear_cached_results) {
initial.commit09911bf2008-07-26 23:55:29504 StopSuggest();
505 done_ = true;
[email protected]93b73832012-10-18 20:18:38506 default_provider_suggestion_ = InstantSuggestion();
[email protected]e29249dc52012-07-19 17:33:50507
508 if (clear_cached_results)
[email protected]71b46152013-05-03 16:39:20509 ClearAllResults();
initial.commit09911bf2008-07-26 23:55:29510}
511
[email protected]0e9e8782012-05-15 23:01:51512void SearchProvider::AddProviderInfo(ProvidersInfo* provider_info) const {
513 provider_info->push_back(metrics::OmniboxEventProto_ProviderInfo());
514 metrics::OmniboxEventProto_ProviderInfo& new_entry = provider_info->back();
515 new_entry.set_provider(AsOmniboxEventProviderType());
516 new_entry.set_provider_done(done_);
[email protected]fea6d302013-04-13 02:04:06517 std::vector<uint32> field_trial_hashes;
518 OmniboxFieldTrial::GetActiveSuggestFieldTrialHashes(&field_trial_hashes);
519 for (size_t i = 0; i < field_trial_hashes.size(); ++i) {
[email protected]618d6e62012-12-16 05:55:57520 if (field_trial_triggered_)
[email protected]fea6d302013-04-13 02:04:06521 new_entry.mutable_field_trial_triggered()->Add(field_trial_hashes[i]);
[email protected]d78d7362012-12-19 18:43:28522 if (field_trial_triggered_in_session_) {
[email protected]618d6e62012-12-16 05:55:57523 new_entry.mutable_field_trial_triggered_in_session()->Add(
[email protected]fea6d302013-04-13 02:04:06524 field_trial_hashes[i]);
[email protected]d78d7362012-12-19 18:43:28525 }
[email protected]618d6e62012-12-16 05:55:57526 }
527}
528
529void SearchProvider::ResetSession() {
530 field_trial_triggered_in_session_ = false;
[email protected]0e9e8782012-05-15 23:01:51531}
532
[email protected]10c2d692012-05-11 05:32:23533void SearchProvider::OnURLFetchComplete(const net::URLFetcher* source) {
initial.commit09911bf2008-07-26 23:55:29534 DCHECK(!done_);
[email protected]257ab712009-04-14 17:16:24535 suggest_results_pending_--;
[email protected]7706a522012-08-16 17:42:25536 LogOmniboxSuggestRequest(REPLY_RECEIVED);
[email protected]1cb2dac2010-03-08 21:49:15537 DCHECK_GE(suggest_results_pending_, 0); // Should never go negative.
[email protected]ec9207d32008-09-26 00:51:06538 const net::HttpResponseHeaders* const response_headers =
[email protected]7cc6e5632011-10-25 17:56:12539 source->GetResponseHeaders();
[email protected]c530c852011-10-24 18:18:34540 std::string json_data;
541 source->GetResponseAsString(&json_data);
[email protected]6c85aa02009-02-27 12:08:09542 // JSON is supposed to be UTF-8, but some suggest service providers send JSON
543 // files in non-UTF-8 encodings. The actual encoding is usually specified in
544 // the Content-Type header field.
[email protected]ec9207d32008-09-26 00:51:06545 if (response_headers) {
546 std::string charset;
547 if (response_headers->GetCharset(&charset)) {
[email protected]a2fedb1e2011-01-25 15:23:36548 string16 data_16;
[email protected]ec9207d32008-09-26 00:51:06549 // TODO(jungshik): Switch to CodePageToUTF8 after it's added.
[email protected]c530c852011-10-24 18:18:34550 if (base::CodepageToUTF16(json_data, charset.c_str(),
[email protected]a2fedb1e2011-01-25 15:23:36551 base::OnStringConversionError::FAIL,
552 &data_16))
553 json_data = UTF16ToUTF8(data_16);
[email protected]ec9207d32008-09-26 00:51:06554 }
555 }
556
[email protected]d7ad4772012-06-01 03:12:54557 const bool is_keyword = (source == keyword_fetcher_.get());
[email protected]f2916ea2013-01-26 02:20:14558 // Ensure the request succeeded and that the provider used is still available.
559 // A verbatim match cannot be generated without this provider, causing errors.
[email protected]013e9a02012-05-18 20:27:10560 const bool request_succeeded =
[email protected]f2916ea2013-01-26 02:20:14561 source->GetStatus().is_success() && source->GetResponseCode() == 200 &&
562 ((is_keyword && providers_.GetKeywordProviderURL()) ||
563 (!is_keyword && providers_.GetDefaultProviderURL()));
[email protected]a0ad93ea2012-05-07 22:11:53564
565 // Record response time for suggest requests sent to Google. We care
566 // only about the common case: the Google default provider used in
567 // non-keyword mode.
[email protected]85b8d6f2012-05-08 20:53:47568 const TemplateURL* default_url = providers_.GetDefaultProviderURL();
[email protected]55ce8f12012-05-09 04:44:08569 if (!is_keyword && default_url &&
[email protected]9899a612012-08-21 23:50:04570 (TemplateURLPrepopulateData::GetEngineType(default_url->url()) ==
571 SEARCH_ENGINE_GOOGLE)) {
[email protected]6dc950f2012-07-16 19:49:08572 const TimeDelta elapsed_time =
[email protected]013e9a02012-05-18 20:27:10573 base::TimeTicks::Now() - time_suggest_request_sent_;
574 if (request_succeeded) {
575 UMA_HISTOGRAM_TIMES("Omnibox.SuggestRequest.Success.GoogleResponseTime",
576 elapsed_time);
577 } else {
578 UMA_HISTOGRAM_TIMES("Omnibox.SuggestRequest.Failure.GoogleResponseTime",
579 elapsed_time);
580 }
[email protected]b4cebf82008-12-29 19:59:08581 }
582
[email protected]d7ad4772012-06-01 03:12:54583 bool results_updated = false;
584 if (request_succeeded) {
585 JSONStringValueSerializer deserializer(json_data);
586 deserializer.set_allow_trailing_comma(true);
587 scoped_ptr<Value> data(deserializer.Deserialize(NULL, NULL));
588 results_updated = data.get() && ParseSuggestResults(data.get(), is_keyword);
589 }
590
[email protected]344946a12012-12-20 12:03:42591 UpdateMatches();
[email protected]d7ad4772012-06-01 03:12:54592 if (done_ || results_updated)
593 listener_->OnProviderUpdate(results_updated);
initial.commit09911bf2008-07-26 23:55:29594}
595
[email protected]abe441e2013-05-06 12:35:05596bool SearchProvider::IsNonInstantSearchDone() const {
597 return !timer_.IsRunning() && (suggest_results_pending_ == 0);
598}
599
[email protected]601858c02010-09-01 17:08:20600SearchProvider::~SearchProvider() {
601}
602
[email protected]8d457132010-11-04 18:13:40603void SearchProvider::DoHistoryQuery(bool minimal_changes) {
604 // The history query results are synchronous, so if minimal_changes is true,
605 // we still have the last results and don't need to do anything.
606 if (minimal_changes)
initial.commit09911bf2008-07-26 23:55:29607 return;
608
[email protected]8d457132010-11-04 18:13:40609 keyword_history_results_.clear();
610 default_history_results_.clear();
initial.commit09911bf2008-07-26 23:55:29611
[email protected]8d457132010-11-04 18:13:40612 HistoryService* const history_service =
[email protected]9d2db762012-06-19 00:01:10613 HistoryServiceFactory::GetForProfile(profile_, Profile::EXPLICIT_ACCESS);
[email protected]8d457132010-11-04 18:13:40614 history::URLDatabase* url_db = history_service ?
615 history_service->InMemoryDatabase() : NULL;
616 if (!url_db)
initial.commit09911bf2008-07-26 23:55:29617 return;
618
[email protected]51124552011-07-16 01:37:10619 // Request history for both the keyword and default provider. We grab many
620 // more matches than we'll ultimately clamp to so that if there are several
621 // recent multi-word matches who scores are lowered (see
622 // AddHistoryResultsToMap()), they won't crowd out older, higher-scoring
623 // matches. Note that this doesn't fix the problem entirely, but merely
624 // limits it to cases with a very large number of such multi-word matches; for
625 // now, this seems OK compared with the complexity of a real fix, which would
626 // require multiple searches and tracking of "single- vs. multi-word" in the
627 // database.
628 int num_matches = kMaxMatches * 5;
[email protected]85b8d6f2012-05-08 20:53:47629 const TemplateURL* default_url = providers_.GetDefaultProviderURL();
630 if (default_url) {
631 url_db->GetMostRecentKeywordSearchTerms(default_url->id(), input_.text(),
632 num_matches, &default_history_results_);
[email protected]257ab712009-04-14 17:16:24633 }
[email protected]85b8d6f2012-05-08 20:53:47634 const TemplateURL* keyword_url = providers_.GetKeywordProviderURL();
635 if (keyword_url) {
636 url_db->GetMostRecentKeywordSearchTerms(keyword_url->id(),
[email protected]14710852013-02-05 23:45:41637 keyword_input_.text(), num_matches, &keyword_history_results_);
[email protected]3954c3a2012-04-10 20:17:55638 }
initial.commit09911bf2008-07-26 23:55:29639}
640
[email protected]6dc950f2012-07-16 19:49:08641void SearchProvider::StartOrStopSuggestQuery(bool minimal_changes) {
[email protected]83c726482008-09-10 06:36:34642 if (!IsQuerySuitableForSuggest()) {
initial.commit09911bf2008-07-26 23:55:29643 StopSuggest();
[email protected]71b46152013-05-03 16:39:20644 ClearAllResults();
initial.commit09911bf2008-07-26 23:55:29645 return;
646 }
647
648 // For the minimal_changes case, if we finished the previous query and still
649 // have its results, or are allowed to keep running it, just do that, rather
650 // than starting a new query.
651 if (minimal_changes &&
[email protected]ea3b9a502011-04-04 14:19:37652 (have_suggest_results_ ||
653 (!done_ &&
654 input_.matches_requested() == AutocompleteInput::ALL_MATCHES)))
initial.commit09911bf2008-07-26 23:55:29655 return;
656
657 // We can't keep running any previous query, so halt it.
658 StopSuggest();
[email protected]d1f0a7f2012-06-05 10:26:42659
660 // Remove existing results that cannot inline autocomplete the new input.
[email protected]71b46152013-05-03 16:39:20661 RemoveAllStaleResults();
initial.commit09911bf2008-07-26 23:55:29662
663 // We can't start a new query if we're only allowed synchronous results.
[email protected]ea3b9a502011-04-04 14:19:37664 if (input_.matches_requested() != AutocompleteInput::ALL_MATCHES)
initial.commit09911bf2008-07-26 23:55:29665 return;
666
[email protected]24dbf2302013-04-05 16:59:25667 // To avoid flooding the suggest server, don't send a query until at
668 // least 100 ms since the last query.
[email protected]515ffa942012-11-27 20:18:24669 base::TimeTicks next_suggest_time(time_suggest_request_sent_ +
670 TimeDelta::FromMilliseconds(kMinimumTimeBetweenSuggestQueriesMs));
671 base::TimeTicks now(base::TimeTicks::Now());
672 if (now >= next_suggest_time) {
673 Run();
674 return;
675 }
676 timer_.Start(FROM_HERE, next_suggest_time - now, this, &SearchProvider::Run);
initial.commit09911bf2008-07-26 23:55:29677}
678
[email protected]83c726482008-09-10 06:36:34679bool SearchProvider::IsQuerySuitableForSuggest() const {
[email protected]3954c3a2012-04-10 20:17:55680 // Don't run Suggest in incognito mode, if the engine doesn't support it, or
681 // if the user has disabled it.
[email protected]85b8d6f2012-05-08 20:53:47682 const TemplateURL* default_url = providers_.GetDefaultProviderURL();
683 const TemplateURL* keyword_url = providers_.GetKeywordProviderURL();
[email protected]83c726482008-09-10 06:36:34684 if (profile_->IsOffTheRecord() ||
[email protected]85b8d6f2012-05-08 20:53:47685 ((!default_url || default_url->suggestions_url().empty()) &&
686 (!keyword_url || keyword_url->suggestions_url().empty())) ||
[email protected]83c726482008-09-10 06:36:34687 !profile_->GetPrefs()->GetBoolean(prefs::kSearchSuggestEnabled))
688 return false;
689
[email protected]cac59d32010-08-09 23:23:14690 // If the input type might be a URL, we take extra care so that private data
[email protected]83c726482008-09-10 06:36:34691 // isn't sent to the server.
[email protected]83c726482008-09-10 06:36:34692
[email protected]cac59d32010-08-09 23:23:14693 // FORCED_QUERY means the user is explicitly asking us to search for this, so
694 // we assume it isn't a URL and/or there isn't private data.
695 if (input_.type() == AutocompleteInput::FORCED_QUERY)
696 return true;
[email protected]83c726482008-09-10 06:36:34697
[email protected]f608ea102013-03-18 15:08:09698 // Next we check the scheme. If this is UNKNOWN/URL with a scheme that isn't
699 // http/https/ftp, we shouldn't send it. Sending things like file: and data:
700 // is both a waste of time and a disclosure of potentially private, local
701 // data. Other "schemes" may actually be usernames, and we don't want to send
702 // passwords. If the scheme is OK, we still need to check other cases below.
703 // If this is QUERY, then the presence of these schemes means the user
704 // explicitly typed one, and thus this is probably a URL that's being entered
705 // and happens to currently be invalid -- in which case we again want to run
706 // our checks below. Other QUERY cases are less likely to be URLs and thus we
707 // assume we're OK.
[email protected]a2fedb1e2011-01-25 15:23:36708 if (!LowerCaseEqualsASCII(input_.scheme(), chrome::kHttpScheme) &&
709 !LowerCaseEqualsASCII(input_.scheme(), chrome::kHttpsScheme) &&
710 !LowerCaseEqualsASCII(input_.scheme(), chrome::kFtpScheme))
[email protected]cac59d32010-08-09 23:23:14711 return (input_.type() == AutocompleteInput::QUERY);
712
713 // Don't send URLs with usernames, queries or refs. Some of these are
714 // private, and the Suggest server is unlikely to have any useful results
715 // for any of them. Also don't send URLs with ports, as we may initially
716 // think that a username + password is a host + port (and we don't want to
717 // send usernames/passwords), and even if the port really is a port, the
718 // server is once again unlikely to have and useful results.
719 const url_parse::Parsed& parts = input_.parts();
720 if (parts.username.is_nonempty() || parts.port.is_nonempty() ||
721 parts.query.is_nonempty() || parts.ref.is_nonempty())
722 return false;
723
724 // Don't send anything for https except the hostname. Hostnames are OK
725 // because they are visible when the TCP connection is established, but the
726 // specific path may reveal private information.
[email protected]a2fedb1e2011-01-25 15:23:36727 if (LowerCaseEqualsASCII(input_.scheme(), chrome::kHttpsScheme) &&
728 parts.path.is_nonempty())
[email protected]cac59d32010-08-09 23:23:14729 return false;
[email protected]83c726482008-09-10 06:36:34730
731 return true;
732}
733
initial.commit09911bf2008-07-26 23:55:29734void SearchProvider::StopSuggest() {
[email protected]7706a522012-08-16 17:42:25735 // Increment the appropriate field in the histogram by the number of
736 // pending requests that were invalidated.
737 for (int i = 0; i < suggest_results_pending_; i++)
738 LogOmniboxSuggestRequest(REQUEST_INVALIDATED);
[email protected]257ab712009-04-14 17:16:24739 suggest_results_pending_ = 0;
[email protected]2d316662008-09-03 18:18:14740 timer_.Stop();
[email protected]257ab712009-04-14 17:16:24741 // Stop any in-progress URL fetches.
742 keyword_fetcher_.reset();
743 default_fetcher_.reset();
[email protected]55ce8f12012-05-09 04:44:08744}
745
[email protected]71b46152013-05-03 16:39:20746void SearchProvider::ClearAllResults() {
[email protected]1e1550e2013-05-02 17:37:51747 ClearResults(&keyword_suggest_results_, &keyword_navigation_results_,
748 &keyword_verbatim_relevance_, &has_keyword_suggested_relevance_);
749 ClearResults(&default_suggest_results_, &default_navigation_results_,
750 &default_verbatim_relevance_, &has_default_suggested_relevance_);
initial.commit09911bf2008-07-26 23:55:29751 have_suggest_results_ = false;
initial.commit09911bf2008-07-26 23:55:29752}
753
[email protected]1e1550e2013-05-02 17:37:51754// static
755void SearchProvider::ClearResults(SuggestResults* suggest_results,
756 NavigationResults* navigation_results,
757 int* verbatim_relevance,
758 bool* has_suggested_relevance) {
759 suggest_results->clear();
760 navigation_results->clear();
761 *verbatim_relevance = -1;
762 *has_suggested_relevance = false;
763}
764
[email protected]71b46152013-05-03 16:39:20765void SearchProvider::RemoveAllStaleResults() {
[email protected]1e1550e2013-05-02 17:37:51766 // In theory it would be better to run an algorithm like that in
767 // RemoveStaleResults(...) below that uses all four results lists
768 // and both verbatim scores at once. However, that will be much
769 // more complicated for little obvious gain. For code simplicity
770 // and ease in reasoning about the invariants involved, this code
771 // removes stales results from the keyword provider and default
772 // provider independently.
773 RemoveStaleResults(input_.text(), GetVerbatimRelevance(),
774 &default_suggest_results_, &default_navigation_results_);
775 if (!keyword_input_.text().empty()) {
776 RemoveStaleResults(keyword_input_.text(), GetKeywordVerbatimRelevance(),
777 &keyword_suggest_results_, &keyword_navigation_results_);
778 } else {
779 // User is either in keyword mode with a blank input or out of
780 // keyword mode entirely.
781 ClearResults(
782 &keyword_suggest_results_, &keyword_navigation_results_,
783 &keyword_verbatim_relevance_, &has_keyword_suggested_relevance_);
784 }
[email protected]d1f0a7f2012-06-05 10:26:42785}
786
[email protected]42cfd01d02013-01-23 02:40:02787// static
[email protected]1e1550e2013-05-02 17:37:51788void SearchProvider::RemoveStaleResults(const string16& input,
789 int verbatim_relevance,
790 SuggestResults* suggest_results,
791 NavigationResults* navigation_results) {
792 DCHECK_GE(verbatim_relevance, 0);
793 // Keep pointers to the head of (the highest scoring elements of)
794 // |suggest_results| and |navigation_results|. Iterate down the lists
795 // removing non-inlineable results in order of decreasing relevance
796 // scores. Stop when the highest scoring element among those remaining
797 // is inlineable or the element is less than |verbatim_relevance|.
798 // This allows non-inlineable lower-scoring results to remain
799 // because (i) they are guaranteed to not be inlined and (ii)
800 // letting them remain reduces visual jank. For instance, as the
801 // user types the mis-spelled query "fpobar" (for foobar), the
802 // suggestion "foobar" will be suggested on every keystroke. If the
803 // SearchProvider always removes all non-inlineable results, the user will
804 // see visual jitter/jank as the result disappears and re-appears moments
805 // later as the suggest server returns results.
806 SuggestResults::iterator sug_it = suggest_results->begin();
807 NavigationResults::iterator nav_it = navigation_results->begin();
808 while ((sug_it != suggest_results->end()) ||
809 (nav_it != navigation_results->end())) {
810 const int sug_rel =
811 (sug_it != suggest_results->end()) ? sug_it->relevance() : -1;
812 const int nav_rel =
813 (nav_it != navigation_results->end()) ? nav_it->relevance() : -1;
814 if (std::max(sug_rel, nav_rel) < verbatim_relevance)
815 break;
816 if (sug_rel > nav_rel) {
817 // The current top result is a search suggestion.
818 if (sug_it->IsInlineable(input))
819 break;
820 sug_it = suggest_results->erase(sug_it);
821 } else if (sug_rel == nav_rel) {
822 // Have both results and they're tied.
823 const bool sug_inlineable = sug_it->IsInlineable(input);
824 const bool nav_inlineable = nav_it->IsInlineable(input);
825 if (!sug_inlineable)
826 sug_it = suggest_results->erase(sug_it);
827 if (!nav_inlineable)
828 nav_it = navigation_results->erase(nav_it);
829 if (sug_inlineable || nav_inlineable)
830 break;
831 } else {
832 // The current top result is a navigational suggestion.
833 if (nav_it->IsInlineable(input))
834 break;
835 nav_it = navigation_results->erase(nav_it);
836 }
[email protected]d1f0a7f2012-06-05 10:26:42837 }
838}
839
[email protected]bb900e02013-03-14 14:15:29840void SearchProvider::AdjustDefaultProviderSuggestion(
841 const string16& previous_input,
842 const string16& current_input) {
843 if (default_provider_suggestion_.type == INSTANT_SUGGESTION_URL) {
[email protected]bb900e02013-03-14 14:15:29844 // Description and relevance do not matter in the check for staleness.
[email protected]a1b5e862013-03-29 06:38:44845 NavigationResult result(*this,
846 GURL(default_provider_suggestion_.text),
[email protected]188b50c2013-03-28 07:19:42847 string16(),
848 false,
849 100);
[email protected]bb900e02013-03-14 14:15:29850 // If navigation suggestion is stale, clear |default_provider_suggestion_|.
[email protected]1e1550e2013-05-02 17:37:51851 if (!result.IsInlineable(current_input))
[email protected]bb900e02013-03-14 14:15:29852 default_provider_suggestion_ = InstantSuggestion();
853 } else {
854 DCHECK(default_provider_suggestion_.type == INSTANT_SUGGESTION_SEARCH);
855 // InstantSuggestion of type SEARCH contain only the suggested text, and not
856 // the full text of the query. This looks at the current and previous input
857 // to determine if the user is typing forward, and if the new input is
858 // contained in |default_provider_suggestion_|. If so, the suggestion is
859 // adjusted and can be kept. Otherwise, it is reset.
860 if (!previous_input.empty() &&
861 StartsWith(current_input, previous_input, false)) {
862 // User is typing forward; verify if new input is part of the suggestion.
863 const string16 new_text = string16(current_input, previous_input.size());
864 if (StartsWith(default_provider_suggestion_.text, new_text, false)) {
865 // New input is a prefix to the previous suggestion, adjust the
866 // suggestion to strip the prefix.
867 default_provider_suggestion_.text.erase(0, new_text.size());
868 return;
869 }
870 }
871 // If we are here, the search suggestion is stale; reset it.
872 default_provider_suggestion_ = InstantSuggestion();
873 }
874}
875
[email protected]d1f0a7f2012-06-05 10:26:42876void SearchProvider::ApplyCalculatedRelevance() {
[email protected]188b50c2013-03-28 07:19:42877 ApplyCalculatedSuggestRelevance(&keyword_suggest_results_);
878 ApplyCalculatedSuggestRelevance(&default_suggest_results_);
879 ApplyCalculatedNavigationRelevance(&keyword_navigation_results_);
880 ApplyCalculatedNavigationRelevance(&default_navigation_results_);
[email protected]dab8d52d2013-03-05 07:35:28881 has_default_suggested_relevance_ = false;
882 has_keyword_suggested_relevance_ = false;
883 default_verbatim_relevance_ = -1;
884 keyword_verbatim_relevance_ = -1;
[email protected]d1f0a7f2012-06-05 10:26:42885}
886
[email protected]188b50c2013-03-28 07:19:42887void SearchProvider::ApplyCalculatedSuggestRelevance(SuggestResults* list) {
[email protected]d1f0a7f2012-06-05 10:26:42888 for (size_t i = 0; i < list->size(); ++i) {
[email protected]188b50c2013-03-28 07:19:42889 SuggestResult& result = (*list)[i];
890 result.set_relevance(
891 result.CalculateRelevance(input_, providers_.has_keyword_provider()) +
892 (list->size() - i - 1));
[email protected]d1f0a7f2012-06-05 10:26:42893 }
894}
895
[email protected]188b50c2013-03-28 07:19:42896void SearchProvider::ApplyCalculatedNavigationRelevance(
897 NavigationResults* list) {
[email protected]d1f0a7f2012-06-05 10:26:42898 for (size_t i = 0; i < list->size(); ++i) {
[email protected]188b50c2013-03-28 07:19:42899 NavigationResult& result = (*list)[i];
900 result.set_relevance(
901 result.CalculateRelevance(input_, providers_.has_keyword_provider()) +
902 (list->size() - i - 1));
[email protected]d1f0a7f2012-06-05 10:26:42903 }
904}
905
[email protected]15fb2aa2012-05-22 22:52:59906net::URLFetcher* SearchProvider::CreateSuggestFetcher(
[email protected]7cc6e5632011-10-25 17:56:12907 int id,
[email protected]9ff91722012-09-07 05:29:12908 const TemplateURL* template_url,
[email protected]14710852013-02-05 23:45:41909 const AutocompleteInput& input) {
[email protected]9ff91722012-09-07 05:29:12910 if (!template_url || template_url->suggestions_url().empty())
911 return NULL;
912
913 // Bail if the suggestion URL is invalid with the given replacements.
[email protected]14710852013-02-05 23:45:41914 TemplateURLRef::SearchTermsArgs search_term_args(input.text());
915 search_term_args.cursor_position = input.cursor_position();
[email protected]9ff91722012-09-07 05:29:12916 GURL suggest_url(template_url->suggestions_url_ref().ReplaceSearchTerms(
[email protected]00790562012-12-14 09:57:16917 search_term_args));
[email protected]9ff91722012-09-07 05:29:12918 if (!suggest_url.is_valid())
919 return NULL;
920
921 suggest_results_pending_++;
922 LogOmniboxSuggestRequest(REQUEST_SENT);
923
924 net::URLFetcher* fetcher =
925 net::URLFetcher::Create(id, suggest_url, net::URLFetcher::GET, this);
[email protected]7cc6e5632011-10-25 17:56:12926 fetcher->SetRequestContext(profile_->GetRequestContext());
[email protected]d3cf8682f02012-02-29 23:29:34927 fetcher->SetLoadFlags(net::LOAD_DO_NOT_SAVE_COOKIES);
[email protected]bd3b4712012-12-18 17:01:30928 // Add Chrome experiment state to the request headers.
929 net::HttpRequestHeaders headers;
[email protected]ab7780792013-01-10 01:26:09930 chrome_variations::VariationsHttpHeaderProvider::GetInstance()->AppendHeaders(
[email protected]bd3b4712012-12-18 17:01:30931 fetcher->GetOriginalURL(), profile_->IsOffTheRecord(), false, &headers);
932 fetcher->SetExtraRequestHeaders(headers.ToString());
[email protected]257ab712009-04-14 17:16:24933 fetcher->Start();
934 return fetcher;
935}
936
[email protected]d7ad4772012-06-01 03:12:54937bool SearchProvider::ParseSuggestResults(Value* root_val, bool is_keyword) {
938 // TODO(pkasting): Fix |have_suggest_results_|; see http://crbug.com/130631
939 have_suggest_results_ = false;
initial.commit09911bf2008-07-26 23:55:29940
[email protected]d7ad4772012-06-01 03:12:54941 string16 query;
942 ListValue* root_list = NULL;
943 ListValue* results = NULL;
[email protected]14710852013-02-05 23:45:41944 const string16& input_text =
945 is_keyword ? keyword_input_.text() : input_.text();
[email protected]d7ad4772012-06-01 03:12:54946 if (!root_val->GetAsList(&root_list) || !root_list->GetString(0, &query) ||
947 (query != input_text) || !root_list->GetList(1, &results))
initial.commit09911bf2008-07-26 23:55:29948 return false;
949
[email protected]55ce8f12012-05-09 04:44:08950 // 3rd element: Description list.
[email protected]d7ad4772012-06-01 03:12:54951 ListValue* descriptions = NULL;
952 root_list->GetList(2, &descriptions);
initial.commit09911bf2008-07-26 23:55:29953
[email protected]55ce8f12012-05-09 04:44:08954 // 4th element: Disregard the query URL list for now.
initial.commit09911bf2008-07-26 23:55:29955
[email protected]d1f0a7f2012-06-05 10:26:42956 // Reset suggested relevance information from the default provider.
[email protected]dab8d52d2013-03-05 07:35:28957 bool* has_suggested_relevance = is_keyword ?
958 &has_keyword_suggested_relevance_ : &has_default_suggested_relevance_;
959 *has_suggested_relevance = false;
960 int* verbatim_relevance = is_keyword ?
961 &keyword_verbatim_relevance_ : &default_verbatim_relevance_;
962 *verbatim_relevance = -1;
[email protected]d1f0a7f2012-06-05 10:26:42963
[email protected]55ce8f12012-05-09 04:44:08964 // 5th element: Optional key-value pairs from the Suggest server.
[email protected]d7ad4772012-06-01 03:12:54965 ListValue* types = NULL;
[email protected]d1f0a7f2012-06-05 10:26:42966 ListValue* relevances = NULL;
967 DictionaryValue* extras = NULL;
968 if (root_list->GetDictionary(4, &extras)) {
969 extras->GetList("google:suggesttype", &types);
970
971 // Only accept relevance suggestions if Instant is disabled.
[email protected]165fe422013-03-27 06:34:03972 if (!chrome::IsInstantEnabled(profile_)) {
[email protected]d1f0a7f2012-06-05 10:26:42973 // Discard this list if its size does not match that of the suggestions.
974 if (extras->GetList("google:suggestrelevance", &relevances) &&
975 relevances->GetSize() != results->GetSize())
976 relevances = NULL;
[email protected]dab8d52d2013-03-05 07:35:28977 extras->GetInteger("google:verbatimrelevance", verbatim_relevance);
[email protected]d1f0a7f2012-06-05 10:26:42978 }
[email protected]618d6e62012-12-16 05:55:57979
980 // Check if the active suggest field trial (if any) has triggered either
981 // for the default provider or keyword provider.
982 bool triggered = false;
983 extras->GetBoolean("google:fieldtrialtriggered", &triggered);
984 field_trial_triggered_ |= triggered;
985 field_trial_triggered_in_session_ |= triggered;
initial.commit09911bf2008-07-26 23:55:29986 }
987
[email protected]d7ad4772012-06-01 03:12:54988 SuggestResults* suggest_results =
989 is_keyword ? &keyword_suggest_results_ : &default_suggest_results_;
990 NavigationResults* navigation_results =
991 is_keyword ? &keyword_navigation_results_ : &default_navigation_results_;
initial.commit09911bf2008-07-26 23:55:29992
[email protected]d1f0a7f2012-06-05 10:26:42993 // Clear the previous results now that new results are available.
994 suggest_results->clear();
995 navigation_results->clear();
996
997 string16 result, title;
998 std::string type;
999 int relevance = -1;
[email protected]d7ad4772012-06-01 03:12:541000 for (size_t index = 0; results->GetString(index, &result); ++index) {
[email protected]8e81f5092010-09-29 23:19:401001 // Google search may return empty suggestions for weird input characters,
[email protected]55ce8f12012-05-09 04:44:081002 // they make no sense at all and can cause problems in our code.
[email protected]d7ad4772012-06-01 03:12:541003 if (result.empty())
[email protected]8e81f5092010-09-29 23:19:401004 continue;
1005
[email protected]d1f0a7f2012-06-05 10:26:421006 // Apply valid suggested relevance scores; discard invalid lists.
1007 if (relevances != NULL && !relevances->GetInteger(index, &relevance))
1008 relevances = NULL;
[email protected]d7ad4772012-06-01 03:12:541009 if (types && types->GetString(index, &type) && (type == "NAVIGATION")) {
[email protected]d1f0a7f2012-06-05 10:26:421010 // Do not blindly trust the URL coming from the server to be valid.
1011 GURL url(URLFixerUpper::FixupURL(UTF16ToUTF8(result), std::string()));
1012 if (url.is_valid()) {
1013 if (descriptions != NULL)
1014 descriptions->GetString(index, &title);
[email protected]188b50c2013-03-28 07:19:421015 navigation_results->push_back(NavigationResult(
[email protected]a1b5e862013-03-29 06:38:441016 *this, url, title, is_keyword, relevance));
initial.commit09911bf2008-07-26 23:55:291017 }
1018 } else {
[email protected]d1f0a7f2012-06-05 10:26:421019 // TODO(kochi): Improve calculator result presentation.
[email protected]188b50c2013-03-28 07:19:421020 suggest_results->push_back(SuggestResult(result, is_keyword, relevance));
initial.commit09911bf2008-07-26 23:55:291021 }
1022 }
1023
[email protected]d1f0a7f2012-06-05 10:26:421024 // Apply calculated relevance scores if a valid list was not provided.
1025 if (relevances == NULL) {
[email protected]188b50c2013-03-28 07:19:421026 ApplyCalculatedSuggestRelevance(suggest_results);
1027 ApplyCalculatedNavigationRelevance(navigation_results);
[email protected]dab8d52d2013-03-05 07:35:281028 } else {
1029 *has_suggested_relevance = true;
[email protected]d1f0a7f2012-06-05 10:26:421030 }
[email protected]9dfb4d362013-04-05 02:15:121031 // Keep the result lists sorted.
1032 const CompareScoredResults comparator = CompareScoredResults();
1033 std::stable_sort(suggest_results->begin(), suggest_results->end(),
1034 comparator);
1035 std::stable_sort(navigation_results->begin(), navigation_results->end(),
1036 comparator);
[email protected]d7ad4772012-06-01 03:12:541037 have_suggest_results_ = true;
[email protected]d1f0a7f2012-06-05 10:26:421038 return true;
initial.commit09911bf2008-07-26 23:55:291039}
1040
[email protected]344946a12012-12-20 12:03:421041void SearchProvider::ConvertResultsToAutocompleteMatches() {
initial.commit09911bf2008-07-26 23:55:291042 // Convert all the results to matches and add them to a map, so we can keep
1043 // the most relevant match for each result.
1044 MatchMap map;
[email protected]257ab712009-04-14 17:16:241045 const Time no_time;
1046 int did_not_accept_keyword_suggestion = keyword_suggest_results_.empty() ?
initial.commit09911bf2008-07-26 23:55:291047 TemplateURLRef::NO_SUGGESTIONS_AVAILABLE :
1048 TemplateURLRef::NO_SUGGESTION_CHOSEN;
initial.commit09911bf2008-07-26 23:55:291049
[email protected]382a0642012-06-06 06:13:521050 int verbatim_relevance = GetVerbatimRelevance();
[email protected]257ab712009-04-14 17:16:241051 int did_not_accept_default_suggestion = default_suggest_results_.empty() ?
[email protected]55ce8f12012-05-09 04:44:081052 TemplateURLRef::NO_SUGGESTIONS_AVAILABLE :
1053 TemplateURLRef::NO_SUGGESTION_CHOSEN;
[email protected]d1f0a7f2012-06-05 10:26:421054 if (verbatim_relevance > 0) {
1055 AddMatchToMap(input_.text(), input_.text(), verbatim_relevance,
1056 AutocompleteMatch::SEARCH_WHAT_YOU_TYPED,
1057 did_not_accept_default_suggestion, false, &map);
1058 }
[email protected]5423e562013-02-07 03:58:451059 if (!keyword_input_.text().empty()) {
1060 const TemplateURL* keyword_url = providers_.GetKeywordProviderURL();
1061 // We only create the verbatim search query match for a keyword
1062 // if it's not an extension keyword. Extension keywords are handled
1063 // in KeywordProvider::Start(). (Extensions are complicated...)
1064 // Note: in this provider, SEARCH_OTHER_ENGINE must correspond
1065 // to the keyword verbatim search query. Do not create other matches
1066 // of type SEARCH_OTHER_ENGINE.
1067 if (keyword_url && !keyword_url->IsExtensionKeyword()) {
[email protected]dab8d52d2013-03-05 07:35:281068 const int keyword_verbatim_relevance = GetKeywordVerbatimRelevance();
1069 if (keyword_verbatim_relevance > 0) {
1070 AddMatchToMap(keyword_input_.text(), keyword_input_.text(),
1071 keyword_verbatim_relevance,
1072 AutocompleteMatch::SEARCH_OTHER_ENGINE,
1073 did_not_accept_keyword_suggestion, true, &map);
1074 }
[email protected]5423e562013-02-07 03:58:451075 }
1076 }
1077 const size_t verbatim_matches_size = map.size();
[email protected]93b73832012-10-18 20:18:381078 if (!default_provider_suggestion_.text.empty() &&
[email protected]2ac15ba2013-01-14 22:38:591079 default_provider_suggestion_.type == INSTANT_SUGGESTION_SEARCH &&
1080 !input_.prevent_inline_autocomplete())
[email protected]93b73832012-10-18 20:18:381081 AddMatchToMap(input_.text() + default_provider_suggestion_.text,
[email protected]55ce8f12012-05-09 04:44:081082 input_.text(), verbatim_relevance + 1,
[email protected]85b8d6f2012-05-08 20:53:471083 AutocompleteMatch::SEARCH_SUGGEST,
[email protected]55ce8f12012-05-09 04:44:081084 did_not_accept_default_suggestion, false, &map);
initial.commit09911bf2008-07-26 23:55:291085
[email protected]257ab712009-04-14 17:16:241086 AddHistoryResultsToMap(keyword_history_results_, true,
1087 did_not_accept_keyword_suggestion, &map);
1088 AddHistoryResultsToMap(default_history_results_, false,
1089 did_not_accept_default_suggestion, &map);
1090
[email protected]188b50c2013-03-28 07:19:421091 AddSuggestResultsToMap(keyword_suggest_results_, &map);
1092 AddSuggestResultsToMap(default_suggest_results_, &map);
initial.commit09911bf2008-07-26 23:55:291093
1094 // Now add the most relevant matches from the map to |matches_|.
1095 matches_.clear();
1096 for (MatchMap::const_iterator i(map.begin()); i != map.end(); ++i)
1097 matches_.push_back(i->second);
1098
[email protected]93b73832012-10-18 20:18:381099 if (!default_provider_suggestion_.text.empty() &&
[email protected]2ac15ba2013-01-14 22:38:591100 default_provider_suggestion_.type == INSTANT_SUGGESTION_URL &&
[email protected]90fe2bb2013-01-15 03:42:131101 !input_.prevent_inline_autocomplete()) {
1102 // See comment in FinalizeInstantQuery() for why we don't use
1103 // |verbatim_relevance| here.
[email protected]93b73832012-10-18 20:18:381104 matches_.push_back(NavigationToMatch(
[email protected]a1b5e862013-03-29 06:38:441105 NavigationResult(*this,
1106 GURL(UTF16ToUTF8(default_provider_suggestion_.text)),
[email protected]93b73832012-10-18 20:18:381107 string16(),
[email protected]188b50c2013-03-28 07:19:421108 false,
1109 kNonURLVerbatimRelevance + 1)));
[email protected]90fe2bb2013-01-15 03:42:131110 }
[email protected]257ab712009-04-14 17:16:241111 AddNavigationResultsToMatches(keyword_navigation_results_, true);
1112 AddNavigationResultsToMatches(default_navigation_results_, false);
initial.commit09911bf2008-07-26 23:55:291113
[email protected]5423e562013-02-07 03:58:451114 // Allow additional match(es) for verbatim results if present.
1115 const size_t max_total_matches = kMaxMatches + verbatim_matches_size;
initial.commit09911bf2008-07-26 23:55:291116 std::partial_sort(matches_.begin(),
1117 matches_.begin() + std::min(max_total_matches, matches_.size()),
1118 matches_.end(), &AutocompleteMatch::MoreRelevant);
[email protected]3723e6e2012-06-11 21:06:561119
initial.commit09911bf2008-07-26 23:55:291120 if (matches_.size() > max_total_matches)
[email protected]344946a12012-12-20 12:03:421121 matches_.resize(max_total_matches);
1122}
1123
[email protected]9dfb4d362013-04-05 02:15:121124bool SearchProvider::IsTopMatchNavigationInKeywordMode() const {
1125 return (!providers_.keyword_provider().empty() &&
1126 (matches_.front().type == AutocompleteMatch::NAVSUGGEST));
1127}
1128
[email protected]344946a12012-12-20 12:03:421129bool SearchProvider::IsTopMatchScoreTooLow() const {
[email protected]dab8d52d2013-03-05 07:35:281130 // Here we use CalculateRelevanceForVerbatimIgnoringKeywordModeState()
1131 // rather than CalculateRelevanceForVerbatim() because the latter returns
1132 // a very low score (250) if keyword mode is active. This is because
1133 // when keyword mode is active the user probably wants the keyword matches,
1134 // not matches from the default provider. Hence, we use the version of
1135 // the function that ignores whether keyword mode is active. This allows
1136 // SearchProvider to maintain its contract with the AutocompleteController
1137 // that it will always provide an inlineable match with a reasonable
1138 // score.
1139 return matches_.front().relevance <
1140 CalculateRelevanceForVerbatimIgnoringKeywordModeState();
[email protected]344946a12012-12-20 12:03:421141}
1142
1143bool SearchProvider::IsTopMatchHighRankSearchForURL() const {
1144 return input_.type() == AutocompleteInput::URL &&
1145 matches_.front().relevance > CalculateRelevanceForVerbatim() &&
1146 (matches_.front().type == AutocompleteMatch::SEARCH_SUGGEST ||
[email protected]5423e562013-02-07 03:58:451147 matches_.front().type == AutocompleteMatch::SEARCH_WHAT_YOU_TYPED ||
1148 matches_.front().type == AutocompleteMatch::SEARCH_OTHER_ENGINE);
[email protected]344946a12012-12-20 12:03:421149}
1150
1151bool SearchProvider::IsTopMatchNotInlinable() const {
[email protected]5423e562013-02-07 03:58:451152 // Note: this test assumes the SEARCH_OTHER_ENGINE match corresponds to
1153 // the verbatim search query on the keyword engine. SearchProvider should
1154 // not create any other match of type SEARCH_OTHER_ENGINE.
[email protected]344946a12012-12-20 12:03:421155 return matches_.front().type != AutocompleteMatch::SEARCH_WHAT_YOU_TYPED &&
1156 matches_.front().type != AutocompleteMatch::URL_WHAT_YOU_TYPED &&
[email protected]5423e562013-02-07 03:58:451157 matches_.front().type != AutocompleteMatch::SEARCH_OTHER_ENGINE &&
[email protected]344946a12012-12-20 12:03:421158 matches_.front().inline_autocomplete_offset == string16::npos &&
1159 matches_.front().fill_into_edit != input_.text();
1160}
1161
1162void SearchProvider::UpdateMatches() {
1163 ConvertResultsToAutocompleteMatches();
initial.commit09911bf2008-07-26 23:55:291164
[email protected]382a0642012-06-06 06:13:521165 // Check constraints that may be violated by suggested relevances.
[email protected]344946a12012-12-20 12:03:421166 if (!matches_.empty() &&
[email protected]dab8d52d2013-03-05 07:35:281167 (has_default_suggested_relevance_ || default_verbatim_relevance_ >= 0 ||
1168 has_keyword_suggested_relevance_ || keyword_verbatim_relevance_ >= 0)) {
[email protected]9dfb4d362013-04-05 02:15:121169 // These blocks attempt to repair undesirable behavior by suggested
[email protected]344946a12012-12-20 12:03:421170 // relevances with minimal impact, preserving other suggested relevances.
[email protected]9dfb4d362013-04-05 02:15:121171 if (IsTopMatchNavigationInKeywordMode()) {
1172 // Correct the suggested relevance scores if the top match is a
1173 // navigation in keyword mode, since inlining a navigation match
1174 // would break the user out of keyword mode. By the way, if the top
1175 // match is a non-keyword match (query or navsuggestion) in keyword
1176 // mode, the user would also break out of keyword mode. However,
1177 // that situation is impossible given the current scoring paradigm
1178 // and the fact that only one search engine (Google) provides suggested
1179 // relevance scores at this time.
1180 DemoteKeywordNavigationMatchesPastTopQuery();
1181 ConvertResultsToAutocompleteMatches();
1182 DCHECK(!IsTopMatchNavigationInKeywordMode());
1183 }
[email protected]344946a12012-12-20 12:03:421184 if (IsTopMatchScoreTooLow()) {
[email protected]1beee342012-06-19 22:22:281185 // Disregard the suggested verbatim relevance if the top score is below
1186 // the usual verbatim value. For example, a BarProvider may rely on
1187 // SearchProvider's verbatim or inlineable matches for input "foo" to
1188 // always outrank its own lowly-ranked non-inlineable "bar" match.
[email protected]dab8d52d2013-03-05 07:35:281189 default_verbatim_relevance_ = -1;
1190 keyword_verbatim_relevance_ = -1;
[email protected]344946a12012-12-20 12:03:421191 ConvertResultsToAutocompleteMatches();
[email protected]e6acd002012-06-16 22:27:471192 }
[email protected]344946a12012-12-20 12:03:421193 if (IsTopMatchHighRankSearchForURL()) {
[email protected]e6acd002012-06-16 22:27:471194 // Disregard the suggested search and verbatim relevances if the input
1195 // type is URL and the top match is a highly-ranked search suggestion.
1196 // For example, prevent a search for "foo.com" from outranking another
1197 // provider's navigation for "foo.com" or "foo.com/url_from_history".
[email protected]188b50c2013-03-28 07:19:421198 ApplyCalculatedSuggestRelevance(&keyword_suggest_results_);
1199 ApplyCalculatedSuggestRelevance(&default_suggest_results_);
[email protected]dab8d52d2013-03-05 07:35:281200 default_verbatim_relevance_ = -1;
1201 keyword_verbatim_relevance_ = -1;
[email protected]344946a12012-12-20 12:03:421202 ConvertResultsToAutocompleteMatches();
[email protected]382a0642012-06-06 06:13:521203 }
[email protected]344946a12012-12-20 12:03:421204 if (IsTopMatchNotInlinable()) {
[email protected]5423e562013-02-07 03:58:451205 // Disregard suggested relevances if the top match is not a verbatim
1206 // match, inlinable, or URL_WHAT_YOU_TYPED (which may be top match
1207 // regardless of inlining). For example, input "foo" should not
1208 // invoke a search for "bar", which would happen if the "bar" search
1209 // match outranked all other matches.
[email protected]344946a12012-12-20 12:03:421210 ApplyCalculatedRelevance();
1211 ConvertResultsToAutocompleteMatches();
[email protected]382a0642012-06-06 06:13:521212 }
[email protected]9dfb4d362013-04-05 02:15:121213 DCHECK(!IsTopMatchNavigationInKeywordMode());
[email protected]344946a12012-12-20 12:03:421214 DCHECK(!IsTopMatchScoreTooLow());
1215 DCHECK(!IsTopMatchHighRankSearchForURL());
1216 DCHECK(!IsTopMatchNotInlinable());
[email protected]d1f0a7f2012-06-05 10:26:421217 }
1218
[email protected]cc63dea2008-08-21 20:56:311219 UpdateStarredStateOfMatches();
[email protected]4ab4c7c2010-11-24 04:49:341220 UpdateDone();
[email protected]257ab712009-04-14 17:16:241221}
1222
1223void SearchProvider::AddNavigationResultsToMatches(
1224 const NavigationResults& navigation_results,
1225 bool is_keyword) {
[email protected]c112f0fe72013-01-18 20:30:091226 if (navigation_results.empty())
1227 return;
1228
[email protected]dab8d52d2013-03-05 07:35:281229 if (is_keyword ?
1230 has_keyword_suggested_relevance_ : has_default_suggested_relevance_) {
[email protected]c112f0fe72013-01-18 20:30:091231 for (NavigationResults::const_iterator it = navigation_results.begin();
1232 it != navigation_results.end(); ++it)
[email protected]188b50c2013-03-28 07:19:421233 matches_.push_back(NavigationToMatch(*it));
[email protected]c112f0fe72013-01-18 20:30:091234 } else {
[email protected]9dfb4d362013-04-05 02:15:121235 // Pick the highest-scoring element only in absence of the
1236 // suggested relevance scores. (The results are already sorted.)
[email protected]6c535842012-05-15 05:20:551237 // TODO(kochi|msw): Add more navigational results if they get more
1238 // meaningful relevance values; see http://b/1170574.
[email protected]9dfb4d362013-04-05 02:15:121239 matches_.push_back(NavigationToMatch(navigation_results.front()));
[email protected]257ab712009-04-14 17:16:241240 }
1241}
1242
1243void SearchProvider::AddHistoryResultsToMap(const HistoryResults& results,
1244 bool is_keyword,
1245 int did_not_accept_suggestion,
1246 MatchMap* map) {
[email protected]51124552011-07-16 01:37:101247 if (results.empty())
1248 return;
1249
[email protected]d7ad4772012-06-01 03:12:541250 bool prevent_inline_autocomplete = input_.prevent_inline_autocomplete() ||
1251 (input_.type() == AutocompleteInput::URL);
[email protected]14710852013-02-05 23:45:411252 const string16& input_text =
1253 is_keyword ? keyword_input_.text() : input_.text();
[email protected]51124552011-07-16 01:37:101254 bool input_multiple_words = HasMultipleWords(input_text);
1255
[email protected]55ce8f12012-05-09 04:44:081256 SuggestResults scored_results;
1257 if (!prevent_inline_autocomplete && input_multiple_words) {
1258 // ScoreHistoryResults() allows autocompletion of multi-word, 1-visit
1259 // queries if the input also has multiple words. But if we were already
[email protected]51124552011-07-16 01:37:101260 // autocompleting a multi-word, multi-visit query, and the current input is
1261 // still a prefix of it, then changing the autocompletion suddenly feels
1262 // wrong. To detect this case, first score as if only one word has been
1263 // typed, then check for a best result that is an autocompleted, multi-word
1264 // query. If we find one, then just keep that score set.
[email protected]55ce8f12012-05-09 04:44:081265 scored_results = ScoreHistoryResults(results, prevent_inline_autocomplete,
1266 false, input_text, is_keyword);
[email protected]9dfb4d362013-04-05 02:15:121267 if ((scored_results.front().relevance() <
[email protected]55ce8f12012-05-09 04:44:081268 AutocompleteResult::kLowestDefaultScore) ||
[email protected]9dfb4d362013-04-05 02:15:121269 !HasMultipleWords(scored_results.front().suggestion()))
[email protected]55ce8f12012-05-09 04:44:081270 scored_results.clear(); // Didn't detect the case above, score normally.
[email protected]51124552011-07-16 01:37:101271 }
[email protected]55ce8f12012-05-09 04:44:081272 if (scored_results.empty())
1273 scored_results = ScoreHistoryResults(results, prevent_inline_autocomplete,
1274 input_multiple_words, input_text,
1275 is_keyword);
1276 for (SuggestResults::const_iterator i(scored_results.begin());
1277 i != scored_results.end(); ++i) {
1278 AddMatchToMap(i->suggestion(), input_text, i->relevance(),
[email protected]51124552011-07-16 01:37:101279 AutocompleteMatch::SEARCH_HISTORY, did_not_accept_suggestion,
[email protected]55ce8f12012-05-09 04:44:081280 is_keyword, map);
[email protected]51124552011-07-16 01:37:101281 }
1282}
1283
[email protected]55ce8f12012-05-09 04:44:081284SearchProvider::SuggestResults SearchProvider::ScoreHistoryResults(
[email protected]51124552011-07-16 01:37:101285 const HistoryResults& results,
1286 bool base_prevent_inline_autocomplete,
1287 bool input_multiple_words,
1288 const string16& input_text,
1289 bool is_keyword) {
[email protected]810ffba2012-06-12 01:07:481290 AutocompleteClassifier* classifier =
1291 AutocompleteClassifierFactory::GetForProfile(profile_);
[email protected]55ce8f12012-05-09 04:44:081292 SuggestResults scored_results;
[email protected]257ab712009-04-14 17:16:241293 for (HistoryResults::const_iterator i(results.begin()); i != results.end();
1294 ++i) {
[email protected]51124552011-07-16 01:37:101295 // Don't autocomplete multi-word queries that have only been seen once
1296 // unless the user has typed more than one word.
1297 bool prevent_inline_autocomplete = base_prevent_inline_autocomplete ||
1298 (!input_multiple_words && (i->visits < 2) && HasMultipleWords(i->term));
1299
[email protected]ea3b9a502011-04-04 14:19:371300 // Don't autocomplete search terms that would normally be treated as URLs
[email protected]51124552011-07-16 01:37:101301 // when typed. For example, if the user searched for "google.com" and types
1302 // "goog", don't autocomplete to the search term "google.com". Otherwise,
1303 // the input will look like a URL but act like a search, which is confusing.
[email protected]cc447362011-04-06 03:57:481304 // NOTE: We don't check this in the following cases:
1305 // * When inline autocomplete is disabled, we won't be inline
1306 // autocompleting this term, so we don't need to worry about confusion as
1307 // much. This also prevents calling Classify() again from inside the
1308 // classifier (which will corrupt state and likely crash), since the
[email protected]51124552011-07-16 01:37:101309 // classifier always disables inline autocomplete.
[email protected]cc447362011-04-06 03:57:481310 // * When the user has typed the whole term, the "what you typed" history
1311 // match will outrank us for URL-like inputs anyway, so we need not do
1312 // anything special.
[email protected]51124552011-07-16 01:37:101313 if (!prevent_inline_autocomplete && classifier && (i->term != input_text)) {
[email protected]ea3b9a502011-04-04 14:19:371314 AutocompleteMatch match;
[email protected]f608ea102013-03-18 15:08:091315 classifier->Classify(i->term, false, false, &match, NULL);
[email protected]2905f742011-10-13 03:51:581316 prevent_inline_autocomplete =
[email protected]749e7ae02012-09-05 18:47:461317 !AutocompleteMatch::IsSearchType(match.type);
[email protected]ea3b9a502011-04-04 14:19:371318 }
[email protected]51124552011-07-16 01:37:101319
1320 int relevance = CalculateRelevanceForHistory(i->time, is_keyword,
1321 prevent_inline_autocomplete);
[email protected]188b50c2013-03-28 07:19:421322 scored_results.push_back(SuggestResult(i->term, is_keyword, relevance));
[email protected]257ab712009-04-14 17:16:241323 }
[email protected]51124552011-07-16 01:37:101324
1325 // History returns results sorted for us. However, we may have docked some
1326 // results' scores, so things are no longer in order. Do a stable sort to get
1327 // things back in order without otherwise disturbing results with equal
1328 // scores, then force the scores to be unique, so that the order in which
1329 // they're shown is deterministic.
[email protected]55ce8f12012-05-09 04:44:081330 std::stable_sort(scored_results.begin(), scored_results.end(),
1331 CompareScoredResults());
[email protected]51124552011-07-16 01:37:101332 int last_relevance = 0;
[email protected]55ce8f12012-05-09 04:44:081333 for (SuggestResults::iterator i(scored_results.begin());
1334 i != scored_results.end(); ++i) {
1335 if ((i != scored_results.begin()) && (i->relevance() >= last_relevance))
1336 i->set_relevance(last_relevance - 1);
1337 last_relevance = i->relevance();
[email protected]51124552011-07-16 01:37:101338 }
1339
[email protected]55ce8f12012-05-09 04:44:081340 return scored_results;
[email protected]257ab712009-04-14 17:16:241341}
1342
[email protected]55ce8f12012-05-09 04:44:081343void SearchProvider::AddSuggestResultsToMap(const SuggestResults& results,
[email protected]55ce8f12012-05-09 04:44:081344 MatchMap* map) {
[email protected]55ce8f12012-05-09 04:44:081345 for (size_t i = 0; i < results.size(); ++i) {
[email protected]188b50c2013-03-28 07:19:421346 const bool is_keyword = results[i].from_keyword_provider();
1347 const string16& input = is_keyword ? keyword_input_.text() : input_.text();
1348 AddMatchToMap(results[i].suggestion(), input, results[i].relevance(),
[email protected]55ce8f12012-05-09 04:44:081349 AutocompleteMatch::SEARCH_SUGGEST, i, is_keyword, map);
[email protected]257ab712009-04-14 17:16:241350 }
initial.commit09911bf2008-07-26 23:55:291351}
1352
[email protected]382a0642012-06-06 06:13:521353int SearchProvider::GetVerbatimRelevance() const {
[email protected]dc6943b2012-06-19 06:39:561354 // Use the suggested verbatim relevance score if it is non-negative (valid),
1355 // if inline autocomplete isn't prevented (always show verbatim on backspace),
[email protected]1beee342012-06-19 22:22:281356 // and if it won't suppress verbatim, leaving no default provider matches.
1357 // Otherwise, if the default provider returned no matches and was still able
[email protected]dc6943b2012-06-19 06:39:561358 // to suppress verbatim, the user would have no search/nav matches and may be
[email protected]1beee342012-06-19 22:22:281359 // left unable to search using their default provider from the omnibox.
[email protected]dc6943b2012-06-19 06:39:561360 // Check for results on each verbatim calculation, as results from older
1361 // queries (on previous input) may be trimmed for failing to inline new input.
[email protected]dab8d52d2013-03-05 07:35:281362 if (default_verbatim_relevance_ >= 0 &&
1363 !input_.prevent_inline_autocomplete() &&
1364 (default_verbatim_relevance_ > 0 ||
[email protected]1beee342012-06-19 22:22:281365 !default_suggest_results_.empty() ||
[email protected]dc6943b2012-06-19 06:39:561366 !default_navigation_results_.empty())) {
[email protected]dab8d52d2013-03-05 07:35:281367 return default_verbatim_relevance_;
[email protected]dc6943b2012-06-19 06:39:561368 }
[email protected]382a0642012-06-06 06:13:521369 return CalculateRelevanceForVerbatim();
1370}
[email protected]d1f0a7f2012-06-05 10:26:421371
[email protected]382a0642012-06-06 06:13:521372int SearchProvider::CalculateRelevanceForVerbatim() const {
[email protected]85b8d6f2012-05-08 20:53:471373 if (!providers_.keyword_provider().empty())
[email protected]52d08b12009-10-19 18:42:361374 return 250;
[email protected]dab8d52d2013-03-05 07:35:281375 return CalculateRelevanceForVerbatimIgnoringKeywordModeState();
1376}
[email protected]52d08b12009-10-19 18:42:361377
[email protected]dab8d52d2013-03-05 07:35:281378int SearchProvider::
1379 CalculateRelevanceForVerbatimIgnoringKeywordModeState() const {
initial.commit09911bf2008-07-26 23:55:291380 switch (input_.type()) {
1381 case AutocompleteInput::UNKNOWN:
[email protected]52d08b12009-10-19 18:42:361382 case AutocompleteInput::QUERY:
1383 case AutocompleteInput::FORCED_QUERY:
[email protected]90fe2bb2013-01-15 03:42:131384 return kNonURLVerbatimRelevance;
initial.commit09911bf2008-07-26 23:55:291385
initial.commit09911bf2008-07-26 23:55:291386 case AutocompleteInput::URL:
[email protected]52d08b12009-10-19 18:42:361387 return 850;
initial.commit09911bf2008-07-26 23:55:291388
1389 default:
1390 NOTREACHED();
1391 return 0;
1392 }
1393}
1394
[email protected]dab8d52d2013-03-05 07:35:281395int SearchProvider::GetKeywordVerbatimRelevance() const {
1396 // Use the suggested verbatim relevance score if it is non-negative (valid),
1397 // if inline autocomplete isn't prevented (always show verbatim on backspace),
1398 // and if it won't suppress verbatim, leaving no keyword provider matches.
1399 // Otherwise, if the keyword provider returned no matches and was still able
1400 // to suppress verbatim, the user would have no search/nav matches and may be
1401 // left unable to search using their keyword provider from the omnibox.
1402 // Check for results on each verbatim calculation, as results from older
1403 // queries (on previous input) may be trimmed for failing to inline new input.
1404 if (keyword_verbatim_relevance_ >= 0 &&
1405 !input_.prevent_inline_autocomplete() &&
1406 (keyword_verbatim_relevance_ > 0 ||
1407 !keyword_suggest_results_.empty() ||
1408 !keyword_navigation_results_.empty())) {
1409 return keyword_verbatim_relevance_;
1410 }
1411 return CalculateRelevanceForKeywordVerbatim(
1412 keyword_input_.type(), keyword_input_.prefer_keyword());
1413}
1414
[email protected]5423e562013-02-07 03:58:451415// static
1416int SearchProvider::CalculateRelevanceForKeywordVerbatim(
1417 AutocompleteInput::Type type,
1418 bool prefer_keyword) {
1419 // This function is responsible for scoring verbatim query matches
1420 // for non-extension keywords. KeywordProvider::CalculateRelevance()
1421 // scores verbatim query matches for extension keywords, as well as
1422 // for keyword matches (i.e., suggestions of a keyword itself, not a
1423 // suggestion of a query on a keyword search engine). These two
1424 // functions are currently in sync, but there's no reason we
1425 // couldn't decide in the future to score verbatim matches
1426 // differently for extension and non-extension keywords. If you
1427 // make such a change, however, you should update this comment to
1428 // describe it, so it's clear why the functions diverge.
1429 if (prefer_keyword)
1430 return 1500;
1431 return (type == AutocompleteInput::QUERY) ? 1450 : 1100;
1432}
1433
[email protected]51124552011-07-16 01:37:101434int SearchProvider::CalculateRelevanceForHistory(
1435 const Time& time,
1436 bool is_keyword,
1437 bool prevent_inline_autocomplete) const {
[email protected]aa613d62010-11-09 20:40:181438 // The relevance of past searches falls off over time. There are two distinct
1439 // equations used. If the first equation is used (searches to the primary
[email protected]51124552011-07-16 01:37:101440 // provider that we want to inline autocomplete), the score starts at 1399 and
1441 // falls to 1300. If the second equation is used the relevance of a search 15
1442 // minutes ago is discounted 50 points, while the relevance of a search two
1443 // weeks ago is discounted 450 points.
[email protected]aa613d62010-11-09 20:40:181444 double elapsed_time = std::max((Time::Now() - time).InSecondsF(), 0.);
[email protected]188b50c2013-03-28 07:19:421445 bool is_primary_provider = is_keyword || !providers_.has_keyword_provider();
[email protected]51124552011-07-16 01:37:101446 if (is_primary_provider && !prevent_inline_autocomplete) {
[email protected]aa613d62010-11-09 20:40:181447 // Searches with the past two days get a different curve.
[email protected]51124552011-07-16 01:37:101448 const double autocomplete_time = 2 * 24 * 60 * 60;
[email protected]aa613d62010-11-09 20:40:181449 if (elapsed_time < autocomplete_time) {
[email protected]e17511f2011-07-13 14:09:181450 return (is_keyword ? 1599 : 1399) - static_cast<int>(99 *
[email protected]aa613d62010-11-09 20:40:181451 std::pow(elapsed_time / autocomplete_time, 2.5));
1452 }
1453 elapsed_time -= autocomplete_time;
1454 }
1455
[email protected]c3a4bd992010-08-18 20:25:011456 const int score_discount =
1457 static_cast<int>(6.5 * std::pow(elapsed_time, 0.3));
initial.commit09911bf2008-07-26 23:55:291458
[email protected]6c85aa02009-02-27 12:08:091459 // Don't let scores go below 0. Negative relevance scores are meaningful in
1460 // a different way.
initial.commit09911bf2008-07-26 23:55:291461 int base_score;
[email protected]51124552011-07-16 01:37:101462 if (is_primary_provider)
[email protected]52d08b12009-10-19 18:42:361463 base_score = (input_.type() == AutocompleteInput::URL) ? 750 : 1050;
[email protected]51124552011-07-16 01:37:101464 else
1465 base_score = 200;
initial.commit09911bf2008-07-26 23:55:291466 return std::max(0, base_score - score_discount);
1467}
1468
[email protected]a2fedb1e2011-01-25 15:23:361469void SearchProvider::AddMatchToMap(const string16& query_string,
1470 const string16& input_text,
initial.commit09911bf2008-07-26 23:55:291471 int relevance,
[email protected]4c1fb7ec2008-11-13 00:19:001472 AutocompleteMatch::Type type,
initial.commit09911bf2008-07-26 23:55:291473 int accepted_suggestion,
[email protected]257ab712009-04-14 17:16:241474 bool is_keyword,
initial.commit09911bf2008-07-26 23:55:291475 MatchMap* map) {
[email protected]4eeb54f92013-04-27 04:01:201476 // With Instant Extended, we never want to inline autocomplete search queries
1477 // -- they should always use grey text if they are to autocomplete at all. So
1478 // we clamp non-verbatim results to just below the verbatim score to ensure
1479 // that none of them are inline autocompleted.
1480 if ((type != AutocompleteMatch::SEARCH_WHAT_YOU_TYPED) &&
1481 chrome::IsInstantExtendedAPIEnabled()) {
1482 relevance = std::min(kNonURLVerbatimRelevance - 1, relevance);
1483 }
[email protected]cb86ee6f2013-04-28 16:58:151484
1485 const string16& keyword = is_keyword ?
[email protected]3954c3a2012-04-10 20:17:551486 providers_.keyword_provider() : providers_.default_provider();
[email protected]cb86ee6f2013-04-28 16:58:151487 AutocompleteMatch match = CreateSearchSuggestion(profile_, this, input_,
1488 query_string, input_text, relevance, type, accepted_suggestion,
1489 is_keyword, keyword);
1490 if (!match.destination_url.is_valid())
[email protected]85b8d6f2012-05-08 20:53:471491 return;
1492
initial.commit09911bf2008-07-26 23:55:291493 // Try to add |match| to |map|. If a match for |query_string| is already in
1494 // |map|, replace it if |match| is more relevant.
1495 // NOTE: Keep this ToLower() call in sync with url_database.cc.
1496 const std::pair<MatchMap::iterator, bool> i = map->insert(
[email protected]a2fedb1e2011-01-25 15:23:361497 std::pair<string16, AutocompleteMatch>(
[email protected]503d03872011-05-06 08:36:261498 base::i18n::ToLower(query_string), match));
initial.commit09911bf2008-07-26 23:55:291499 // NOTE: We purposefully do a direct relevance comparison here instead of
1500 // using AutocompleteMatch::MoreRelevant(), so that we'll prefer "items added
1501 // first" rather than "items alphabetically first" when the scores are equal.
1502 // The only case this matters is when a user has results with the same score
1503 // that differ only by capitalization; because the history system returns
1504 // results sorted by recency, this means we'll pick the most recent such
1505 // result even if the precision of our relevance score is too low to
1506 // distinguish the two.
1507 if (!i.second && (match.relevance > i.first->second.relevance))
1508 i.first->second = match;
1509}
1510
1511AutocompleteMatch SearchProvider::NavigationToMatch(
[email protected]188b50c2013-03-28 07:19:421512 const NavigationResult& navigation) {
1513 const string16& input = navigation.from_keyword_provider() ?
1514 keyword_input_.text() : input_.text();
[email protected]55ce8f12012-05-09 04:44:081515 AutocompleteMatch match(this, navigation.relevance(), false,
[email protected]4c1fb7ec2008-11-13 00:19:001516 AutocompleteMatch::NAVSUGGEST);
[email protected]55ce8f12012-05-09 04:44:081517 match.destination_url = navigation.url();
[email protected]371dab12012-06-01 03:23:551518
1519 // First look for the user's input inside the fill_into_edit as it would be
1520 // without trimming the scheme, so we can find matches at the beginning of the
1521 // scheme.
[email protected]a1b5e862013-03-29 06:38:441522 const string16& untrimmed_fill_into_edit = navigation.formatted_url();
[email protected]371dab12012-06-01 03:23:551523 const URLPrefix* prefix =
1524 URLPrefix::BestURLPrefix(untrimmed_fill_into_edit, input);
1525 size_t match_start = (prefix == NULL) ?
1526 untrimmed_fill_into_edit.find(input) : prefix->prefix.length();
1527 size_t inline_autocomplete_offset = (prefix == NULL) ?
1528 string16::npos : (match_start + input.length());
1529 bool trim_http = !HasHTTPScheme(input) && (!prefix || (match_start != 0));
1530
1531 // Preserve the forced query '?' prefix in |match.fill_into_edit|.
1532 // Otherwise, user edits to a suggestion would show non-Search results.
1533 if (input_.type() == AutocompleteInput::FORCED_QUERY) {
1534 match.fill_into_edit = ASCIIToUTF16("?");
1535 if (inline_autocomplete_offset != string16::npos)
1536 ++inline_autocomplete_offset;
1537 }
1538
1539 const std::string languages(
1540 profile_->GetPrefs()->GetString(prefs::kAcceptLanguages));
1541 const net::FormatUrlTypes format_types =
1542 net::kFormatUrlOmitAll & ~(trim_http ? 0 : net::kFormatUrlOmitHTTP);
1543 match.fill_into_edit +=
1544 AutocompleteInput::FormattedStringWithEquivalentMeaning(navigation.url(),
1545 net::FormatUrl(navigation.url(), languages, format_types,
1546 net::UnescapeRule::SPACES, NULL, NULL,
1547 &inline_autocomplete_offset));
1548 if (!input_.prevent_inline_autocomplete())
1549 match.inline_autocomplete_offset = inline_autocomplete_offset;
1550 DCHECK((match.inline_autocomplete_offset == string16::npos) ||
1551 (match.inline_autocomplete_offset <= match.fill_into_edit.length()));
1552
1553 match.contents = net::FormatUrl(navigation.url(), languages,
1554 format_types, net::UnescapeRule::SPACES, NULL, NULL, &match_start);
1555 // If the first match in the untrimmed string was inside a scheme that we
1556 // trimmed, look for a subsequent match.
1557 if (match_start == string16::npos)
1558 match_start = match.contents.find(input);
1559 // Safe if |match_start| is npos; also safe if the input is longer than the
1560 // remaining contents after |match_start|.
1561 AutocompleteMatch::ClassifyLocationInString(match_start, input.length(),
1562 match.contents.length(), ACMatchClassification::URL,
1563 &match.contents_class);
initial.commit09911bf2008-07-26 23:55:291564
[email protected]55ce8f12012-05-09 04:44:081565 match.description = navigation.description();
[email protected]371dab12012-06-01 03:23:551566 AutocompleteMatch::ClassifyMatchInString(input, match.description,
1567 ACMatchClassification::NONE, &match.description_class);
initial.commit09911bf2008-07-26 23:55:291568 return match;
1569}
[email protected]4ab4c7c2010-11-24 04:49:341570
[email protected]9dfb4d362013-04-05 02:15:121571void SearchProvider::DemoteKeywordNavigationMatchesPastTopQuery() {
[email protected]d519d392013-03-27 09:24:461572 // First, determine the maximum score of any keyword query match (verbatim or
1573 // query suggestion).
1574 int max_query_relevance = GetKeywordVerbatimRelevance();
1575 if (!keyword_suggest_results_.empty()) {
[email protected]d519d392013-03-27 09:24:461576 max_query_relevance =
[email protected]9dfb4d362013-04-05 02:15:121577 std::max(keyword_suggest_results_.front().relevance(),
1578 max_query_relevance);
[email protected]d519d392013-03-27 09:24:461579 }
1580 // If no query is supposed to appear, then navigational matches cannot
[email protected]9dfb4d362013-04-05 02:15:121581 // be demoted past it. Get rid of suggested relevance scores for
1582 // navsuggestions and introduce the verbatim results again. The keyword
1583 // verbatim match will outscore the navsuggest matches.
1584 if (max_query_relevance == 0) {
1585 ApplyCalculatedNavigationRelevance(&keyword_navigation_results_);
1586 ApplyCalculatedNavigationRelevance(&default_navigation_results_);
1587 keyword_verbatim_relevance_ = -1;
1588 default_verbatim_relevance_ = -1;
1589 return;
1590 }
[email protected]d519d392013-03-27 09:24:461591 // Now we know we can enforce the minimum score constraint even after
1592 // the navigation matches are demoted. Proceed to demote the navigation
1593 // matches to enforce the query-must-come-first constraint.
[email protected]d519d392013-03-27 09:24:461594 // Cap the relevance score of all results.
1595 for (NavigationResults::iterator it = keyword_navigation_results_.begin();
1596 it != keyword_navigation_results_.end(); ++it) {
[email protected]9dfb4d362013-04-05 02:15:121597 if (it->relevance() < max_query_relevance)
1598 return;
1599 max_query_relevance = std::max(max_query_relevance - 1, 0);
1600 it->set_relevance(max_query_relevance);
[email protected]d519d392013-03-27 09:24:461601 }
[email protected]d519d392013-03-27 09:24:461602}
1603
[email protected]4ab4c7c2010-11-24 04:49:341604void SearchProvider::UpdateDone() {
[email protected]2cdf1172012-08-26 12:21:331605 // We're done when the timer isn't running, there are no suggest queries
[email protected]5fac3782013-03-06 09:32:311606 // pending, and we're not waiting on Instant.
[email protected]abe441e2013-05-06 12:35:051607 done_ = IsNonInstantSearchDone() &&
1608 (instant_finalized_ || !chrome::IsInstantEnabled(profile_));
[email protected]4ab4c7c2010-11-24 04:49:341609}