blob: f1d7ea1a6a04f1dac1728b7c80e1dd34a3c12bf1 [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]618d6e62012-12-16 05:55:57226 instant_finalized_(false),
227 field_trial_triggered_(false),
[email protected]9a091392013-05-04 14:27:24228 field_trial_triggered_in_session_(false),
229 suppress_search_suggestions_(false) {
[email protected]4ab4c7c2010-11-24 04:49:34230}
231
[email protected]a2fedb1e2011-01-25 15:23:36232void SearchProvider::FinalizeInstantQuery(const string16& input_text,
[email protected]93b73832012-10-18 20:18:38233 const InstantSuggestion& suggestion) {
[email protected]4ab4c7c2010-11-24 04:49:34234 if (done_ || instant_finalized_)
235 return;
236
237 instant_finalized_ = true;
238 UpdateDone();
239
[email protected]e918c112010-12-08 23:03:49240 if (input_text.empty()) {
[email protected]4ab4c7c2010-11-24 04:49:34241 // We only need to update the listener if we're actually done.
242 if (done_)
243 listener_->OnProviderUpdate(false);
244 return;
245 }
246
[email protected]93b73832012-10-18 20:18:38247 default_provider_suggestion_ = suggestion;
[email protected]9e789742011-01-10 23:27:32248
[email protected]a2fedb1e2011-01-25 15:23:36249 string16 adjusted_input_text(input_text);
[email protected]e918c112010-12-08 23:03:49250 AutocompleteInput::RemoveForcedQueryStringIfNecessary(input_.type(),
251 &adjusted_input_text);
252
[email protected]93b73832012-10-18 20:18:38253 const string16 text = adjusted_input_text + suggestion.text;
[email protected]9acdcdc02012-05-21 20:58:36254 bool results_updated = false;
[email protected]4ab4c7c2010-11-24 04:49:34255 // Remove any matches that are identical to |text|. We don't use the
256 // destination_url for comparison as it varies depending upon the index passed
257 // to TemplateURL::ReplaceSearchTerms.
258 for (ACMatches::iterator i = matches_.begin(); i != matches_.end();) {
[email protected]b7f64d742013-05-21 04:04:04259 if (((i->type == AutocompleteMatchType::SEARCH_HISTORY) ||
260 (i->type == AutocompleteMatchType::SEARCH_SUGGEST)) &&
[email protected]4ab4c7c2010-11-24 04:49:34261 (i->fill_into_edit == text)) {
[email protected]e030de62010-11-24 05:41:19262 i = matches_.erase(i);
[email protected]9acdcdc02012-05-21 20:58:36263 results_updated = true;
[email protected]4ab4c7c2010-11-24 04:49:34264 } else {
265 ++i;
266 }
267 }
268
[email protected]5fac3782013-03-06 09:32:31269 // Add the new Instant suggest result.
[email protected]93b73832012-10-18 20:18:38270 if (suggestion.type == INSTANT_SUGGESTION_SEARCH) {
[email protected]90fe2bb2013-01-15 03:42:13271 // Instant has a query suggestion. Rank it higher than SEARCH_WHAT_YOU_TYPED
272 // so that it gets autocompleted.
273 const int verbatim_relevance = GetVerbatimRelevance();
[email protected]cc1526e2013-05-17 04:04:24274 int did_not_accept_default_suggestion =
275 default_results_.suggest_results.empty() ?
[email protected]4ab4c7c2010-11-24 04:49:34276 TemplateURLRef::NO_SUGGESTIONS_AVAILABLE :
277 TemplateURLRef::NO_SUGGESTION_CHOSEN;
[email protected]93b73832012-10-18 20:18:38278 MatchMap match_map;
279 AddMatchToMap(text, adjusted_input_text, verbatim_relevance + 1,
[email protected]b7f64d742013-05-21 04:04:04280 AutocompleteMatchType::SEARCH_SUGGEST,
[email protected]93b73832012-10-18 20:18:38281 did_not_accept_default_suggestion, false, &match_map);
282 if (!match_map.empty()) {
283 matches_.push_back(match_map.begin()->second);
284 results_updated = true;
285 }
286 } else {
[email protected]c112f0fe72013-01-18 20:30:09287 // Instant has a URL suggestion. Rank it higher than URL_WHAT_YOU_TYPED so
[email protected]90fe2bb2013-01-15 03:42:13288 // it gets autocompleted; use kNonURLVerbatimRelevance rather than
289 // verbatim_relevance so that the score does not change if the user keeps
290 // typing and the input changes from type UNKNOWN to URL.
[email protected]93b73832012-10-18 20:18:38291 matches_.push_back(NavigationToMatch(
[email protected]a1b5e862013-03-29 06:38:44292 NavigationResult(*this,
293 GURL(UTF16ToUTF8(suggestion.text)),
[email protected]93b73832012-10-18 20:18:38294 string16(),
[email protected]188b50c2013-03-28 07:19:42295 false,
296 kNonURLVerbatimRelevance + 1)));
[email protected]9acdcdc02012-05-21 20:58:36297 results_updated = true;
298 }
[email protected]4ab4c7c2010-11-24 04:49:34299
[email protected]9acdcdc02012-05-21 20:58:36300 if (results_updated || done_)
301 listener_->OnProviderUpdate(results_updated);
[email protected]601858c02010-09-01 17:08:20302}
303
[email protected]0a633ba92013-03-26 09:13:47304void SearchProvider::ClearInstantSuggestion() {
305 default_provider_suggestion_ = InstantSuggestion();
306 if (done_ || instant_finalized_)
307 return;
308 instant_finalized_ = true;
309 UpdateMatches();
310 listener_->OnProviderUpdate(true);
311}
312
[email protected]9a091392013-05-04 14:27:24313void SearchProvider::SuppressSearchSuggestions() {
314 suppress_search_suggestions_ = true;
315}
316
initial.commit09911bf2008-07-26 23:55:29317void SearchProvider::Start(const AutocompleteInput& input,
[email protected]8deeb952008-10-09 18:21:27318 bool minimal_changes) {
[email protected]9a091392013-05-04 14:27:24319 const bool suppress_search_suggestions = suppress_search_suggestions_;
320 suppress_search_suggestions_ = false;
321
[email protected]04504c242013-01-22 21:08:55322 // Do our best to load the model as early as possible. This will reduce
323 // odds of having the model not ready when really needed (a non-empty input).
324 TemplateURLService* model = providers_.template_url_service();
325 DCHECK(model);
326 model->Load();
327
initial.commit09911bf2008-07-26 23:55:29328 matches_.clear();
[email protected]618d6e62012-12-16 05:55:57329 field_trial_triggered_ = false;
initial.commit09911bf2008-07-26 23:55:29330
[email protected]ea3b9a502011-04-04 14:19:37331 instant_finalized_ =
332 (input.matches_requested() != AutocompleteInput::ALL_MATCHES);
[email protected]4ab4c7c2010-11-24 04:49:34333
[email protected]6c85aa02009-02-27 12:08:09334 // Can't return search/suggest results for bogus input or without a profile.
initial.commit09911bf2008-07-26 23:55:29335 if (!profile_ || (input.type() == AutocompleteInput::INVALID)) {
[email protected]e29249dc52012-07-19 17:33:50336 Stop(false);
initial.commit09911bf2008-07-26 23:55:29337 return;
338 }
339
[email protected]14710852013-02-05 23:45:41340 keyword_input_ = input;
[email protected]257ab712009-04-14 17:16:24341 const TemplateURL* keyword_provider =
[email protected]14710852013-02-05 23:45:41342 KeywordProvider::GetSubstitutingTemplateURLForInput(model,
343 &keyword_input_);
344 if (keyword_provider == NULL)
345 keyword_input_.Clear();
346 else if (keyword_input_.text().empty())
[email protected]257ab712009-04-14 17:16:24347 keyword_provider = NULL;
[email protected]257ab712009-04-14 17:16:24348
[email protected]85b8d6f2012-05-08 20:53:47349 const TemplateURL* default_provider = model->GetDefaultSearchProvider();
[email protected]9b74ab52012-03-30 16:08:07350 if (default_provider && !default_provider->SupportsReplacement())
[email protected]257ab712009-04-14 17:16:24351 default_provider = NULL;
352
353 if (keyword_provider == default_provider)
[email protected]e17511f2011-07-13 14:09:18354 default_provider = NULL; // No use in querying the same provider twice.
[email protected]257ab712009-04-14 17:16:24355
356 if (!default_provider && !keyword_provider) {
357 // No valid providers.
[email protected]e29249dc52012-07-19 17:33:50358 Stop(false);
initial.commit09911bf2008-07-26 23:55:29359 return;
360 }
361
362 // If we're still running an old query but have since changed the query text
[email protected]257ab712009-04-14 17:16:24363 // or the providers, abort the query.
[email protected]85b8d6f2012-05-08 20:53:47364 string16 default_provider_keyword(default_provider ?
365 default_provider->keyword() : string16());
366 string16 keyword_provider_keyword(keyword_provider ?
367 keyword_provider->keyword() : string16());
[email protected]9e789742011-01-10 23:27:32368 if (!minimal_changes ||
[email protected]85b8d6f2012-05-08 20:53:47369 !providers_.equal(default_provider_keyword, keyword_provider_keyword)) {
[email protected]bb900e02013-03-14 14:15:29370 // If Instant has not come back with a suggestion, adjust the previous
371 // suggestion if possible. If |instant_finalized| is true, we are looking
372 // for synchronous matches only, so the suggestion is cleared.
373 if (instant_finalized_)
[email protected]93b73832012-10-18 20:18:38374 default_provider_suggestion_ = InstantSuggestion();
[email protected]9e789742011-01-10 23:27:32375 else
[email protected]bb900e02013-03-14 14:15:29376 AdjustDefaultProviderSuggestion(input_.text(), input.text());
377
378 // Cancel any in-flight suggest requests.
379 if (!done_) {
380 // The Stop(false) call below clears |default_provider_suggestion_|, but
381 // in this instance we do not want to clear cached results, so we
382 // restore it.
383 base::AutoReset<InstantSuggestion> reset(&default_provider_suggestion_,
384 InstantSuggestion());
[email protected]e29249dc52012-07-19 17:33:50385 Stop(false);
[email protected]bb900e02013-03-14 14:15:29386 }
[email protected]257ab712009-04-14 17:16:24387 }
initial.commit09911bf2008-07-26 23:55:29388
[email protected]85b8d6f2012-05-08 20:53:47389 providers_.set(default_provider_keyword, keyword_provider_keyword);
initial.commit09911bf2008-07-26 23:55:29390
391 if (input.text().empty()) {
392 // User typed "?" alone. Give them a placeholder result indicating what
393 // this syntax does.
[email protected]257ab712009-04-14 17:16:24394 if (default_provider) {
[email protected]69c579e2010-04-23 20:01:00395 AutocompleteMatch match;
396 match.provider = this;
[email protected]a2fedb1e2011-01-25 15:23:36397 match.contents.assign(l10n_util::GetStringUTF16(IDS_EMPTY_KEYWORD_VALUE));
[email protected]257ab712009-04-14 17:16:24398 match.contents_class.push_back(
[email protected]2c33dd22010-02-11 21:46:35399 ACMatchClassification(0, ACMatchClassification::NONE));
[email protected]85b8d6f2012-05-08 20:53:47400 match.keyword = providers_.default_provider();
[email protected]257ab712009-04-14 17:16:24401 matches_.push_back(match);
402 }
[email protected]e29249dc52012-07-19 17:33:50403 Stop(false);
initial.commit09911bf2008-07-26 23:55:29404 return;
405 }
406
407 input_ = input;
408
[email protected]9a091392013-05-04 14:27:24409 if (!suppress_search_suggestions) {
[email protected]5cd06c3e2012-09-20 03:25:20410 DoHistoryQuery(minimal_changes);
411 StartOrStopSuggestQuery(minimal_changes);
412 }
[email protected]344946a12012-12-20 12:03:42413 UpdateMatches();
initial.commit09911bf2008-07-26 23:55:29414}
415
[email protected]188b50c2013-03-28 07:19:42416SearchProvider::Result::Result(bool from_keyword_provider, int relevance)
417 : from_keyword_provider_(from_keyword_provider),
418 relevance_(relevance) {
419}
420
[email protected]55ce8f12012-05-09 04:44:08421SearchProvider::Result::~Result() {}
422
423SearchProvider::SuggestResult::SuggestResult(const string16& suggestion,
[email protected]188b50c2013-03-28 07:19:42424 bool from_keyword_provider,
[email protected]55ce8f12012-05-09 04:44:08425 int relevance)
[email protected]188b50c2013-03-28 07:19:42426 : Result(from_keyword_provider, relevance),
[email protected]55ce8f12012-05-09 04:44:08427 suggestion_(suggestion) {
428}
429
430SearchProvider::SuggestResult::~SuggestResult() {}
431
[email protected]a1b5e862013-03-29 06:38:44432bool SearchProvider::SuggestResult::IsInlineable(const string16& input) const {
433 return StartsWith(suggestion_, input, false);
434}
435
[email protected]188b50c2013-03-28 07:19:42436int SearchProvider::SuggestResult::CalculateRelevance(
437 const AutocompleteInput& input,
438 bool keyword_provider_requested) const {
439 if (!from_keyword_provider_ && keyword_provider_requested)
440 return 100;
441 return ((input.type() == AutocompleteInput::URL) ? 300 : 600);
442}
443
444SearchProvider::NavigationResult::NavigationResult(
[email protected]a1b5e862013-03-29 06:38:44445 const AutocompleteProvider& provider,
[email protected]188b50c2013-03-28 07:19:42446 const GURL& url,
447 const string16& description,
448 bool from_keyword_provider,
449 int relevance)
450 : Result(from_keyword_provider, relevance),
[email protected]55ce8f12012-05-09 04:44:08451 url_(url),
[email protected]a1b5e862013-03-29 06:38:44452 formatted_url_(AutocompleteInput::FormattedStringWithEquivalentMeaning(
453 url, provider.StringForURLDisplay(url, true, false))),
[email protected]55ce8f12012-05-09 04:44:08454 description_(description) {
455 DCHECK(url_.is_valid());
456}
457
[email protected]a1b5e862013-03-29 06:38:44458SearchProvider::NavigationResult::~NavigationResult() {}
459
460bool SearchProvider::NavigationResult::IsInlineable(
461 const string16& input) const {
462 return URLPrefix::BestURLPrefix(formatted_url_, input) != NULL;
463}
464
[email protected]188b50c2013-03-28 07:19:42465int SearchProvider::NavigationResult::CalculateRelevance(
466 const AutocompleteInput& input,
467 bool keyword_provider_requested) const {
468 return (from_keyword_provider_ || !keyword_provider_requested) ? 800 : 150;
469}
470
[email protected]cc1526e2013-05-17 04:04:24471SearchProvider::Results::Results()
472 : has_suggested_relevance(false),
473 verbatim_relevance(-1) {
474}
475
476SearchProvider::Results::~Results() {
477}
478
479void SearchProvider::Results::Clear() {
480 suggest_results.clear();
481 navigation_results.clear();
482 has_suggested_relevance = false;
483 verbatim_relevance = -1;
484}
485
[email protected]55ce8f12012-05-09 04:44:08486class SearchProvider::CompareScoredResults {
[email protected]51124552011-07-16 01:37:10487 public:
[email protected]55ce8f12012-05-09 04:44:08488 bool operator()(const Result& a, const Result& b) {
[email protected]51124552011-07-16 01:37:10489 // Sort in descending relevance order.
[email protected]55ce8f12012-05-09 04:44:08490 return a.relevance() > b.relevance();
[email protected]51124552011-07-16 01:37:10491 }
492};
493
initial.commit09911bf2008-07-26 23:55:29494void SearchProvider::Run() {
495 // Start a new request with the current input.
[email protected]257ab712009-04-14 17:16:24496 suggest_results_pending_ = 0;
[email protected]a0ad93ea2012-05-07 22:11:53497 time_suggest_request_sent_ = base::TimeTicks::Now();
[email protected]9ff91722012-09-07 05:29:12498
499 default_fetcher_.reset(CreateSuggestFetcher(kDefaultProviderURLFetcherID,
[email protected]14710852013-02-05 23:45:41500 providers_.GetDefaultProviderURL(), input_));
[email protected]9ff91722012-09-07 05:29:12501 keyword_fetcher_.reset(CreateSuggestFetcher(kKeywordProviderURLFetcherID,
[email protected]14710852013-02-05 23:45:41502 providers_.GetKeywordProviderURL(), keyword_input_));
[email protected]85b8d6f2012-05-08 20:53:47503
504 // Both the above can fail if the providers have been modified or deleted
505 // since the query began.
506 if (suggest_results_pending_ == 0) {
507 UpdateDone();
508 // We only need to update the listener if we're actually done.
509 if (done_)
510 listener_->OnProviderUpdate(false);
511 }
initial.commit09911bf2008-07-26 23:55:29512}
513
[email protected]e29249dc52012-07-19 17:33:50514void SearchProvider::Stop(bool clear_cached_results) {
initial.commit09911bf2008-07-26 23:55:29515 StopSuggest();
516 done_ = true;
[email protected]93b73832012-10-18 20:18:38517 default_provider_suggestion_ = InstantSuggestion();
[email protected]e29249dc52012-07-19 17:33:50518
519 if (clear_cached_results)
[email protected]71b46152013-05-03 16:39:20520 ClearAllResults();
initial.commit09911bf2008-07-26 23:55:29521}
522
[email protected]0e9e8782012-05-15 23:01:51523void SearchProvider::AddProviderInfo(ProvidersInfo* provider_info) const {
524 provider_info->push_back(metrics::OmniboxEventProto_ProviderInfo());
525 metrics::OmniboxEventProto_ProviderInfo& new_entry = provider_info->back();
526 new_entry.set_provider(AsOmniboxEventProviderType());
527 new_entry.set_provider_done(done_);
[email protected]fea6d302013-04-13 02:04:06528 std::vector<uint32> field_trial_hashes;
529 OmniboxFieldTrial::GetActiveSuggestFieldTrialHashes(&field_trial_hashes);
530 for (size_t i = 0; i < field_trial_hashes.size(); ++i) {
[email protected]618d6e62012-12-16 05:55:57531 if (field_trial_triggered_)
[email protected]fea6d302013-04-13 02:04:06532 new_entry.mutable_field_trial_triggered()->Add(field_trial_hashes[i]);
[email protected]d78d7362012-12-19 18:43:28533 if (field_trial_triggered_in_session_) {
[email protected]618d6e62012-12-16 05:55:57534 new_entry.mutable_field_trial_triggered_in_session()->Add(
[email protected]fea6d302013-04-13 02:04:06535 field_trial_hashes[i]);
[email protected]d78d7362012-12-19 18:43:28536 }
[email protected]618d6e62012-12-16 05:55:57537 }
538}
539
540void SearchProvider::ResetSession() {
541 field_trial_triggered_in_session_ = false;
[email protected]0e9e8782012-05-15 23:01:51542}
543
[email protected]10c2d692012-05-11 05:32:23544void SearchProvider::OnURLFetchComplete(const net::URLFetcher* source) {
initial.commit09911bf2008-07-26 23:55:29545 DCHECK(!done_);
[email protected]257ab712009-04-14 17:16:24546 suggest_results_pending_--;
[email protected]7706a522012-08-16 17:42:25547 LogOmniboxSuggestRequest(REPLY_RECEIVED);
[email protected]1cb2dac2010-03-08 21:49:15548 DCHECK_GE(suggest_results_pending_, 0); // Should never go negative.
[email protected]ec9207d32008-09-26 00:51:06549 const net::HttpResponseHeaders* const response_headers =
[email protected]7cc6e5632011-10-25 17:56:12550 source->GetResponseHeaders();
[email protected]c530c852011-10-24 18:18:34551 std::string json_data;
552 source->GetResponseAsString(&json_data);
[email protected]6c85aa02009-02-27 12:08:09553 // JSON is supposed to be UTF-8, but some suggest service providers send JSON
554 // files in non-UTF-8 encodings. The actual encoding is usually specified in
555 // the Content-Type header field.
[email protected]ec9207d32008-09-26 00:51:06556 if (response_headers) {
557 std::string charset;
558 if (response_headers->GetCharset(&charset)) {
[email protected]a2fedb1e2011-01-25 15:23:36559 string16 data_16;
[email protected]ec9207d32008-09-26 00:51:06560 // TODO(jungshik): Switch to CodePageToUTF8 after it's added.
[email protected]c530c852011-10-24 18:18:34561 if (base::CodepageToUTF16(json_data, charset.c_str(),
[email protected]a2fedb1e2011-01-25 15:23:36562 base::OnStringConversionError::FAIL,
563 &data_16))
564 json_data = UTF16ToUTF8(data_16);
[email protected]ec9207d32008-09-26 00:51:06565 }
566 }
567
[email protected]d7ad4772012-06-01 03:12:54568 const bool is_keyword = (source == keyword_fetcher_.get());
[email protected]f2916ea2013-01-26 02:20:14569 // Ensure the request succeeded and that the provider used is still available.
570 // A verbatim match cannot be generated without this provider, causing errors.
[email protected]013e9a02012-05-18 20:27:10571 const bool request_succeeded =
[email protected]f2916ea2013-01-26 02:20:14572 source->GetStatus().is_success() && source->GetResponseCode() == 200 &&
573 ((is_keyword && providers_.GetKeywordProviderURL()) ||
574 (!is_keyword && providers_.GetDefaultProviderURL()));
[email protected]a0ad93ea2012-05-07 22:11:53575
576 // Record response time for suggest requests sent to Google. We care
577 // only about the common case: the Google default provider used in
578 // non-keyword mode.
[email protected]85b8d6f2012-05-08 20:53:47579 const TemplateURL* default_url = providers_.GetDefaultProviderURL();
[email protected]55ce8f12012-05-09 04:44:08580 if (!is_keyword && default_url &&
[email protected]9899a612012-08-21 23:50:04581 (TemplateURLPrepopulateData::GetEngineType(default_url->url()) ==
582 SEARCH_ENGINE_GOOGLE)) {
[email protected]6dc950f2012-07-16 19:49:08583 const TimeDelta elapsed_time =
[email protected]013e9a02012-05-18 20:27:10584 base::TimeTicks::Now() - time_suggest_request_sent_;
585 if (request_succeeded) {
586 UMA_HISTOGRAM_TIMES("Omnibox.SuggestRequest.Success.GoogleResponseTime",
587 elapsed_time);
588 } else {
589 UMA_HISTOGRAM_TIMES("Omnibox.SuggestRequest.Failure.GoogleResponseTime",
590 elapsed_time);
591 }
[email protected]b4cebf82008-12-29 19:59:08592 }
593
[email protected]d7ad4772012-06-01 03:12:54594 bool results_updated = false;
595 if (request_succeeded) {
596 JSONStringValueSerializer deserializer(json_data);
597 deserializer.set_allow_trailing_comma(true);
598 scoped_ptr<Value> data(deserializer.Deserialize(NULL, NULL));
599 results_updated = data.get() && ParseSuggestResults(data.get(), is_keyword);
600 }
601
[email protected]344946a12012-12-20 12:03:42602 UpdateMatches();
[email protected]d7ad4772012-06-01 03:12:54603 if (done_ || results_updated)
604 listener_->OnProviderUpdate(results_updated);
initial.commit09911bf2008-07-26 23:55:29605}
606
[email protected]abe441e2013-05-06 12:35:05607bool SearchProvider::IsNonInstantSearchDone() const {
608 return !timer_.IsRunning() && (suggest_results_pending_ == 0);
609}
610
[email protected]601858c02010-09-01 17:08:20611SearchProvider::~SearchProvider() {
612}
613
[email protected]8d457132010-11-04 18:13:40614void SearchProvider::DoHistoryQuery(bool minimal_changes) {
615 // The history query results are synchronous, so if minimal_changes is true,
616 // we still have the last results and don't need to do anything.
617 if (minimal_changes)
initial.commit09911bf2008-07-26 23:55:29618 return;
619
[email protected]8d457132010-11-04 18:13:40620 keyword_history_results_.clear();
621 default_history_results_.clear();
initial.commit09911bf2008-07-26 23:55:29622
[email protected]8d457132010-11-04 18:13:40623 HistoryService* const history_service =
[email protected]9d2db762012-06-19 00:01:10624 HistoryServiceFactory::GetForProfile(profile_, Profile::EXPLICIT_ACCESS);
[email protected]8d457132010-11-04 18:13:40625 history::URLDatabase* url_db = history_service ?
626 history_service->InMemoryDatabase() : NULL;
627 if (!url_db)
initial.commit09911bf2008-07-26 23:55:29628 return;
629
[email protected]51124552011-07-16 01:37:10630 // Request history for both the keyword and default provider. We grab many
631 // more matches than we'll ultimately clamp to so that if there are several
632 // recent multi-word matches who scores are lowered (see
633 // AddHistoryResultsToMap()), they won't crowd out older, higher-scoring
634 // matches. Note that this doesn't fix the problem entirely, but merely
635 // limits it to cases with a very large number of such multi-word matches; for
636 // now, this seems OK compared with the complexity of a real fix, which would
637 // require multiple searches and tracking of "single- vs. multi-word" in the
638 // database.
639 int num_matches = kMaxMatches * 5;
[email protected]85b8d6f2012-05-08 20:53:47640 const TemplateURL* default_url = providers_.GetDefaultProviderURL();
641 if (default_url) {
642 url_db->GetMostRecentKeywordSearchTerms(default_url->id(), input_.text(),
643 num_matches, &default_history_results_);
[email protected]257ab712009-04-14 17:16:24644 }
[email protected]85b8d6f2012-05-08 20:53:47645 const TemplateURL* keyword_url = providers_.GetKeywordProviderURL();
646 if (keyword_url) {
647 url_db->GetMostRecentKeywordSearchTerms(keyword_url->id(),
[email protected]14710852013-02-05 23:45:41648 keyword_input_.text(), num_matches, &keyword_history_results_);
[email protected]3954c3a2012-04-10 20:17:55649 }
initial.commit09911bf2008-07-26 23:55:29650}
651
[email protected]6dc950f2012-07-16 19:49:08652void SearchProvider::StartOrStopSuggestQuery(bool minimal_changes) {
[email protected]83c726482008-09-10 06:36:34653 if (!IsQuerySuitableForSuggest()) {
initial.commit09911bf2008-07-26 23:55:29654 StopSuggest();
[email protected]71b46152013-05-03 16:39:20655 ClearAllResults();
initial.commit09911bf2008-07-26 23:55:29656 return;
657 }
658
659 // For the minimal_changes case, if we finished the previous query and still
660 // have its results, or are allowed to keep running it, just do that, rather
661 // than starting a new query.
662 if (minimal_changes &&
[email protected]cc1526e2013-05-17 04:04:24663 (!default_results_.suggest_results.empty() ||
664 !default_results_.navigation_results.empty() ||
665 !keyword_results_.suggest_results.empty() ||
666 !keyword_results_.navigation_results.empty() ||
[email protected]ea3b9a502011-04-04 14:19:37667 (!done_ &&
668 input_.matches_requested() == AutocompleteInput::ALL_MATCHES)))
initial.commit09911bf2008-07-26 23:55:29669 return;
670
671 // We can't keep running any previous query, so halt it.
672 StopSuggest();
[email protected]d1f0a7f2012-06-05 10:26:42673
674 // Remove existing results that cannot inline autocomplete the new input.
[email protected]71b46152013-05-03 16:39:20675 RemoveAllStaleResults();
initial.commit09911bf2008-07-26 23:55:29676
677 // We can't start a new query if we're only allowed synchronous results.
[email protected]ea3b9a502011-04-04 14:19:37678 if (input_.matches_requested() != AutocompleteInput::ALL_MATCHES)
initial.commit09911bf2008-07-26 23:55:29679 return;
680
[email protected]24dbf2302013-04-05 16:59:25681 // To avoid flooding the suggest server, don't send a query until at
682 // least 100 ms since the last query.
[email protected]515ffa942012-11-27 20:18:24683 base::TimeTicks next_suggest_time(time_suggest_request_sent_ +
684 TimeDelta::FromMilliseconds(kMinimumTimeBetweenSuggestQueriesMs));
685 base::TimeTicks now(base::TimeTicks::Now());
686 if (now >= next_suggest_time) {
687 Run();
688 return;
689 }
690 timer_.Start(FROM_HERE, next_suggest_time - now, this, &SearchProvider::Run);
initial.commit09911bf2008-07-26 23:55:29691}
692
[email protected]83c726482008-09-10 06:36:34693bool SearchProvider::IsQuerySuitableForSuggest() const {
[email protected]3954c3a2012-04-10 20:17:55694 // Don't run Suggest in incognito mode, if the engine doesn't support it, or
695 // if the user has disabled it.
[email protected]85b8d6f2012-05-08 20:53:47696 const TemplateURL* default_url = providers_.GetDefaultProviderURL();
697 const TemplateURL* keyword_url = providers_.GetKeywordProviderURL();
[email protected]83c726482008-09-10 06:36:34698 if (profile_->IsOffTheRecord() ||
[email protected]85b8d6f2012-05-08 20:53:47699 ((!default_url || default_url->suggestions_url().empty()) &&
700 (!keyword_url || keyword_url->suggestions_url().empty())) ||
[email protected]83c726482008-09-10 06:36:34701 !profile_->GetPrefs()->GetBoolean(prefs::kSearchSuggestEnabled))
702 return false;
703
[email protected]cac59d32010-08-09 23:23:14704 // If the input type might be a URL, we take extra care so that private data
[email protected]83c726482008-09-10 06:36:34705 // isn't sent to the server.
[email protected]83c726482008-09-10 06:36:34706
[email protected]cac59d32010-08-09 23:23:14707 // FORCED_QUERY means the user is explicitly asking us to search for this, so
708 // we assume it isn't a URL and/or there isn't private data.
709 if (input_.type() == AutocompleteInput::FORCED_QUERY)
710 return true;
[email protected]83c726482008-09-10 06:36:34711
[email protected]f608ea102013-03-18 15:08:09712 // Next we check the scheme. If this is UNKNOWN/URL with a scheme that isn't
713 // http/https/ftp, we shouldn't send it. Sending things like file: and data:
714 // is both a waste of time and a disclosure of potentially private, local
715 // data. Other "schemes" may actually be usernames, and we don't want to send
716 // passwords. If the scheme is OK, we still need to check other cases below.
717 // If this is QUERY, then the presence of these schemes means the user
718 // explicitly typed one, and thus this is probably a URL that's being entered
719 // and happens to currently be invalid -- in which case we again want to run
720 // our checks below. Other QUERY cases are less likely to be URLs and thus we
721 // assume we're OK.
[email protected]a2fedb1e2011-01-25 15:23:36722 if (!LowerCaseEqualsASCII(input_.scheme(), chrome::kHttpScheme) &&
723 !LowerCaseEqualsASCII(input_.scheme(), chrome::kHttpsScheme) &&
724 !LowerCaseEqualsASCII(input_.scheme(), chrome::kFtpScheme))
[email protected]cac59d32010-08-09 23:23:14725 return (input_.type() == AutocompleteInput::QUERY);
726
727 // Don't send URLs with usernames, queries or refs. Some of these are
728 // private, and the Suggest server is unlikely to have any useful results
729 // for any of them. Also don't send URLs with ports, as we may initially
730 // think that a username + password is a host + port (and we don't want to
731 // send usernames/passwords), and even if the port really is a port, the
732 // server is once again unlikely to have and useful results.
733 const url_parse::Parsed& parts = input_.parts();
734 if (parts.username.is_nonempty() || parts.port.is_nonempty() ||
735 parts.query.is_nonempty() || parts.ref.is_nonempty())
736 return false;
737
738 // Don't send anything for https except the hostname. Hostnames are OK
739 // because they are visible when the TCP connection is established, but the
740 // specific path may reveal private information.
[email protected]a2fedb1e2011-01-25 15:23:36741 if (LowerCaseEqualsASCII(input_.scheme(), chrome::kHttpsScheme) &&
742 parts.path.is_nonempty())
[email protected]cac59d32010-08-09 23:23:14743 return false;
[email protected]83c726482008-09-10 06:36:34744
745 return true;
746}
747
initial.commit09911bf2008-07-26 23:55:29748void SearchProvider::StopSuggest() {
[email protected]7706a522012-08-16 17:42:25749 // Increment the appropriate field in the histogram by the number of
750 // pending requests that were invalidated.
751 for (int i = 0; i < suggest_results_pending_; i++)
752 LogOmniboxSuggestRequest(REQUEST_INVALIDATED);
[email protected]257ab712009-04-14 17:16:24753 suggest_results_pending_ = 0;
[email protected]2d316662008-09-03 18:18:14754 timer_.Stop();
[email protected]257ab712009-04-14 17:16:24755 // Stop any in-progress URL fetches.
756 keyword_fetcher_.reset();
757 default_fetcher_.reset();
[email protected]55ce8f12012-05-09 04:44:08758}
759
[email protected]71b46152013-05-03 16:39:20760void SearchProvider::ClearAllResults() {
[email protected]cc1526e2013-05-17 04:04:24761 keyword_results_.Clear();
762 default_results_.Clear();
[email protected]1e1550e2013-05-02 17:37:51763}
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(),
[email protected]cc1526e2013-05-17 04:04:24774 &default_results_.suggest_results,
775 &default_results_.navigation_results);
[email protected]1e1550e2013-05-02 17:37:51776 if (!keyword_input_.text().empty()) {
777 RemoveStaleResults(keyword_input_.text(), GetKeywordVerbatimRelevance(),
[email protected]cc1526e2013-05-17 04:04:24778 &keyword_results_.suggest_results,
779 &keyword_results_.navigation_results);
[email protected]1e1550e2013-05-02 17:37:51780 } else {
781 // User is either in keyword mode with a blank input or out of
782 // keyword mode entirely.
[email protected]cc1526e2013-05-17 04:04:24783 keyword_results_.Clear();
[email protected]1e1550e2013-05-02 17:37:51784 }
[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]cc1526e2013-05-17 04:04:24877 ApplyCalculatedSuggestRelevance(&keyword_results_.suggest_results);
878 ApplyCalculatedSuggestRelevance(&default_results_.suggest_results);
879 ApplyCalculatedNavigationRelevance(&keyword_results_.navigation_results);
880 ApplyCalculatedNavigationRelevance(&default_results_.navigation_results);
881 default_results_.has_suggested_relevance = false;
882 keyword_results_.has_suggested_relevance = false;
883 default_results_.verbatim_relevance = -1;
884 keyword_results_.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) {
[email protected]d7ad4772012-06-01 03:12:54938 string16 query;
939 ListValue* root_list = NULL;
[email protected]cc1526e2013-05-17 04:04:24940 ListValue* results_list = NULL;
[email protected]14710852013-02-05 23:45:41941 const string16& input_text =
942 is_keyword ? keyword_input_.text() : input_.text();
[email protected]d7ad4772012-06-01 03:12:54943 if (!root_val->GetAsList(&root_list) || !root_list->GetString(0, &query) ||
[email protected]cc1526e2013-05-17 04:04:24944 (query != input_text) || !root_list->GetList(1, &results_list))
initial.commit09911bf2008-07-26 23:55:29945 return false;
946
[email protected]55ce8f12012-05-09 04:44:08947 // 3rd element: Description list.
[email protected]d7ad4772012-06-01 03:12:54948 ListValue* descriptions = NULL;
949 root_list->GetList(2, &descriptions);
initial.commit09911bf2008-07-26 23:55:29950
[email protected]55ce8f12012-05-09 04:44:08951 // 4th element: Disregard the query URL list for now.
initial.commit09911bf2008-07-26 23:55:29952
[email protected]d1f0a7f2012-06-05 10:26:42953 // Reset suggested relevance information from the default provider.
[email protected]cc1526e2013-05-17 04:04:24954 Results* results = is_keyword ? &keyword_results_ : &default_results_;
955 results->has_suggested_relevance = false;
956 results->verbatim_relevance = -1;
[email protected]d1f0a7f2012-06-05 10:26:42957
[email protected]55ce8f12012-05-09 04:44:08958 // 5th element: Optional key-value pairs from the Suggest server.
[email protected]d7ad4772012-06-01 03:12:54959 ListValue* types = NULL;
[email protected]d1f0a7f2012-06-05 10:26:42960 ListValue* relevances = NULL;
961 DictionaryValue* extras = NULL;
962 if (root_list->GetDictionary(4, &extras)) {
963 extras->GetList("google:suggesttype", &types);
964
965 // Only accept relevance suggestions if Instant is disabled.
[email protected]165fe422013-03-27 06:34:03966 if (!chrome::IsInstantEnabled(profile_)) {
[email protected]d1f0a7f2012-06-05 10:26:42967 // Discard this list if its size does not match that of the suggestions.
968 if (extras->GetList("google:suggestrelevance", &relevances) &&
[email protected]cc1526e2013-05-17 04:04:24969 relevances->GetSize() != results_list->GetSize())
[email protected]d1f0a7f2012-06-05 10:26:42970 relevances = NULL;
[email protected]cc1526e2013-05-17 04:04:24971 extras->GetInteger("google:verbatimrelevance",
972 &results->verbatim_relevance);
[email protected]d1f0a7f2012-06-05 10:26:42973 }
[email protected]618d6e62012-12-16 05:55:57974
975 // Check if the active suggest field trial (if any) has triggered either
976 // for the default provider or keyword provider.
977 bool triggered = false;
978 extras->GetBoolean("google:fieldtrialtriggered", &triggered);
979 field_trial_triggered_ |= triggered;
980 field_trial_triggered_in_session_ |= triggered;
initial.commit09911bf2008-07-26 23:55:29981 }
982
[email protected]d1f0a7f2012-06-05 10:26:42983 // Clear the previous results now that new results are available.
[email protected]cc1526e2013-05-17 04:04:24984 results->suggest_results.clear();
985 results->navigation_results.clear();
[email protected]d1f0a7f2012-06-05 10:26:42986
987 string16 result, title;
988 std::string type;
989 int relevance = -1;
[email protected]cc1526e2013-05-17 04:04:24990 for (size_t index = 0; results_list->GetString(index, &result); ++index) {
[email protected]8e81f5092010-09-29 23:19:40991 // Google search may return empty suggestions for weird input characters,
[email protected]55ce8f12012-05-09 04:44:08992 // they make no sense at all and can cause problems in our code.
[email protected]d7ad4772012-06-01 03:12:54993 if (result.empty())
[email protected]8e81f5092010-09-29 23:19:40994 continue;
995
[email protected]d1f0a7f2012-06-05 10:26:42996 // Apply valid suggested relevance scores; discard invalid lists.
997 if (relevances != NULL && !relevances->GetInteger(index, &relevance))
998 relevances = NULL;
[email protected]d7ad4772012-06-01 03:12:54999 if (types && types->GetString(index, &type) && (type == "NAVIGATION")) {
[email protected]d1f0a7f2012-06-05 10:26:421000 // Do not blindly trust the URL coming from the server to be valid.
1001 GURL url(URLFixerUpper::FixupURL(UTF16ToUTF8(result), std::string()));
1002 if (url.is_valid()) {
1003 if (descriptions != NULL)
1004 descriptions->GetString(index, &title);
[email protected]cc1526e2013-05-17 04:04:241005 results->navigation_results.push_back(
1006 NavigationResult(*this, url, title, is_keyword, relevance));
initial.commit09911bf2008-07-26 23:55:291007 }
1008 } else {
[email protected]d1f0a7f2012-06-05 10:26:421009 // TODO(kochi): Improve calculator result presentation.
[email protected]cc1526e2013-05-17 04:04:241010 results->suggest_results.push_back(
1011 SuggestResult(result, is_keyword, relevance));
initial.commit09911bf2008-07-26 23:55:291012 }
1013 }
1014
[email protected]d1f0a7f2012-06-05 10:26:421015 // Apply calculated relevance scores if a valid list was not provided.
1016 if (relevances == NULL) {
[email protected]cc1526e2013-05-17 04:04:241017 ApplyCalculatedSuggestRelevance(&results->suggest_results);
1018 ApplyCalculatedNavigationRelevance(&results->navigation_results);
[email protected]dab8d52d2013-03-05 07:35:281019 } else {
[email protected]cc1526e2013-05-17 04:04:241020 results->has_suggested_relevance = true;
[email protected]d1f0a7f2012-06-05 10:26:421021 }
[email protected]9dfb4d362013-04-05 02:15:121022 // Keep the result lists sorted.
1023 const CompareScoredResults comparator = CompareScoredResults();
[email protected]cc1526e2013-05-17 04:04:241024 std::stable_sort(results->suggest_results.begin(),
1025 results->suggest_results.end(),
[email protected]9dfb4d362013-04-05 02:15:121026 comparator);
[email protected]cc1526e2013-05-17 04:04:241027 std::stable_sort(results->navigation_results.begin(),
1028 results->navigation_results.end(),
[email protected]9dfb4d362013-04-05 02:15:121029 comparator);
[email protected]d1f0a7f2012-06-05 10:26:421030 return true;
initial.commit09911bf2008-07-26 23:55:291031}
1032
[email protected]344946a12012-12-20 12:03:421033void SearchProvider::ConvertResultsToAutocompleteMatches() {
initial.commit09911bf2008-07-26 23:55:291034 // Convert all the results to matches and add them to a map, so we can keep
1035 // the most relevant match for each result.
1036 MatchMap map;
[email protected]257ab712009-04-14 17:16:241037 const Time no_time;
[email protected]cc1526e2013-05-17 04:04:241038 int did_not_accept_keyword_suggestion =
1039 keyword_results_.suggest_results.empty() ?
initial.commit09911bf2008-07-26 23:55:291040 TemplateURLRef::NO_SUGGESTIONS_AVAILABLE :
1041 TemplateURLRef::NO_SUGGESTION_CHOSEN;
initial.commit09911bf2008-07-26 23:55:291042
[email protected]382a0642012-06-06 06:13:521043 int verbatim_relevance = GetVerbatimRelevance();
[email protected]cc1526e2013-05-17 04:04:241044 int did_not_accept_default_suggestion =
1045 default_results_.suggest_results.empty() ?
[email protected]55ce8f12012-05-09 04:44:081046 TemplateURLRef::NO_SUGGESTIONS_AVAILABLE :
1047 TemplateURLRef::NO_SUGGESTION_CHOSEN;
[email protected]d1f0a7f2012-06-05 10:26:421048 if (verbatim_relevance > 0) {
1049 AddMatchToMap(input_.text(), input_.text(), verbatim_relevance,
[email protected]b7f64d742013-05-21 04:04:041050 AutocompleteMatchType::SEARCH_WHAT_YOU_TYPED,
[email protected]d1f0a7f2012-06-05 10:26:421051 did_not_accept_default_suggestion, false, &map);
1052 }
[email protected]5423e562013-02-07 03:58:451053 if (!keyword_input_.text().empty()) {
1054 const TemplateURL* keyword_url = providers_.GetKeywordProviderURL();
1055 // We only create the verbatim search query match for a keyword
1056 // if it's not an extension keyword. Extension keywords are handled
1057 // in KeywordProvider::Start(). (Extensions are complicated...)
1058 // Note: in this provider, SEARCH_OTHER_ENGINE must correspond
1059 // to the keyword verbatim search query. Do not create other matches
1060 // of type SEARCH_OTHER_ENGINE.
1061 if (keyword_url && !keyword_url->IsExtensionKeyword()) {
[email protected]dab8d52d2013-03-05 07:35:281062 const int keyword_verbatim_relevance = GetKeywordVerbatimRelevance();
1063 if (keyword_verbatim_relevance > 0) {
1064 AddMatchToMap(keyword_input_.text(), keyword_input_.text(),
1065 keyword_verbatim_relevance,
[email protected]b7f64d742013-05-21 04:04:041066 AutocompleteMatchType::SEARCH_OTHER_ENGINE,
[email protected]dab8d52d2013-03-05 07:35:281067 did_not_accept_keyword_suggestion, true, &map);
1068 }
[email protected]5423e562013-02-07 03:58:451069 }
1070 }
1071 const size_t verbatim_matches_size = map.size();
[email protected]93b73832012-10-18 20:18:381072 if (!default_provider_suggestion_.text.empty() &&
[email protected]2ac15ba2013-01-14 22:38:591073 default_provider_suggestion_.type == INSTANT_SUGGESTION_SEARCH &&
1074 !input_.prevent_inline_autocomplete())
[email protected]93b73832012-10-18 20:18:381075 AddMatchToMap(input_.text() + default_provider_suggestion_.text,
[email protected]55ce8f12012-05-09 04:44:081076 input_.text(), verbatim_relevance + 1,
[email protected]b7f64d742013-05-21 04:04:041077 AutocompleteMatchType::SEARCH_SUGGEST,
[email protected]55ce8f12012-05-09 04:44:081078 did_not_accept_default_suggestion, false, &map);
initial.commit09911bf2008-07-26 23:55:291079
[email protected]257ab712009-04-14 17:16:241080 AddHistoryResultsToMap(keyword_history_results_, true,
1081 did_not_accept_keyword_suggestion, &map);
1082 AddHistoryResultsToMap(default_history_results_, false,
1083 did_not_accept_default_suggestion, &map);
1084
[email protected]cc1526e2013-05-17 04:04:241085 AddSuggestResultsToMap(keyword_results_.suggest_results, &map);
1086 AddSuggestResultsToMap(default_results_.suggest_results, &map);
initial.commit09911bf2008-07-26 23:55:291087
1088 // Now add the most relevant matches from the map to |matches_|.
1089 matches_.clear();
1090 for (MatchMap::const_iterator i(map.begin()); i != map.end(); ++i)
1091 matches_.push_back(i->second);
1092
[email protected]93b73832012-10-18 20:18:381093 if (!default_provider_suggestion_.text.empty() &&
[email protected]2ac15ba2013-01-14 22:38:591094 default_provider_suggestion_.type == INSTANT_SUGGESTION_URL &&
[email protected]90fe2bb2013-01-15 03:42:131095 !input_.prevent_inline_autocomplete()) {
1096 // See comment in FinalizeInstantQuery() for why we don't use
1097 // |verbatim_relevance| here.
[email protected]93b73832012-10-18 20:18:381098 matches_.push_back(NavigationToMatch(
[email protected]a1b5e862013-03-29 06:38:441099 NavigationResult(*this,
1100 GURL(UTF16ToUTF8(default_provider_suggestion_.text)),
[email protected]93b73832012-10-18 20:18:381101 string16(),
[email protected]188b50c2013-03-28 07:19:421102 false,
1103 kNonURLVerbatimRelevance + 1)));
[email protected]90fe2bb2013-01-15 03:42:131104 }
[email protected]cc1526e2013-05-17 04:04:241105 AddNavigationResultsToMatches(keyword_results_.navigation_results, true);
1106 AddNavigationResultsToMatches(default_results_.navigation_results, false);
initial.commit09911bf2008-07-26 23:55:291107
[email protected]5423e562013-02-07 03:58:451108 // Allow additional match(es) for verbatim results if present.
1109 const size_t max_total_matches = kMaxMatches + verbatim_matches_size;
initial.commit09911bf2008-07-26 23:55:291110 std::partial_sort(matches_.begin(),
1111 matches_.begin() + std::min(max_total_matches, matches_.size()),
1112 matches_.end(), &AutocompleteMatch::MoreRelevant);
[email protected]3723e6e2012-06-11 21:06:561113
initial.commit09911bf2008-07-26 23:55:291114 if (matches_.size() > max_total_matches)
[email protected]344946a12012-12-20 12:03:421115 matches_.resize(max_total_matches);
1116}
1117
[email protected]9dfb4d362013-04-05 02:15:121118bool SearchProvider::IsTopMatchNavigationInKeywordMode() const {
1119 return (!providers_.keyword_provider().empty() &&
[email protected]b7f64d742013-05-21 04:04:041120 (matches_.front().type == AutocompleteMatchType::NAVSUGGEST));
[email protected]9dfb4d362013-04-05 02:15:121121}
1122
[email protected]344946a12012-12-20 12:03:421123bool SearchProvider::IsTopMatchScoreTooLow() const {
[email protected]dab8d52d2013-03-05 07:35:281124 // Here we use CalculateRelevanceForVerbatimIgnoringKeywordModeState()
1125 // rather than CalculateRelevanceForVerbatim() because the latter returns
1126 // a very low score (250) if keyword mode is active. This is because
1127 // when keyword mode is active the user probably wants the keyword matches,
1128 // not matches from the default provider. Hence, we use the version of
1129 // the function that ignores whether keyword mode is active. This allows
1130 // SearchProvider to maintain its contract with the AutocompleteController
1131 // that it will always provide an inlineable match with a reasonable
1132 // score.
1133 return matches_.front().relevance <
1134 CalculateRelevanceForVerbatimIgnoringKeywordModeState();
[email protected]344946a12012-12-20 12:03:421135}
1136
1137bool SearchProvider::IsTopMatchHighRankSearchForURL() const {
1138 return input_.type() == AutocompleteInput::URL &&
1139 matches_.front().relevance > CalculateRelevanceForVerbatim() &&
[email protected]b7f64d742013-05-21 04:04:041140 (matches_.front().type == AutocompleteMatchType::SEARCH_SUGGEST ||
1141 matches_.front().type ==
1142 AutocompleteMatchType::SEARCH_WHAT_YOU_TYPED ||
1143 matches_.front().type == AutocompleteMatchType::SEARCH_OTHER_ENGINE);
[email protected]344946a12012-12-20 12:03:421144}
1145
1146bool SearchProvider::IsTopMatchNotInlinable() const {
[email protected]5423e562013-02-07 03:58:451147 // Note: this test assumes the SEARCH_OTHER_ENGINE match corresponds to
1148 // the verbatim search query on the keyword engine. SearchProvider should
1149 // not create any other match of type SEARCH_OTHER_ENGINE.
[email protected]b7f64d742013-05-21 04:04:041150 return
1151 matches_.front().type != AutocompleteMatchType::SEARCH_WHAT_YOU_TYPED &&
1152 matches_.front().type != AutocompleteMatchType::URL_WHAT_YOU_TYPED &&
1153 matches_.front().type != AutocompleteMatchType::SEARCH_OTHER_ENGINE &&
1154 matches_.front().inline_autocomplete_offset == string16::npos &&
1155 matches_.front().fill_into_edit != input_.text();
[email protected]344946a12012-12-20 12:03:421156}
1157
1158void SearchProvider::UpdateMatches() {
1159 ConvertResultsToAutocompleteMatches();
initial.commit09911bf2008-07-26 23:55:291160
[email protected]382a0642012-06-06 06:13:521161 // Check constraints that may be violated by suggested relevances.
[email protected]344946a12012-12-20 12:03:421162 if (!matches_.empty() &&
[email protected]cc1526e2013-05-17 04:04:241163 (default_results_.has_suggested_relevance ||
1164 default_results_.verbatim_relevance >= 0 ||
1165 keyword_results_.has_suggested_relevance ||
1166 keyword_results_.verbatim_relevance >= 0)) {
[email protected]9dfb4d362013-04-05 02:15:121167 // These blocks attempt to repair undesirable behavior by suggested
[email protected]344946a12012-12-20 12:03:421168 // relevances with minimal impact, preserving other suggested relevances.
[email protected]9dfb4d362013-04-05 02:15:121169 if (IsTopMatchNavigationInKeywordMode()) {
1170 // Correct the suggested relevance scores if the top match is a
1171 // navigation in keyword mode, since inlining a navigation match
1172 // would break the user out of keyword mode. By the way, if the top
1173 // match is a non-keyword match (query or navsuggestion) in keyword
1174 // mode, the user would also break out of keyword mode. However,
1175 // that situation is impossible given the current scoring paradigm
1176 // and the fact that only one search engine (Google) provides suggested
1177 // relevance scores at this time.
1178 DemoteKeywordNavigationMatchesPastTopQuery();
1179 ConvertResultsToAutocompleteMatches();
1180 DCHECK(!IsTopMatchNavigationInKeywordMode());
1181 }
[email protected]344946a12012-12-20 12:03:421182 if (IsTopMatchScoreTooLow()) {
[email protected]1beee342012-06-19 22:22:281183 // Disregard the suggested verbatim relevance if the top score is below
1184 // the usual verbatim value. For example, a BarProvider may rely on
1185 // SearchProvider's verbatim or inlineable matches for input "foo" to
1186 // always outrank its own lowly-ranked non-inlineable "bar" match.
[email protected]cc1526e2013-05-17 04:04:241187 default_results_.verbatim_relevance = -1;
1188 keyword_results_.verbatim_relevance = -1;
[email protected]344946a12012-12-20 12:03:421189 ConvertResultsToAutocompleteMatches();
[email protected]e6acd002012-06-16 22:27:471190 }
[email protected]344946a12012-12-20 12:03:421191 if (IsTopMatchHighRankSearchForURL()) {
[email protected]e6acd002012-06-16 22:27:471192 // Disregard the suggested search and verbatim relevances if the input
1193 // type is URL and the top match is a highly-ranked search suggestion.
1194 // For example, prevent a search for "foo.com" from outranking another
1195 // provider's navigation for "foo.com" or "foo.com/url_from_history".
[email protected]cc1526e2013-05-17 04:04:241196 ApplyCalculatedSuggestRelevance(&keyword_results_.suggest_results);
1197 ApplyCalculatedSuggestRelevance(&default_results_.suggest_results);
1198 default_results_.verbatim_relevance = -1;
1199 keyword_results_.verbatim_relevance = -1;
[email protected]344946a12012-12-20 12:03:421200 ConvertResultsToAutocompleteMatches();
[email protected]382a0642012-06-06 06:13:521201 }
[email protected]344946a12012-12-20 12:03:421202 if (IsTopMatchNotInlinable()) {
[email protected]5423e562013-02-07 03:58:451203 // Disregard suggested relevances if the top match is not a verbatim
1204 // match, inlinable, or URL_WHAT_YOU_TYPED (which may be top match
1205 // regardless of inlining). For example, input "foo" should not
1206 // invoke a search for "bar", which would happen if the "bar" search
1207 // match outranked all other matches.
[email protected]344946a12012-12-20 12:03:421208 ApplyCalculatedRelevance();
1209 ConvertResultsToAutocompleteMatches();
[email protected]382a0642012-06-06 06:13:521210 }
[email protected]9dfb4d362013-04-05 02:15:121211 DCHECK(!IsTopMatchNavigationInKeywordMode());
[email protected]344946a12012-12-20 12:03:421212 DCHECK(!IsTopMatchScoreTooLow());
1213 DCHECK(!IsTopMatchHighRankSearchForURL());
1214 DCHECK(!IsTopMatchNotInlinable());
[email protected]d1f0a7f2012-06-05 10:26:421215 }
1216
[email protected]cc63dea2008-08-21 20:56:311217 UpdateStarredStateOfMatches();
[email protected]4ab4c7c2010-11-24 04:49:341218 UpdateDone();
[email protected]257ab712009-04-14 17:16:241219}
1220
1221void SearchProvider::AddNavigationResultsToMatches(
1222 const NavigationResults& navigation_results,
1223 bool is_keyword) {
[email protected]c112f0fe72013-01-18 20:30:091224 if (navigation_results.empty())
1225 return;
1226
[email protected]dab8d52d2013-03-05 07:35:281227 if (is_keyword ?
[email protected]cc1526e2013-05-17 04:04:241228 keyword_results_.has_suggested_relevance :
1229 default_results_.has_suggested_relevance) {
[email protected]c112f0fe72013-01-18 20:30:091230 for (NavigationResults::const_iterator it = navigation_results.begin();
1231 it != navigation_results.end(); ++it)
[email protected]188b50c2013-03-28 07:19:421232 matches_.push_back(NavigationToMatch(*it));
[email protected]c112f0fe72013-01-18 20:30:091233 } else {
[email protected]9dfb4d362013-04-05 02:15:121234 // Pick the highest-scoring element only in absence of the
1235 // suggested relevance scores. (The results are already sorted.)
[email protected]6c535842012-05-15 05:20:551236 // TODO(kochi|msw): Add more navigational results if they get more
1237 // meaningful relevance values; see http://b/1170574.
[email protected]9dfb4d362013-04-05 02:15:121238 matches_.push_back(NavigationToMatch(navigation_results.front()));
[email protected]257ab712009-04-14 17:16:241239 }
1240}
1241
1242void SearchProvider::AddHistoryResultsToMap(const HistoryResults& results,
1243 bool is_keyword,
1244 int did_not_accept_suggestion,
1245 MatchMap* map) {
[email protected]51124552011-07-16 01:37:101246 if (results.empty())
1247 return;
1248
[email protected]d7ad4772012-06-01 03:12:541249 bool prevent_inline_autocomplete = input_.prevent_inline_autocomplete() ||
1250 (input_.type() == AutocompleteInput::URL);
[email protected]14710852013-02-05 23:45:411251 const string16& input_text =
1252 is_keyword ? keyword_input_.text() : input_.text();
[email protected]51124552011-07-16 01:37:101253 bool input_multiple_words = HasMultipleWords(input_text);
1254
[email protected]55ce8f12012-05-09 04:44:081255 SuggestResults scored_results;
1256 if (!prevent_inline_autocomplete && input_multiple_words) {
1257 // ScoreHistoryResults() allows autocompletion of multi-word, 1-visit
1258 // queries if the input also has multiple words. But if we were already
[email protected]51124552011-07-16 01:37:101259 // autocompleting a multi-word, multi-visit query, and the current input is
1260 // still a prefix of it, then changing the autocompletion suddenly feels
1261 // wrong. To detect this case, first score as if only one word has been
1262 // typed, then check for a best result that is an autocompleted, multi-word
1263 // query. If we find one, then just keep that score set.
[email protected]55ce8f12012-05-09 04:44:081264 scored_results = ScoreHistoryResults(results, prevent_inline_autocomplete,
1265 false, input_text, is_keyword);
[email protected]9dfb4d362013-04-05 02:15:121266 if ((scored_results.front().relevance() <
[email protected]55ce8f12012-05-09 04:44:081267 AutocompleteResult::kLowestDefaultScore) ||
[email protected]9dfb4d362013-04-05 02:15:121268 !HasMultipleWords(scored_results.front().suggestion()))
[email protected]55ce8f12012-05-09 04:44:081269 scored_results.clear(); // Didn't detect the case above, score normally.
[email protected]51124552011-07-16 01:37:101270 }
[email protected]55ce8f12012-05-09 04:44:081271 if (scored_results.empty())
1272 scored_results = ScoreHistoryResults(results, prevent_inline_autocomplete,
1273 input_multiple_words, input_text,
1274 is_keyword);
1275 for (SuggestResults::const_iterator i(scored_results.begin());
1276 i != scored_results.end(); ++i) {
1277 AddMatchToMap(i->suggestion(), input_text, i->relevance(),
[email protected]b7f64d742013-05-21 04:04:041278 AutocompleteMatchType::SEARCH_HISTORY,
1279 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]b7f64d742013-05-21 04:04:041349 AutocompleteMatchType::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]cc1526e2013-05-17 04:04:241362 if (default_results_.verbatim_relevance >= 0 &&
[email protected]dab8d52d2013-03-05 07:35:281363 !input_.prevent_inline_autocomplete() &&
[email protected]cc1526e2013-05-17 04:04:241364 (default_results_.verbatim_relevance > 0 ||
1365 !default_results_.suggest_results.empty() ||
1366 !default_results_.navigation_results.empty())) {
1367 return default_results_.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.
[email protected]cc1526e2013-05-17 04:04:241404 if (keyword_results_.verbatim_relevance >= 0 &&
[email protected]dab8d52d2013-03-05 07:35:281405 !input_.prevent_inline_autocomplete() &&
[email protected]cc1526e2013-05-17 04:04:241406 (keyword_results_.verbatim_relevance > 0 ||
1407 !keyword_results_.suggest_results.empty() ||
1408 !keyword_results_.navigation_results.empty())) {
1409 return keyword_results_.verbatim_relevance;
[email protected]dab8d52d2013-03-05 07:35:281410 }
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.
[email protected]b7f64d742013-05-21 04:04:041480 if (type != AutocompleteMatchType::SEARCH_WHAT_YOU_TYPED &&
1481 type != AutocompleteMatchType::SEARCH_OTHER_ENGINE &&
[email protected]4eeb54f92013-04-27 04:01:201482 chrome::IsInstantExtendedAPIEnabled()) {
1483 relevance = std::min(kNonURLVerbatimRelevance - 1, relevance);
1484 }
[email protected]cb86ee6f2013-04-28 16:58:151485
1486 const string16& keyword = is_keyword ?
[email protected]3954c3a2012-04-10 20:17:551487 providers_.keyword_provider() : providers_.default_provider();
[email protected]cb86ee6f2013-04-28 16:58:151488 AutocompleteMatch match = CreateSearchSuggestion(profile_, this, input_,
1489 query_string, input_text, relevance, type, accepted_suggestion,
1490 is_keyword, keyword);
1491 if (!match.destination_url.is_valid())
[email protected]85b8d6f2012-05-08 20:53:471492 return;
1493
initial.commit09911bf2008-07-26 23:55:291494 // Try to add |match| to |map|. If a match for |query_string| is already in
1495 // |map|, replace it if |match| is more relevant.
1496 // NOTE: Keep this ToLower() call in sync with url_database.cc.
1497 const std::pair<MatchMap::iterator, bool> i = map->insert(
[email protected]a2fedb1e2011-01-25 15:23:361498 std::pair<string16, AutocompleteMatch>(
[email protected]503d03872011-05-06 08:36:261499 base::i18n::ToLower(query_string), match));
initial.commit09911bf2008-07-26 23:55:291500 // NOTE: We purposefully do a direct relevance comparison here instead of
1501 // using AutocompleteMatch::MoreRelevant(), so that we'll prefer "items added
1502 // first" rather than "items alphabetically first" when the scores are equal.
1503 // The only case this matters is when a user has results with the same score
1504 // that differ only by capitalization; because the history system returns
1505 // results sorted by recency, this means we'll pick the most recent such
1506 // result even if the precision of our relevance score is too low to
1507 // distinguish the two.
1508 if (!i.second && (match.relevance > i.first->second.relevance))
1509 i.first->second = match;
1510}
1511
1512AutocompleteMatch SearchProvider::NavigationToMatch(
[email protected]188b50c2013-03-28 07:19:421513 const NavigationResult& navigation) {
1514 const string16& input = navigation.from_keyword_provider() ?
1515 keyword_input_.text() : input_.text();
[email protected]55ce8f12012-05-09 04:44:081516 AutocompleteMatch match(this, navigation.relevance(), false,
[email protected]b7f64d742013-05-21 04:04:041517 AutocompleteMatchType::NAVSUGGEST);
[email protected]55ce8f12012-05-09 04:44:081518 match.destination_url = navigation.url();
[email protected]371dab12012-06-01 03:23:551519
1520 // First look for the user's input inside the fill_into_edit as it would be
1521 // without trimming the scheme, so we can find matches at the beginning of the
1522 // scheme.
[email protected]a1b5e862013-03-29 06:38:441523 const string16& untrimmed_fill_into_edit = navigation.formatted_url();
[email protected]371dab12012-06-01 03:23:551524 const URLPrefix* prefix =
1525 URLPrefix::BestURLPrefix(untrimmed_fill_into_edit, input);
1526 size_t match_start = (prefix == NULL) ?
1527 untrimmed_fill_into_edit.find(input) : prefix->prefix.length();
1528 size_t inline_autocomplete_offset = (prefix == NULL) ?
1529 string16::npos : (match_start + input.length());
1530 bool trim_http = !HasHTTPScheme(input) && (!prefix || (match_start != 0));
1531
1532 // Preserve the forced query '?' prefix in |match.fill_into_edit|.
1533 // Otherwise, user edits to a suggestion would show non-Search results.
1534 if (input_.type() == AutocompleteInput::FORCED_QUERY) {
1535 match.fill_into_edit = ASCIIToUTF16("?");
1536 if (inline_autocomplete_offset != string16::npos)
1537 ++inline_autocomplete_offset;
1538 }
1539
1540 const std::string languages(
1541 profile_->GetPrefs()->GetString(prefs::kAcceptLanguages));
1542 const net::FormatUrlTypes format_types =
1543 net::kFormatUrlOmitAll & ~(trim_http ? 0 : net::kFormatUrlOmitHTTP);
1544 match.fill_into_edit +=
1545 AutocompleteInput::FormattedStringWithEquivalentMeaning(navigation.url(),
1546 net::FormatUrl(navigation.url(), languages, format_types,
1547 net::UnescapeRule::SPACES, NULL, NULL,
1548 &inline_autocomplete_offset));
1549 if (!input_.prevent_inline_autocomplete())
1550 match.inline_autocomplete_offset = inline_autocomplete_offset;
1551 DCHECK((match.inline_autocomplete_offset == string16::npos) ||
1552 (match.inline_autocomplete_offset <= match.fill_into_edit.length()));
1553
1554 match.contents = net::FormatUrl(navigation.url(), languages,
1555 format_types, net::UnescapeRule::SPACES, NULL, NULL, &match_start);
1556 // If the first match in the untrimmed string was inside a scheme that we
1557 // trimmed, look for a subsequent match.
1558 if (match_start == string16::npos)
1559 match_start = match.contents.find(input);
1560 // Safe if |match_start| is npos; also safe if the input is longer than the
1561 // remaining contents after |match_start|.
1562 AutocompleteMatch::ClassifyLocationInString(match_start, input.length(),
1563 match.contents.length(), ACMatchClassification::URL,
1564 &match.contents_class);
initial.commit09911bf2008-07-26 23:55:291565
[email protected]55ce8f12012-05-09 04:44:081566 match.description = navigation.description();
[email protected]371dab12012-06-01 03:23:551567 AutocompleteMatch::ClassifyMatchInString(input, match.description,
1568 ACMatchClassification::NONE, &match.description_class);
initial.commit09911bf2008-07-26 23:55:291569 return match;
1570}
[email protected]4ab4c7c2010-11-24 04:49:341571
[email protected]9dfb4d362013-04-05 02:15:121572void SearchProvider::DemoteKeywordNavigationMatchesPastTopQuery() {
[email protected]d519d392013-03-27 09:24:461573 // First, determine the maximum score of any keyword query match (verbatim or
1574 // query suggestion).
1575 int max_query_relevance = GetKeywordVerbatimRelevance();
[email protected]cc1526e2013-05-17 04:04:241576 if (!keyword_results_.suggest_results.empty()) {
[email protected]d519d392013-03-27 09:24:461577 max_query_relevance =
[email protected]cc1526e2013-05-17 04:04:241578 std::max(keyword_results_.suggest_results.front().relevance(),
[email protected]9dfb4d362013-04-05 02:15:121579 max_query_relevance);
[email protected]d519d392013-03-27 09:24:461580 }
1581 // If no query is supposed to appear, then navigational matches cannot
[email protected]9dfb4d362013-04-05 02:15:121582 // be demoted past it. Get rid of suggested relevance scores for
1583 // navsuggestions and introduce the verbatim results again. The keyword
1584 // verbatim match will outscore the navsuggest matches.
1585 if (max_query_relevance == 0) {
[email protected]cc1526e2013-05-17 04:04:241586 ApplyCalculatedNavigationRelevance(&keyword_results_.navigation_results);
1587 ApplyCalculatedNavigationRelevance(&default_results_.navigation_results);
1588 keyword_results_.verbatim_relevance = -1;
1589 default_results_.verbatim_relevance = -1;
[email protected]9dfb4d362013-04-05 02:15:121590 return;
1591 }
[email protected]d519d392013-03-27 09:24:461592 // Now we know we can enforce the minimum score constraint even after
1593 // the navigation matches are demoted. Proceed to demote the navigation
1594 // matches to enforce the query-must-come-first constraint.
[email protected]d519d392013-03-27 09:24:461595 // Cap the relevance score of all results.
[email protected]cc1526e2013-05-17 04:04:241596 for (NavigationResults::iterator it =
1597 keyword_results_.navigation_results.begin();
1598 it != keyword_results_.navigation_results.end(); ++it) {
[email protected]9dfb4d362013-04-05 02:15:121599 if (it->relevance() < max_query_relevance)
1600 return;
1601 max_query_relevance = std::max(max_query_relevance - 1, 0);
1602 it->set_relevance(max_query_relevance);
[email protected]d519d392013-03-27 09:24:461603 }
[email protected]d519d392013-03-27 09:24:461604}
1605
[email protected]4ab4c7c2010-11-24 04:49:341606void SearchProvider::UpdateDone() {
[email protected]2cdf1172012-08-26 12:21:331607 // We're done when the timer isn't running, there are no suggest queries
[email protected]5fac3782013-03-06 09:32:311608 // pending, and we're not waiting on Instant.
[email protected]abe441e2013-05-06 12:35:051609 done_ = IsNonInstantSearchDone() &&
1610 (instant_finalized_ || !chrome::IsInstantEnabled(profile_));
[email protected]4ab4c7c2010-11-24 04:49:341611}