blob: 1e3739453299eb34ea9e1c8e374380aa7dfc65b8 [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]3954c3a2012-04-10 20:17:55124
[email protected]30f5bc92012-06-26 04:14:55125SearchProvider::SearchProvider(AutocompleteProviderListener* listener,
126 Profile* profile)
[email protected]35f1f4f02012-09-11 13:17:00127 : AutocompleteProvider(listener, profile,
128 AutocompleteProvider::TYPE_SEARCH),
[email protected]85b8d6f2012-05-08 20:53:47129 providers_(TemplateURLServiceFactory::GetForProfile(profile)),
[email protected]601858c02010-09-01 17:08:20130 suggest_results_pending_(0),
[email protected]dab8d52d2013-03-05 07:35:28131 has_default_suggested_relevance_(false),
132 has_keyword_suggested_relevance_(false),
133 default_verbatim_relevance_(-1),
134 keyword_verbatim_relevance_(-1),
[email protected]8e5cc282010-12-05 18:11:39135 have_suggest_results_(false),
[email protected]618d6e62012-12-16 05:55:57136 instant_finalized_(false),
137 field_trial_triggered_(false),
138 field_trial_triggered_in_session_(false) {
[email protected]4ab4c7c2010-11-24 04:49:34139}
140
[email protected]a2fedb1e2011-01-25 15:23:36141void SearchProvider::FinalizeInstantQuery(const string16& input_text,
[email protected]93b73832012-10-18 20:18:38142 const InstantSuggestion& suggestion) {
[email protected]4ab4c7c2010-11-24 04:49:34143 if (done_ || instant_finalized_)
144 return;
145
146 instant_finalized_ = true;
147 UpdateDone();
148
[email protected]e918c112010-12-08 23:03:49149 if (input_text.empty()) {
[email protected]4ab4c7c2010-11-24 04:49:34150 // We only need to update the listener if we're actually done.
151 if (done_)
152 listener_->OnProviderUpdate(false);
153 return;
154 }
155
[email protected]93b73832012-10-18 20:18:38156 default_provider_suggestion_ = suggestion;
[email protected]9e789742011-01-10 23:27:32157
[email protected]a2fedb1e2011-01-25 15:23:36158 string16 adjusted_input_text(input_text);
[email protected]e918c112010-12-08 23:03:49159 AutocompleteInput::RemoveForcedQueryStringIfNecessary(input_.type(),
160 &adjusted_input_text);
161
[email protected]93b73832012-10-18 20:18:38162 const string16 text = adjusted_input_text + suggestion.text;
[email protected]9acdcdc02012-05-21 20:58:36163 bool results_updated = false;
[email protected]4ab4c7c2010-11-24 04:49:34164 // Remove any matches that are identical to |text|. We don't use the
165 // destination_url for comparison as it varies depending upon the index passed
166 // to TemplateURL::ReplaceSearchTerms.
167 for (ACMatches::iterator i = matches_.begin(); i != matches_.end();) {
168 if (((i->type == AutocompleteMatch::SEARCH_HISTORY) ||
169 (i->type == AutocompleteMatch::SEARCH_SUGGEST)) &&
170 (i->fill_into_edit == text)) {
[email protected]e030de62010-11-24 05:41:19171 i = matches_.erase(i);
[email protected]9acdcdc02012-05-21 20:58:36172 results_updated = true;
[email protected]4ab4c7c2010-11-24 04:49:34173 } else {
174 ++i;
175 }
176 }
177
[email protected]5fac3782013-03-06 09:32:31178 // Add the new Instant suggest result.
[email protected]93b73832012-10-18 20:18:38179 if (suggestion.type == INSTANT_SUGGESTION_SEARCH) {
[email protected]90fe2bb2013-01-15 03:42:13180 // Instant has a query suggestion. Rank it higher than SEARCH_WHAT_YOU_TYPED
181 // so that it gets autocompleted.
182 const int verbatim_relevance = GetVerbatimRelevance();
[email protected]93b73832012-10-18 20:18:38183 int did_not_accept_default_suggestion = default_suggest_results_.empty() ?
[email protected]4ab4c7c2010-11-24 04:49:34184 TemplateURLRef::NO_SUGGESTIONS_AVAILABLE :
185 TemplateURLRef::NO_SUGGESTION_CHOSEN;
[email protected]93b73832012-10-18 20:18:38186 MatchMap match_map;
187 AddMatchToMap(text, adjusted_input_text, verbatim_relevance + 1,
188 AutocompleteMatch::SEARCH_SUGGEST,
189 did_not_accept_default_suggestion, false, &match_map);
190 if (!match_map.empty()) {
191 matches_.push_back(match_map.begin()->second);
192 results_updated = true;
193 }
194 } else {
[email protected]c112f0fe72013-01-18 20:30:09195 // Instant has a URL suggestion. Rank it higher than URL_WHAT_YOU_TYPED so
[email protected]90fe2bb2013-01-15 03:42:13196 // it gets autocompleted; use kNonURLVerbatimRelevance rather than
197 // verbatim_relevance so that the score does not change if the user keeps
198 // typing and the input changes from type UNKNOWN to URL.
[email protected]93b73832012-10-18 20:18:38199 matches_.push_back(NavigationToMatch(
[email protected]a1b5e862013-03-29 06:38:44200 NavigationResult(*this,
201 GURL(UTF16ToUTF8(suggestion.text)),
[email protected]93b73832012-10-18 20:18:38202 string16(),
[email protected]188b50c2013-03-28 07:19:42203 false,
204 kNonURLVerbatimRelevance + 1)));
[email protected]9acdcdc02012-05-21 20:58:36205 results_updated = true;
206 }
[email protected]4ab4c7c2010-11-24 04:49:34207
[email protected]9acdcdc02012-05-21 20:58:36208 if (results_updated || done_)
209 listener_->OnProviderUpdate(results_updated);
[email protected]601858c02010-09-01 17:08:20210}
211
[email protected]0a633ba92013-03-26 09:13:47212void SearchProvider::ClearInstantSuggestion() {
213 default_provider_suggestion_ = InstantSuggestion();
214 if (done_ || instant_finalized_)
215 return;
216 instant_finalized_ = true;
217 UpdateMatches();
218 listener_->OnProviderUpdate(true);
219}
220
initial.commit09911bf2008-07-26 23:55:29221void SearchProvider::Start(const AutocompleteInput& input,
[email protected]8deeb952008-10-09 18:21:27222 bool minimal_changes) {
[email protected]04504c242013-01-22 21:08:55223 // Do our best to load the model as early as possible. This will reduce
224 // odds of having the model not ready when really needed (a non-empty input).
225 TemplateURLService* model = providers_.template_url_service();
226 DCHECK(model);
227 model->Load();
228
initial.commit09911bf2008-07-26 23:55:29229 matches_.clear();
[email protected]618d6e62012-12-16 05:55:57230 field_trial_triggered_ = false;
initial.commit09911bf2008-07-26 23:55:29231
[email protected]ea3b9a502011-04-04 14:19:37232 instant_finalized_ =
233 (input.matches_requested() != AutocompleteInput::ALL_MATCHES);
[email protected]4ab4c7c2010-11-24 04:49:34234
[email protected]6c85aa02009-02-27 12:08:09235 // Can't return search/suggest results for bogus input or without a profile.
initial.commit09911bf2008-07-26 23:55:29236 if (!profile_ || (input.type() == AutocompleteInput::INVALID)) {
[email protected]e29249dc52012-07-19 17:33:50237 Stop(false);
initial.commit09911bf2008-07-26 23:55:29238 return;
239 }
240
[email protected]14710852013-02-05 23:45:41241 keyword_input_ = input;
[email protected]257ab712009-04-14 17:16:24242 const TemplateURL* keyword_provider =
[email protected]14710852013-02-05 23:45:41243 KeywordProvider::GetSubstitutingTemplateURLForInput(model,
244 &keyword_input_);
245 if (keyword_provider == NULL)
246 keyword_input_.Clear();
247 else if (keyword_input_.text().empty())
[email protected]257ab712009-04-14 17:16:24248 keyword_provider = NULL;
[email protected]257ab712009-04-14 17:16:24249
[email protected]85b8d6f2012-05-08 20:53:47250 const TemplateURL* default_provider = model->GetDefaultSearchProvider();
[email protected]9b74ab52012-03-30 16:08:07251 if (default_provider && !default_provider->SupportsReplacement())
[email protected]257ab712009-04-14 17:16:24252 default_provider = NULL;
253
254 if (keyword_provider == default_provider)
[email protected]e17511f2011-07-13 14:09:18255 default_provider = NULL; // No use in querying the same provider twice.
[email protected]257ab712009-04-14 17:16:24256
257 if (!default_provider && !keyword_provider) {
258 // No valid providers.
[email protected]e29249dc52012-07-19 17:33:50259 Stop(false);
initial.commit09911bf2008-07-26 23:55:29260 return;
261 }
262
263 // If we're still running an old query but have since changed the query text
[email protected]257ab712009-04-14 17:16:24264 // or the providers, abort the query.
[email protected]85b8d6f2012-05-08 20:53:47265 string16 default_provider_keyword(default_provider ?
266 default_provider->keyword() : string16());
267 string16 keyword_provider_keyword(keyword_provider ?
268 keyword_provider->keyword() : string16());
[email protected]9e789742011-01-10 23:27:32269 if (!minimal_changes ||
[email protected]85b8d6f2012-05-08 20:53:47270 !providers_.equal(default_provider_keyword, keyword_provider_keyword)) {
[email protected]bb900e02013-03-14 14:15:29271 // If Instant has not come back with a suggestion, adjust the previous
272 // suggestion if possible. If |instant_finalized| is true, we are looking
273 // for synchronous matches only, so the suggestion is cleared.
274 if (instant_finalized_)
[email protected]93b73832012-10-18 20:18:38275 default_provider_suggestion_ = InstantSuggestion();
[email protected]9e789742011-01-10 23:27:32276 else
[email protected]bb900e02013-03-14 14:15:29277 AdjustDefaultProviderSuggestion(input_.text(), input.text());
278
279 // Cancel any in-flight suggest requests.
280 if (!done_) {
281 // The Stop(false) call below clears |default_provider_suggestion_|, but
282 // in this instance we do not want to clear cached results, so we
283 // restore it.
284 base::AutoReset<InstantSuggestion> reset(&default_provider_suggestion_,
285 InstantSuggestion());
[email protected]e29249dc52012-07-19 17:33:50286 Stop(false);
[email protected]bb900e02013-03-14 14:15:29287 }
[email protected]257ab712009-04-14 17:16:24288 }
initial.commit09911bf2008-07-26 23:55:29289
[email protected]85b8d6f2012-05-08 20:53:47290 providers_.set(default_provider_keyword, keyword_provider_keyword);
initial.commit09911bf2008-07-26 23:55:29291
292 if (input.text().empty()) {
293 // User typed "?" alone. Give them a placeholder result indicating what
294 // this syntax does.
[email protected]257ab712009-04-14 17:16:24295 if (default_provider) {
[email protected]69c579e2010-04-23 20:01:00296 AutocompleteMatch match;
297 match.provider = this;
[email protected]a2fedb1e2011-01-25 15:23:36298 match.contents.assign(l10n_util::GetStringUTF16(IDS_EMPTY_KEYWORD_VALUE));
[email protected]257ab712009-04-14 17:16:24299 match.contents_class.push_back(
[email protected]2c33dd22010-02-11 21:46:35300 ACMatchClassification(0, ACMatchClassification::NONE));
[email protected]85b8d6f2012-05-08 20:53:47301 match.keyword = providers_.default_provider();
[email protected]257ab712009-04-14 17:16:24302 matches_.push_back(match);
303 }
[email protected]e29249dc52012-07-19 17:33:50304 Stop(false);
initial.commit09911bf2008-07-26 23:55:29305 return;
306 }
307
308 input_ = input;
309
[email protected]5fac3782013-03-06 09:32:31310 // When Instant is enabled in the extended mode, the embedded page will handle
311 // all search suggestions itself, so don't run the normal provider flow.
312 // TODO(dcblack): Once we are done refactoring the omnibox so we don't need to
[email protected]5cd06c3e2012-09-20 03:25:20313 // use FinalizeInstantQuery anymore, we can take out this check and remove
314 // this provider from kInstantExtendedOmniboxProviders.
[email protected]165fe422013-03-27 06:34:03315 if (!chrome::IsInstantExtendedAPIEnabled() ||
316 !chrome::IsInstantEnabled(profile_)) {
[email protected]5cd06c3e2012-09-20 03:25:20317 DoHistoryQuery(minimal_changes);
318 StartOrStopSuggestQuery(minimal_changes);
319 }
[email protected]344946a12012-12-20 12:03:42320 UpdateMatches();
initial.commit09911bf2008-07-26 23:55:29321}
322
[email protected]188b50c2013-03-28 07:19:42323SearchProvider::Result::Result(bool from_keyword_provider, int relevance)
324 : from_keyword_provider_(from_keyword_provider),
325 relevance_(relevance) {
326}
327
[email protected]55ce8f12012-05-09 04:44:08328SearchProvider::Result::~Result() {}
329
330SearchProvider::SuggestResult::SuggestResult(const string16& suggestion,
[email protected]188b50c2013-03-28 07:19:42331 bool from_keyword_provider,
[email protected]55ce8f12012-05-09 04:44:08332 int relevance)
[email protected]188b50c2013-03-28 07:19:42333 : Result(from_keyword_provider, relevance),
[email protected]55ce8f12012-05-09 04:44:08334 suggestion_(suggestion) {
335}
336
337SearchProvider::SuggestResult::~SuggestResult() {}
338
[email protected]a1b5e862013-03-29 06:38:44339bool SearchProvider::SuggestResult::IsInlineable(const string16& input) const {
340 return StartsWith(suggestion_, input, false);
341}
342
[email protected]188b50c2013-03-28 07:19:42343int SearchProvider::SuggestResult::CalculateRelevance(
344 const AutocompleteInput& input,
345 bool keyword_provider_requested) const {
346 if (!from_keyword_provider_ && keyword_provider_requested)
347 return 100;
348 return ((input.type() == AutocompleteInput::URL) ? 300 : 600);
349}
350
351SearchProvider::NavigationResult::NavigationResult(
[email protected]a1b5e862013-03-29 06:38:44352 const AutocompleteProvider& provider,
[email protected]188b50c2013-03-28 07:19:42353 const GURL& url,
354 const string16& description,
355 bool from_keyword_provider,
356 int relevance)
357 : Result(from_keyword_provider, relevance),
[email protected]55ce8f12012-05-09 04:44:08358 url_(url),
[email protected]a1b5e862013-03-29 06:38:44359 formatted_url_(AutocompleteInput::FormattedStringWithEquivalentMeaning(
360 url, provider.StringForURLDisplay(url, true, false))),
[email protected]55ce8f12012-05-09 04:44:08361 description_(description) {
362 DCHECK(url_.is_valid());
363}
364
[email protected]a1b5e862013-03-29 06:38:44365SearchProvider::NavigationResult::~NavigationResult() {}
366
367bool SearchProvider::NavigationResult::IsInlineable(
368 const string16& input) const {
369 return URLPrefix::BestURLPrefix(formatted_url_, input) != NULL;
370}
371
[email protected]188b50c2013-03-28 07:19:42372int SearchProvider::NavigationResult::CalculateRelevance(
373 const AutocompleteInput& input,
374 bool keyword_provider_requested) const {
375 return (from_keyword_provider_ || !keyword_provider_requested) ? 800 : 150;
376}
377
[email protected]55ce8f12012-05-09 04:44:08378class SearchProvider::CompareScoredResults {
[email protected]51124552011-07-16 01:37:10379 public:
[email protected]55ce8f12012-05-09 04:44:08380 bool operator()(const Result& a, const Result& b) {
[email protected]51124552011-07-16 01:37:10381 // Sort in descending relevance order.
[email protected]55ce8f12012-05-09 04:44:08382 return a.relevance() > b.relevance();
[email protected]51124552011-07-16 01:37:10383 }
384};
385
initial.commit09911bf2008-07-26 23:55:29386void SearchProvider::Run() {
387 // Start a new request with the current input.
[email protected]257ab712009-04-14 17:16:24388 suggest_results_pending_ = 0;
[email protected]a0ad93ea2012-05-07 22:11:53389 time_suggest_request_sent_ = base::TimeTicks::Now();
[email protected]9ff91722012-09-07 05:29:12390
391 default_fetcher_.reset(CreateSuggestFetcher(kDefaultProviderURLFetcherID,
[email protected]14710852013-02-05 23:45:41392 providers_.GetDefaultProviderURL(), input_));
[email protected]9ff91722012-09-07 05:29:12393 keyword_fetcher_.reset(CreateSuggestFetcher(kKeywordProviderURLFetcherID,
[email protected]14710852013-02-05 23:45:41394 providers_.GetKeywordProviderURL(), keyword_input_));
[email protected]85b8d6f2012-05-08 20:53:47395
396 // Both the above can fail if the providers have been modified or deleted
397 // since the query began.
398 if (suggest_results_pending_ == 0) {
399 UpdateDone();
400 // We only need to update the listener if we're actually done.
401 if (done_)
402 listener_->OnProviderUpdate(false);
403 }
initial.commit09911bf2008-07-26 23:55:29404}
405
[email protected]e29249dc52012-07-19 17:33:50406void SearchProvider::Stop(bool clear_cached_results) {
initial.commit09911bf2008-07-26 23:55:29407 StopSuggest();
408 done_ = true;
[email protected]93b73832012-10-18 20:18:38409 default_provider_suggestion_ = InstantSuggestion();
[email protected]e29249dc52012-07-19 17:33:50410
411 if (clear_cached_results)
412 ClearResults();
initial.commit09911bf2008-07-26 23:55:29413}
414
[email protected]0e9e8782012-05-15 23:01:51415void SearchProvider::AddProviderInfo(ProvidersInfo* provider_info) const {
416 provider_info->push_back(metrics::OmniboxEventProto_ProviderInfo());
417 metrics::OmniboxEventProto_ProviderInfo& new_entry = provider_info->back();
418 new_entry.set_provider(AsOmniboxEventProviderType());
419 new_entry.set_provider_done(done_);
[email protected]618d6e62012-12-16 05:55:57420 uint32 field_trial_hash = 0;
[email protected]684fcc12013-03-08 22:50:02421 if (OmniboxFieldTrial::GetActiveSuggestFieldTrialHash(&field_trial_hash)) {
[email protected]618d6e62012-12-16 05:55:57422 if (field_trial_triggered_)
423 new_entry.mutable_field_trial_triggered()->Add(field_trial_hash);
[email protected]d78d7362012-12-19 18:43:28424 if (field_trial_triggered_in_session_) {
[email protected]618d6e62012-12-16 05:55:57425 new_entry.mutable_field_trial_triggered_in_session()->Add(
426 field_trial_hash);
[email protected]d78d7362012-12-19 18:43:28427 }
[email protected]618d6e62012-12-16 05:55:57428 }
429}
430
431void SearchProvider::ResetSession() {
432 field_trial_triggered_in_session_ = false;
[email protected]0e9e8782012-05-15 23:01:51433}
434
[email protected]10c2d692012-05-11 05:32:23435void SearchProvider::OnURLFetchComplete(const net::URLFetcher* source) {
initial.commit09911bf2008-07-26 23:55:29436 DCHECK(!done_);
[email protected]257ab712009-04-14 17:16:24437 suggest_results_pending_--;
[email protected]7706a522012-08-16 17:42:25438 LogOmniboxSuggestRequest(REPLY_RECEIVED);
[email protected]1cb2dac2010-03-08 21:49:15439 DCHECK_GE(suggest_results_pending_, 0); // Should never go negative.
[email protected]ec9207d32008-09-26 00:51:06440 const net::HttpResponseHeaders* const response_headers =
[email protected]7cc6e5632011-10-25 17:56:12441 source->GetResponseHeaders();
[email protected]c530c852011-10-24 18:18:34442 std::string json_data;
443 source->GetResponseAsString(&json_data);
[email protected]6c85aa02009-02-27 12:08:09444 // JSON is supposed to be UTF-8, but some suggest service providers send JSON
445 // files in non-UTF-8 encodings. The actual encoding is usually specified in
446 // the Content-Type header field.
[email protected]ec9207d32008-09-26 00:51:06447 if (response_headers) {
448 std::string charset;
449 if (response_headers->GetCharset(&charset)) {
[email protected]a2fedb1e2011-01-25 15:23:36450 string16 data_16;
[email protected]ec9207d32008-09-26 00:51:06451 // TODO(jungshik): Switch to CodePageToUTF8 after it's added.
[email protected]c530c852011-10-24 18:18:34452 if (base::CodepageToUTF16(json_data, charset.c_str(),
[email protected]a2fedb1e2011-01-25 15:23:36453 base::OnStringConversionError::FAIL,
454 &data_16))
455 json_data = UTF16ToUTF8(data_16);
[email protected]ec9207d32008-09-26 00:51:06456 }
457 }
458
[email protected]d7ad4772012-06-01 03:12:54459 const bool is_keyword = (source == keyword_fetcher_.get());
[email protected]f2916ea2013-01-26 02:20:14460 // Ensure the request succeeded and that the provider used is still available.
461 // A verbatim match cannot be generated without this provider, causing errors.
[email protected]013e9a02012-05-18 20:27:10462 const bool request_succeeded =
[email protected]f2916ea2013-01-26 02:20:14463 source->GetStatus().is_success() && source->GetResponseCode() == 200 &&
464 ((is_keyword && providers_.GetKeywordProviderURL()) ||
465 (!is_keyword && providers_.GetDefaultProviderURL()));
[email protected]a0ad93ea2012-05-07 22:11:53466
467 // Record response time for suggest requests sent to Google. We care
468 // only about the common case: the Google default provider used in
469 // non-keyword mode.
[email protected]85b8d6f2012-05-08 20:53:47470 const TemplateURL* default_url = providers_.GetDefaultProviderURL();
[email protected]55ce8f12012-05-09 04:44:08471 if (!is_keyword && default_url &&
[email protected]9899a612012-08-21 23:50:04472 (TemplateURLPrepopulateData::GetEngineType(default_url->url()) ==
473 SEARCH_ENGINE_GOOGLE)) {
[email protected]6dc950f2012-07-16 19:49:08474 const TimeDelta elapsed_time =
[email protected]013e9a02012-05-18 20:27:10475 base::TimeTicks::Now() - time_suggest_request_sent_;
476 if (request_succeeded) {
477 UMA_HISTOGRAM_TIMES("Omnibox.SuggestRequest.Success.GoogleResponseTime",
478 elapsed_time);
479 } else {
480 UMA_HISTOGRAM_TIMES("Omnibox.SuggestRequest.Failure.GoogleResponseTime",
481 elapsed_time);
482 }
[email protected]b4cebf82008-12-29 19:59:08483 }
484
[email protected]d7ad4772012-06-01 03:12:54485 bool results_updated = false;
486 if (request_succeeded) {
487 JSONStringValueSerializer deserializer(json_data);
488 deserializer.set_allow_trailing_comma(true);
489 scoped_ptr<Value> data(deserializer.Deserialize(NULL, NULL));
490 results_updated = data.get() && ParseSuggestResults(data.get(), is_keyword);
491 }
492
[email protected]344946a12012-12-20 12:03:42493 UpdateMatches();
[email protected]d7ad4772012-06-01 03:12:54494 if (done_ || results_updated)
495 listener_->OnProviderUpdate(results_updated);
initial.commit09911bf2008-07-26 23:55:29496}
497
[email protected]601858c02010-09-01 17:08:20498SearchProvider::~SearchProvider() {
499}
500
[email protected]8d457132010-11-04 18:13:40501void SearchProvider::DoHistoryQuery(bool minimal_changes) {
502 // The history query results are synchronous, so if minimal_changes is true,
503 // we still have the last results and don't need to do anything.
504 if (minimal_changes)
initial.commit09911bf2008-07-26 23:55:29505 return;
506
[email protected]8d457132010-11-04 18:13:40507 keyword_history_results_.clear();
508 default_history_results_.clear();
initial.commit09911bf2008-07-26 23:55:29509
[email protected]8d457132010-11-04 18:13:40510 HistoryService* const history_service =
[email protected]9d2db762012-06-19 00:01:10511 HistoryServiceFactory::GetForProfile(profile_, Profile::EXPLICIT_ACCESS);
[email protected]8d457132010-11-04 18:13:40512 history::URLDatabase* url_db = history_service ?
513 history_service->InMemoryDatabase() : NULL;
514 if (!url_db)
initial.commit09911bf2008-07-26 23:55:29515 return;
516
[email protected]51124552011-07-16 01:37:10517 // Request history for both the keyword and default provider. We grab many
518 // more matches than we'll ultimately clamp to so that if there are several
519 // recent multi-word matches who scores are lowered (see
520 // AddHistoryResultsToMap()), they won't crowd out older, higher-scoring
521 // matches. Note that this doesn't fix the problem entirely, but merely
522 // limits it to cases with a very large number of such multi-word matches; for
523 // now, this seems OK compared with the complexity of a real fix, which would
524 // require multiple searches and tracking of "single- vs. multi-word" in the
525 // database.
526 int num_matches = kMaxMatches * 5;
[email protected]85b8d6f2012-05-08 20:53:47527 const TemplateURL* default_url = providers_.GetDefaultProviderURL();
528 if (default_url) {
529 url_db->GetMostRecentKeywordSearchTerms(default_url->id(), input_.text(),
530 num_matches, &default_history_results_);
[email protected]257ab712009-04-14 17:16:24531 }
[email protected]85b8d6f2012-05-08 20:53:47532 const TemplateURL* keyword_url = providers_.GetKeywordProviderURL();
533 if (keyword_url) {
534 url_db->GetMostRecentKeywordSearchTerms(keyword_url->id(),
[email protected]14710852013-02-05 23:45:41535 keyword_input_.text(), num_matches, &keyword_history_results_);
[email protected]3954c3a2012-04-10 20:17:55536 }
initial.commit09911bf2008-07-26 23:55:29537}
538
[email protected]6dc950f2012-07-16 19:49:08539void SearchProvider::StartOrStopSuggestQuery(bool minimal_changes) {
[email protected]83c726482008-09-10 06:36:34540 if (!IsQuerySuitableForSuggest()) {
initial.commit09911bf2008-07-26 23:55:29541 StopSuggest();
[email protected]55ce8f12012-05-09 04:44:08542 ClearResults();
initial.commit09911bf2008-07-26 23:55:29543 return;
544 }
545
546 // For the minimal_changes case, if we finished the previous query and still
547 // have its results, or are allowed to keep running it, just do that, rather
548 // than starting a new query.
549 if (minimal_changes &&
[email protected]ea3b9a502011-04-04 14:19:37550 (have_suggest_results_ ||
551 (!done_ &&
552 input_.matches_requested() == AutocompleteInput::ALL_MATCHES)))
initial.commit09911bf2008-07-26 23:55:29553 return;
554
555 // We can't keep running any previous query, so halt it.
556 StopSuggest();
[email protected]d1f0a7f2012-06-05 10:26:42557
558 // Remove existing results that cannot inline autocomplete the new input.
559 RemoveStaleResults();
initial.commit09911bf2008-07-26 23:55:29560
561 // We can't start a new query if we're only allowed synchronous results.
[email protected]ea3b9a502011-04-04 14:19:37562 if (input_.matches_requested() != AutocompleteInput::ALL_MATCHES)
initial.commit09911bf2008-07-26 23:55:29563 return;
564
[email protected]515ffa942012-11-27 20:18:24565 // To avoid flooding the suggest server, don't send a query until at least 100
566 // ms since the last query.
567 const int kMinimumTimeBetweenSuggestQueriesMs = 100;
568 base::TimeTicks next_suggest_time(time_suggest_request_sent_ +
569 TimeDelta::FromMilliseconds(kMinimumTimeBetweenSuggestQueriesMs));
570 base::TimeTicks now(base::TimeTicks::Now());
571 if (now >= next_suggest_time) {
572 Run();
573 return;
574 }
575 timer_.Start(FROM_HERE, next_suggest_time - now, this, &SearchProvider::Run);
initial.commit09911bf2008-07-26 23:55:29576}
577
[email protected]83c726482008-09-10 06:36:34578bool SearchProvider::IsQuerySuitableForSuggest() const {
[email protected]3954c3a2012-04-10 20:17:55579 // Don't run Suggest in incognito mode, if the engine doesn't support it, or
580 // if the user has disabled it.
[email protected]85b8d6f2012-05-08 20:53:47581 const TemplateURL* default_url = providers_.GetDefaultProviderURL();
582 const TemplateURL* keyword_url = providers_.GetKeywordProviderURL();
[email protected]83c726482008-09-10 06:36:34583 if (profile_->IsOffTheRecord() ||
[email protected]85b8d6f2012-05-08 20:53:47584 ((!default_url || default_url->suggestions_url().empty()) &&
585 (!keyword_url || keyword_url->suggestions_url().empty())) ||
[email protected]83c726482008-09-10 06:36:34586 !profile_->GetPrefs()->GetBoolean(prefs::kSearchSuggestEnabled))
587 return false;
588
[email protected]cac59d32010-08-09 23:23:14589 // If the input type might be a URL, we take extra care so that private data
[email protected]83c726482008-09-10 06:36:34590 // isn't sent to the server.
[email protected]83c726482008-09-10 06:36:34591
[email protected]cac59d32010-08-09 23:23:14592 // FORCED_QUERY means the user is explicitly asking us to search for this, so
593 // we assume it isn't a URL and/or there isn't private data.
594 if (input_.type() == AutocompleteInput::FORCED_QUERY)
595 return true;
[email protected]83c726482008-09-10 06:36:34596
[email protected]f608ea102013-03-18 15:08:09597 // Next we check the scheme. If this is UNKNOWN/URL with a scheme that isn't
598 // http/https/ftp, we shouldn't send it. Sending things like file: and data:
599 // is both a waste of time and a disclosure of potentially private, local
600 // data. Other "schemes" may actually be usernames, and we don't want to send
601 // passwords. If the scheme is OK, we still need to check other cases below.
602 // If this is QUERY, then the presence of these schemes means the user
603 // explicitly typed one, and thus this is probably a URL that's being entered
604 // and happens to currently be invalid -- in which case we again want to run
605 // our checks below. Other QUERY cases are less likely to be URLs and thus we
606 // assume we're OK.
[email protected]a2fedb1e2011-01-25 15:23:36607 if (!LowerCaseEqualsASCII(input_.scheme(), chrome::kHttpScheme) &&
608 !LowerCaseEqualsASCII(input_.scheme(), chrome::kHttpsScheme) &&
609 !LowerCaseEqualsASCII(input_.scheme(), chrome::kFtpScheme))
[email protected]cac59d32010-08-09 23:23:14610 return (input_.type() == AutocompleteInput::QUERY);
611
612 // Don't send URLs with usernames, queries or refs. Some of these are
613 // private, and the Suggest server is unlikely to have any useful results
614 // for any of them. Also don't send URLs with ports, as we may initially
615 // think that a username + password is a host + port (and we don't want to
616 // send usernames/passwords), and even if the port really is a port, the
617 // server is once again unlikely to have and useful results.
618 const url_parse::Parsed& parts = input_.parts();
619 if (parts.username.is_nonempty() || parts.port.is_nonempty() ||
620 parts.query.is_nonempty() || parts.ref.is_nonempty())
621 return false;
622
623 // Don't send anything for https except the hostname. Hostnames are OK
624 // because they are visible when the TCP connection is established, but the
625 // specific path may reveal private information.
[email protected]a2fedb1e2011-01-25 15:23:36626 if (LowerCaseEqualsASCII(input_.scheme(), chrome::kHttpsScheme) &&
627 parts.path.is_nonempty())
[email protected]cac59d32010-08-09 23:23:14628 return false;
[email protected]83c726482008-09-10 06:36:34629
630 return true;
631}
632
initial.commit09911bf2008-07-26 23:55:29633void SearchProvider::StopSuggest() {
[email protected]7706a522012-08-16 17:42:25634 // Increment the appropriate field in the histogram by the number of
635 // pending requests that were invalidated.
636 for (int i = 0; i < suggest_results_pending_; i++)
637 LogOmniboxSuggestRequest(REQUEST_INVALIDATED);
[email protected]257ab712009-04-14 17:16:24638 suggest_results_pending_ = 0;
[email protected]2d316662008-09-03 18:18:14639 timer_.Stop();
[email protected]257ab712009-04-14 17:16:24640 // Stop any in-progress URL fetches.
641 keyword_fetcher_.reset();
642 default_fetcher_.reset();
[email protected]55ce8f12012-05-09 04:44:08643}
644
645void SearchProvider::ClearResults() {
[email protected]257ab712009-04-14 17:16:24646 keyword_suggest_results_.clear();
647 default_suggest_results_.clear();
648 keyword_navigation_results_.clear();
649 default_navigation_results_.clear();
[email protected]dab8d52d2013-03-05 07:35:28650 has_default_suggested_relevance_ = false;
651 has_keyword_suggested_relevance_ = false;
652 default_verbatim_relevance_ = -1;
653 keyword_verbatim_relevance_ = -1;
initial.commit09911bf2008-07-26 23:55:29654 have_suggest_results_ = false;
initial.commit09911bf2008-07-26 23:55:29655}
656
[email protected]d1f0a7f2012-06-05 10:26:42657void SearchProvider::RemoveStaleResults() {
[email protected]14710852013-02-05 23:45:41658 // Keyword provider results should match |keyword_input_.text()|, unless
[email protected]42cfd01d02013-01-23 02:40:02659 // the input was just changed to non-keyword mode; in that case, compare
660 // against |input_.text()|.
661 const string16& keyword_input =
[email protected]14710852013-02-05 23:45:41662 !keyword_input_.text().empty() ? keyword_input_.text() : input_.text();
[email protected]42cfd01d02013-01-23 02:40:02663 RemoveStaleSuggestResults(&keyword_suggest_results_, keyword_input);
664 RemoveStaleSuggestResults(&default_suggest_results_, input_.text());
665 RemoveStaleNavigationResults(&keyword_navigation_results_, keyword_input);
666 RemoveStaleNavigationResults(&default_navigation_results_, input_.text());
[email protected]d1f0a7f2012-06-05 10:26:42667}
668
[email protected]42cfd01d02013-01-23 02:40:02669// static
[email protected]d1f0a7f2012-06-05 10:26:42670void SearchProvider::RemoveStaleSuggestResults(SuggestResults* list,
[email protected]42cfd01d02013-01-23 02:40:02671 const string16& input) {
[email protected]d1f0a7f2012-06-05 10:26:42672 for (SuggestResults::iterator i = list->begin(); i < list->end();)
[email protected]a1b5e862013-03-29 06:38:44673 i = i->IsInlineable(input) ? (i + 1) : list->erase(i);
[email protected]d1f0a7f2012-06-05 10:26:42674}
675
[email protected]a1b5e862013-03-29 06:38:44676// static
[email protected]d1f0a7f2012-06-05 10:26:42677void SearchProvider::RemoveStaleNavigationResults(NavigationResults* list,
[email protected]42cfd01d02013-01-23 02:40:02678 const string16& input) {
[email protected]d1f0a7f2012-06-05 10:26:42679 for (NavigationResults::iterator i = list->begin(); i < list->end();) {
[email protected]a1b5e862013-03-29 06:38:44680 i = i->IsInlineable(input) ? (i + 1) : list->erase(i);
[email protected]d1f0a7f2012-06-05 10:26:42681 }
682}
683
[email protected]bb900e02013-03-14 14:15:29684void SearchProvider::AdjustDefaultProviderSuggestion(
685 const string16& previous_input,
686 const string16& current_input) {
687 if (default_provider_suggestion_.type == INSTANT_SUGGESTION_URL) {
688 // Build a list of NavigationResults with only one NavigationResult in it,
689 // initialized with the URL in the navigation suggestion. This allows the
690 // use of RemoveStaleNavigationResults(), which has non-trivial logic to
691 // determine staleness.
692 NavigationResults list;
693 // Description and relevance do not matter in the check for staleness.
[email protected]a1b5e862013-03-29 06:38:44694 NavigationResult result(*this,
695 GURL(default_provider_suggestion_.text),
[email protected]188b50c2013-03-28 07:19:42696 string16(),
697 false,
698 100);
[email protected]bb900e02013-03-14 14:15:29699 list.push_back(result);
700 RemoveStaleNavigationResults(&list, current_input);
701 // If navigation suggestion is stale, clear |default_provider_suggestion_|.
702 if (list.empty())
703 default_provider_suggestion_ = InstantSuggestion();
704 } else {
705 DCHECK(default_provider_suggestion_.type == INSTANT_SUGGESTION_SEARCH);
706 // InstantSuggestion of type SEARCH contain only the suggested text, and not
707 // the full text of the query. This looks at the current and previous input
708 // to determine if the user is typing forward, and if the new input is
709 // contained in |default_provider_suggestion_|. If so, the suggestion is
710 // adjusted and can be kept. Otherwise, it is reset.
711 if (!previous_input.empty() &&
712 StartsWith(current_input, previous_input, false)) {
713 // User is typing forward; verify if new input is part of the suggestion.
714 const string16 new_text = string16(current_input, previous_input.size());
715 if (StartsWith(default_provider_suggestion_.text, new_text, false)) {
716 // New input is a prefix to the previous suggestion, adjust the
717 // suggestion to strip the prefix.
718 default_provider_suggestion_.text.erase(0, new_text.size());
719 return;
720 }
721 }
722 // If we are here, the search suggestion is stale; reset it.
723 default_provider_suggestion_ = InstantSuggestion();
724 }
725}
726
[email protected]d1f0a7f2012-06-05 10:26:42727void SearchProvider::ApplyCalculatedRelevance() {
[email protected]188b50c2013-03-28 07:19:42728 ApplyCalculatedSuggestRelevance(&keyword_suggest_results_);
729 ApplyCalculatedSuggestRelevance(&default_suggest_results_);
730 ApplyCalculatedNavigationRelevance(&keyword_navigation_results_);
731 ApplyCalculatedNavigationRelevance(&default_navigation_results_);
[email protected]dab8d52d2013-03-05 07:35:28732 has_default_suggested_relevance_ = false;
733 has_keyword_suggested_relevance_ = false;
734 default_verbatim_relevance_ = -1;
735 keyword_verbatim_relevance_ = -1;
[email protected]d1f0a7f2012-06-05 10:26:42736}
737
[email protected]188b50c2013-03-28 07:19:42738void SearchProvider::ApplyCalculatedSuggestRelevance(SuggestResults* list) {
[email protected]d1f0a7f2012-06-05 10:26:42739 for (size_t i = 0; i < list->size(); ++i) {
[email protected]188b50c2013-03-28 07:19:42740 SuggestResult& result = (*list)[i];
741 result.set_relevance(
742 result.CalculateRelevance(input_, providers_.has_keyword_provider()) +
743 (list->size() - i - 1));
[email protected]d1f0a7f2012-06-05 10:26:42744 }
745}
746
[email protected]188b50c2013-03-28 07:19:42747void SearchProvider::ApplyCalculatedNavigationRelevance(
748 NavigationResults* list) {
[email protected]d1f0a7f2012-06-05 10:26:42749 for (size_t i = 0; i < list->size(); ++i) {
[email protected]188b50c2013-03-28 07:19:42750 NavigationResult& result = (*list)[i];
751 result.set_relevance(
752 result.CalculateRelevance(input_, providers_.has_keyword_provider()) +
753 (list->size() - i - 1));
[email protected]d1f0a7f2012-06-05 10:26:42754 }
755}
756
[email protected]15fb2aa2012-05-22 22:52:59757net::URLFetcher* SearchProvider::CreateSuggestFetcher(
[email protected]7cc6e5632011-10-25 17:56:12758 int id,
[email protected]9ff91722012-09-07 05:29:12759 const TemplateURL* template_url,
[email protected]14710852013-02-05 23:45:41760 const AutocompleteInput& input) {
[email protected]9ff91722012-09-07 05:29:12761 if (!template_url || template_url->suggestions_url().empty())
762 return NULL;
763
764 // Bail if the suggestion URL is invalid with the given replacements.
[email protected]14710852013-02-05 23:45:41765 TemplateURLRef::SearchTermsArgs search_term_args(input.text());
766 search_term_args.cursor_position = input.cursor_position();
[email protected]9ff91722012-09-07 05:29:12767 GURL suggest_url(template_url->suggestions_url_ref().ReplaceSearchTerms(
[email protected]00790562012-12-14 09:57:16768 search_term_args));
[email protected]9ff91722012-09-07 05:29:12769 if (!suggest_url.is_valid())
770 return NULL;
771
772 suggest_results_pending_++;
773 LogOmniboxSuggestRequest(REQUEST_SENT);
774
775 net::URLFetcher* fetcher =
776 net::URLFetcher::Create(id, suggest_url, net::URLFetcher::GET, this);
[email protected]7cc6e5632011-10-25 17:56:12777 fetcher->SetRequestContext(profile_->GetRequestContext());
[email protected]d3cf8682f02012-02-29 23:29:34778 fetcher->SetLoadFlags(net::LOAD_DO_NOT_SAVE_COOKIES);
[email protected]bd3b4712012-12-18 17:01:30779 // Add Chrome experiment state to the request headers.
780 net::HttpRequestHeaders headers;
[email protected]ab7780792013-01-10 01:26:09781 chrome_variations::VariationsHttpHeaderProvider::GetInstance()->AppendHeaders(
[email protected]bd3b4712012-12-18 17:01:30782 fetcher->GetOriginalURL(), profile_->IsOffTheRecord(), false, &headers);
783 fetcher->SetExtraRequestHeaders(headers.ToString());
[email protected]257ab712009-04-14 17:16:24784 fetcher->Start();
785 return fetcher;
786}
787
[email protected]d7ad4772012-06-01 03:12:54788bool SearchProvider::ParseSuggestResults(Value* root_val, bool is_keyword) {
789 // TODO(pkasting): Fix |have_suggest_results_|; see http://crbug.com/130631
790 have_suggest_results_ = false;
initial.commit09911bf2008-07-26 23:55:29791
[email protected]d7ad4772012-06-01 03:12:54792 string16 query;
793 ListValue* root_list = NULL;
794 ListValue* results = NULL;
[email protected]14710852013-02-05 23:45:41795 const string16& input_text =
796 is_keyword ? keyword_input_.text() : input_.text();
[email protected]d7ad4772012-06-01 03:12:54797 if (!root_val->GetAsList(&root_list) || !root_list->GetString(0, &query) ||
798 (query != input_text) || !root_list->GetList(1, &results))
initial.commit09911bf2008-07-26 23:55:29799 return false;
800
[email protected]55ce8f12012-05-09 04:44:08801 // 3rd element: Description list.
[email protected]d7ad4772012-06-01 03:12:54802 ListValue* descriptions = NULL;
803 root_list->GetList(2, &descriptions);
initial.commit09911bf2008-07-26 23:55:29804
[email protected]55ce8f12012-05-09 04:44:08805 // 4th element: Disregard the query URL list for now.
initial.commit09911bf2008-07-26 23:55:29806
[email protected]d1f0a7f2012-06-05 10:26:42807 // Reset suggested relevance information from the default provider.
[email protected]dab8d52d2013-03-05 07:35:28808 bool* has_suggested_relevance = is_keyword ?
809 &has_keyword_suggested_relevance_ : &has_default_suggested_relevance_;
810 *has_suggested_relevance = false;
811 int* verbatim_relevance = is_keyword ?
812 &keyword_verbatim_relevance_ : &default_verbatim_relevance_;
813 *verbatim_relevance = -1;
[email protected]d1f0a7f2012-06-05 10:26:42814
[email protected]55ce8f12012-05-09 04:44:08815 // 5th element: Optional key-value pairs from the Suggest server.
[email protected]d7ad4772012-06-01 03:12:54816 ListValue* types = NULL;
[email protected]d1f0a7f2012-06-05 10:26:42817 ListValue* relevances = NULL;
818 DictionaryValue* extras = NULL;
819 if (root_list->GetDictionary(4, &extras)) {
820 extras->GetList("google:suggesttype", &types);
821
822 // Only accept relevance suggestions if Instant is disabled.
[email protected]165fe422013-03-27 06:34:03823 if (!chrome::IsInstantEnabled(profile_)) {
[email protected]d1f0a7f2012-06-05 10:26:42824 // Discard this list if its size does not match that of the suggestions.
825 if (extras->GetList("google:suggestrelevance", &relevances) &&
826 relevances->GetSize() != results->GetSize())
827 relevances = NULL;
[email protected]dab8d52d2013-03-05 07:35:28828 extras->GetInteger("google:verbatimrelevance", verbatim_relevance);
[email protected]d1f0a7f2012-06-05 10:26:42829 }
[email protected]618d6e62012-12-16 05:55:57830
831 // Check if the active suggest field trial (if any) has triggered either
832 // for the default provider or keyword provider.
833 bool triggered = false;
834 extras->GetBoolean("google:fieldtrialtriggered", &triggered);
835 field_trial_triggered_ |= triggered;
836 field_trial_triggered_in_session_ |= triggered;
initial.commit09911bf2008-07-26 23:55:29837 }
838
[email protected]d7ad4772012-06-01 03:12:54839 SuggestResults* suggest_results =
840 is_keyword ? &keyword_suggest_results_ : &default_suggest_results_;
841 NavigationResults* navigation_results =
842 is_keyword ? &keyword_navigation_results_ : &default_navigation_results_;
initial.commit09911bf2008-07-26 23:55:29843
[email protected]d1f0a7f2012-06-05 10:26:42844 // Clear the previous results now that new results are available.
845 suggest_results->clear();
846 navigation_results->clear();
847
848 string16 result, title;
849 std::string type;
850 int relevance = -1;
[email protected]d7ad4772012-06-01 03:12:54851 for (size_t index = 0; results->GetString(index, &result); ++index) {
[email protected]8e81f5092010-09-29 23:19:40852 // Google search may return empty suggestions for weird input characters,
[email protected]55ce8f12012-05-09 04:44:08853 // they make no sense at all and can cause problems in our code.
[email protected]d7ad4772012-06-01 03:12:54854 if (result.empty())
[email protected]8e81f5092010-09-29 23:19:40855 continue;
856
[email protected]d1f0a7f2012-06-05 10:26:42857 // Apply valid suggested relevance scores; discard invalid lists.
858 if (relevances != NULL && !relevances->GetInteger(index, &relevance))
859 relevances = NULL;
[email protected]d7ad4772012-06-01 03:12:54860 if (types && types->GetString(index, &type) && (type == "NAVIGATION")) {
[email protected]d1f0a7f2012-06-05 10:26:42861 // Do not blindly trust the URL coming from the server to be valid.
862 GURL url(URLFixerUpper::FixupURL(UTF16ToUTF8(result), std::string()));
863 if (url.is_valid()) {
864 if (descriptions != NULL)
865 descriptions->GetString(index, &title);
[email protected]188b50c2013-03-28 07:19:42866 navigation_results->push_back(NavigationResult(
[email protected]a1b5e862013-03-29 06:38:44867 *this, url, title, is_keyword, relevance));
initial.commit09911bf2008-07-26 23:55:29868 }
869 } else {
[email protected]d1f0a7f2012-06-05 10:26:42870 // TODO(kochi): Improve calculator result presentation.
[email protected]188b50c2013-03-28 07:19:42871 suggest_results->push_back(SuggestResult(result, is_keyword, relevance));
initial.commit09911bf2008-07-26 23:55:29872 }
873 }
874
[email protected]d519d392013-03-27 09:24:46875 // In keyword mode with suggested relevance scores, demote navsuggestions
876 // below the top query match (what-you-typed or suggestion). (We
877 // don't want keyword navsuggestions to be inlined.)
878 if (is_keyword && (relevances != NULL)) {
879 // If we fail to demote navigational result relevance scores, then
880 // cancel suggested relevance scoring for keyword mode entirely.
881 if (!DemoteKeywordNavigationMatchesBelowTopQueryMatch())
882 relevances = NULL;
883 }
884
[email protected]d1f0a7f2012-06-05 10:26:42885 // Apply calculated relevance scores if a valid list was not provided.
886 if (relevances == NULL) {
[email protected]188b50c2013-03-28 07:19:42887 ApplyCalculatedSuggestRelevance(suggest_results);
888 ApplyCalculatedNavigationRelevance(navigation_results);
[email protected]dab8d52d2013-03-05 07:35:28889 } else {
890 *has_suggested_relevance = true;
[email protected]d1f0a7f2012-06-05 10:26:42891 }
892
[email protected]d7ad4772012-06-01 03:12:54893 have_suggest_results_ = true;
[email protected]d1f0a7f2012-06-05 10:26:42894 return true;
initial.commit09911bf2008-07-26 23:55:29895}
896
[email protected]344946a12012-12-20 12:03:42897void SearchProvider::ConvertResultsToAutocompleteMatches() {
initial.commit09911bf2008-07-26 23:55:29898 // Convert all the results to matches and add them to a map, so we can keep
899 // the most relevant match for each result.
900 MatchMap map;
[email protected]257ab712009-04-14 17:16:24901 const Time no_time;
902 int did_not_accept_keyword_suggestion = keyword_suggest_results_.empty() ?
initial.commit09911bf2008-07-26 23:55:29903 TemplateURLRef::NO_SUGGESTIONS_AVAILABLE :
904 TemplateURLRef::NO_SUGGESTION_CHOSEN;
initial.commit09911bf2008-07-26 23:55:29905
[email protected]382a0642012-06-06 06:13:52906 int verbatim_relevance = GetVerbatimRelevance();
[email protected]257ab712009-04-14 17:16:24907 int did_not_accept_default_suggestion = default_suggest_results_.empty() ?
[email protected]55ce8f12012-05-09 04:44:08908 TemplateURLRef::NO_SUGGESTIONS_AVAILABLE :
909 TemplateURLRef::NO_SUGGESTION_CHOSEN;
[email protected]d1f0a7f2012-06-05 10:26:42910 if (verbatim_relevance > 0) {
911 AddMatchToMap(input_.text(), input_.text(), verbatim_relevance,
912 AutocompleteMatch::SEARCH_WHAT_YOU_TYPED,
913 did_not_accept_default_suggestion, false, &map);
914 }
[email protected]5423e562013-02-07 03:58:45915 if (!keyword_input_.text().empty()) {
916 const TemplateURL* keyword_url = providers_.GetKeywordProviderURL();
917 // We only create the verbatim search query match for a keyword
918 // if it's not an extension keyword. Extension keywords are handled
919 // in KeywordProvider::Start(). (Extensions are complicated...)
920 // Note: in this provider, SEARCH_OTHER_ENGINE must correspond
921 // to the keyword verbatim search query. Do not create other matches
922 // of type SEARCH_OTHER_ENGINE.
923 if (keyword_url && !keyword_url->IsExtensionKeyword()) {
[email protected]dab8d52d2013-03-05 07:35:28924 const int keyword_verbatim_relevance = GetKeywordVerbatimRelevance();
925 if (keyword_verbatim_relevance > 0) {
926 AddMatchToMap(keyword_input_.text(), keyword_input_.text(),
927 keyword_verbatim_relevance,
928 AutocompleteMatch::SEARCH_OTHER_ENGINE,
929 did_not_accept_keyword_suggestion, true, &map);
930 }
[email protected]5423e562013-02-07 03:58:45931 }
932 }
933 const size_t verbatim_matches_size = map.size();
[email protected]93b73832012-10-18 20:18:38934 if (!default_provider_suggestion_.text.empty() &&
[email protected]2ac15ba2013-01-14 22:38:59935 default_provider_suggestion_.type == INSTANT_SUGGESTION_SEARCH &&
936 !input_.prevent_inline_autocomplete())
[email protected]93b73832012-10-18 20:18:38937 AddMatchToMap(input_.text() + default_provider_suggestion_.text,
[email protected]55ce8f12012-05-09 04:44:08938 input_.text(), verbatim_relevance + 1,
[email protected]85b8d6f2012-05-08 20:53:47939 AutocompleteMatch::SEARCH_SUGGEST,
[email protected]55ce8f12012-05-09 04:44:08940 did_not_accept_default_suggestion, false, &map);
initial.commit09911bf2008-07-26 23:55:29941
[email protected]257ab712009-04-14 17:16:24942 AddHistoryResultsToMap(keyword_history_results_, true,
943 did_not_accept_keyword_suggestion, &map);
944 AddHistoryResultsToMap(default_history_results_, false,
945 did_not_accept_default_suggestion, &map);
946
[email protected]188b50c2013-03-28 07:19:42947 AddSuggestResultsToMap(keyword_suggest_results_, &map);
948 AddSuggestResultsToMap(default_suggest_results_, &map);
initial.commit09911bf2008-07-26 23:55:29949
950 // Now add the most relevant matches from the map to |matches_|.
951 matches_.clear();
952 for (MatchMap::const_iterator i(map.begin()); i != map.end(); ++i)
953 matches_.push_back(i->second);
954
[email protected]93b73832012-10-18 20:18:38955 if (!default_provider_suggestion_.text.empty() &&
[email protected]2ac15ba2013-01-14 22:38:59956 default_provider_suggestion_.type == INSTANT_SUGGESTION_URL &&
[email protected]90fe2bb2013-01-15 03:42:13957 !input_.prevent_inline_autocomplete()) {
958 // See comment in FinalizeInstantQuery() for why we don't use
959 // |verbatim_relevance| here.
[email protected]93b73832012-10-18 20:18:38960 matches_.push_back(NavigationToMatch(
[email protected]a1b5e862013-03-29 06:38:44961 NavigationResult(*this,
962 GURL(UTF16ToUTF8(default_provider_suggestion_.text)),
[email protected]93b73832012-10-18 20:18:38963 string16(),
[email protected]188b50c2013-03-28 07:19:42964 false,
965 kNonURLVerbatimRelevance + 1)));
[email protected]90fe2bb2013-01-15 03:42:13966 }
[email protected]257ab712009-04-14 17:16:24967 AddNavigationResultsToMatches(keyword_navigation_results_, true);
968 AddNavigationResultsToMatches(default_navigation_results_, false);
initial.commit09911bf2008-07-26 23:55:29969
[email protected]5423e562013-02-07 03:58:45970 // Allow additional match(es) for verbatim results if present.
971 const size_t max_total_matches = kMaxMatches + verbatim_matches_size;
initial.commit09911bf2008-07-26 23:55:29972 std::partial_sort(matches_.begin(),
973 matches_.begin() + std::min(max_total_matches, matches_.size()),
974 matches_.end(), &AutocompleteMatch::MoreRelevant);
[email protected]3723e6e2012-06-11 21:06:56975
initial.commit09911bf2008-07-26 23:55:29976 if (matches_.size() > max_total_matches)
[email protected]344946a12012-12-20 12:03:42977 matches_.resize(max_total_matches);
978}
979
980bool SearchProvider::IsTopMatchScoreTooLow() const {
[email protected]dab8d52d2013-03-05 07:35:28981 // Here we use CalculateRelevanceForVerbatimIgnoringKeywordModeState()
982 // rather than CalculateRelevanceForVerbatim() because the latter returns
983 // a very low score (250) if keyword mode is active. This is because
984 // when keyword mode is active the user probably wants the keyword matches,
985 // not matches from the default provider. Hence, we use the version of
986 // the function that ignores whether keyword mode is active. This allows
987 // SearchProvider to maintain its contract with the AutocompleteController
988 // that it will always provide an inlineable match with a reasonable
989 // score.
990 return matches_.front().relevance <
991 CalculateRelevanceForVerbatimIgnoringKeywordModeState();
[email protected]344946a12012-12-20 12:03:42992}
993
994bool SearchProvider::IsTopMatchHighRankSearchForURL() const {
995 return input_.type() == AutocompleteInput::URL &&
996 matches_.front().relevance > CalculateRelevanceForVerbatim() &&
997 (matches_.front().type == AutocompleteMatch::SEARCH_SUGGEST ||
[email protected]5423e562013-02-07 03:58:45998 matches_.front().type == AutocompleteMatch::SEARCH_WHAT_YOU_TYPED ||
999 matches_.front().type == AutocompleteMatch::SEARCH_OTHER_ENGINE);
[email protected]344946a12012-12-20 12:03:421000}
1001
1002bool SearchProvider::IsTopMatchNotInlinable() const {
[email protected]5423e562013-02-07 03:58:451003 // Note: this test assumes the SEARCH_OTHER_ENGINE match corresponds to
1004 // the verbatim search query on the keyword engine. SearchProvider should
1005 // not create any other match of type SEARCH_OTHER_ENGINE.
[email protected]344946a12012-12-20 12:03:421006 return matches_.front().type != AutocompleteMatch::SEARCH_WHAT_YOU_TYPED &&
1007 matches_.front().type != AutocompleteMatch::URL_WHAT_YOU_TYPED &&
[email protected]5423e562013-02-07 03:58:451008 matches_.front().type != AutocompleteMatch::SEARCH_OTHER_ENGINE &&
[email protected]344946a12012-12-20 12:03:421009 matches_.front().inline_autocomplete_offset == string16::npos &&
1010 matches_.front().fill_into_edit != input_.text();
1011}
1012
1013void SearchProvider::UpdateMatches() {
1014 ConvertResultsToAutocompleteMatches();
initial.commit09911bf2008-07-26 23:55:291015
[email protected]382a0642012-06-06 06:13:521016 // Check constraints that may be violated by suggested relevances.
[email protected]344946a12012-12-20 12:03:421017 if (!matches_.empty() &&
[email protected]dab8d52d2013-03-05 07:35:281018 (has_default_suggested_relevance_ || default_verbatim_relevance_ >= 0 ||
1019 has_keyword_suggested_relevance_ || keyword_verbatim_relevance_ >= 0)) {
1020 // These two blocks attempt to repair undesirable behavior by suggested
[email protected]344946a12012-12-20 12:03:421021 // relevances with minimal impact, preserving other suggested relevances.
1022 if (IsTopMatchScoreTooLow()) {
[email protected]1beee342012-06-19 22:22:281023 // Disregard the suggested verbatim relevance if the top score is below
1024 // the usual verbatim value. For example, a BarProvider may rely on
1025 // SearchProvider's verbatim or inlineable matches for input "foo" to
1026 // always outrank its own lowly-ranked non-inlineable "bar" match.
[email protected]dab8d52d2013-03-05 07:35:281027 default_verbatim_relevance_ = -1;
1028 keyword_verbatim_relevance_ = -1;
[email protected]344946a12012-12-20 12:03:421029 ConvertResultsToAutocompleteMatches();
[email protected]e6acd002012-06-16 22:27:471030 }
[email protected]344946a12012-12-20 12:03:421031 if (IsTopMatchHighRankSearchForURL()) {
[email protected]e6acd002012-06-16 22:27:471032 // Disregard the suggested search and verbatim relevances if the input
1033 // type is URL and the top match is a highly-ranked search suggestion.
1034 // For example, prevent a search for "foo.com" from outranking another
1035 // provider's navigation for "foo.com" or "foo.com/url_from_history".
[email protected]188b50c2013-03-28 07:19:421036 ApplyCalculatedSuggestRelevance(&keyword_suggest_results_);
1037 ApplyCalculatedSuggestRelevance(&default_suggest_results_);
[email protected]dab8d52d2013-03-05 07:35:281038 default_verbatim_relevance_ = -1;
1039 keyword_verbatim_relevance_ = -1;
[email protected]344946a12012-12-20 12:03:421040 ConvertResultsToAutocompleteMatches();
[email protected]382a0642012-06-06 06:13:521041 }
[email protected]344946a12012-12-20 12:03:421042 if (IsTopMatchNotInlinable()) {
[email protected]5423e562013-02-07 03:58:451043 // Disregard suggested relevances if the top match is not a verbatim
1044 // match, inlinable, or URL_WHAT_YOU_TYPED (which may be top match
1045 // regardless of inlining). For example, input "foo" should not
1046 // invoke a search for "bar", which would happen if the "bar" search
1047 // match outranked all other matches.
[email protected]344946a12012-12-20 12:03:421048 ApplyCalculatedRelevance();
1049 ConvertResultsToAutocompleteMatches();
[email protected]382a0642012-06-06 06:13:521050 }
[email protected]344946a12012-12-20 12:03:421051 DCHECK(!IsTopMatchScoreTooLow());
1052 DCHECK(!IsTopMatchHighRankSearchForURL());
1053 DCHECK(!IsTopMatchNotInlinable());
[email protected]d1f0a7f2012-06-05 10:26:421054 }
1055
[email protected]cc63dea2008-08-21 20:56:311056 UpdateStarredStateOfMatches();
[email protected]4ab4c7c2010-11-24 04:49:341057 UpdateDone();
[email protected]257ab712009-04-14 17:16:241058}
1059
1060void SearchProvider::AddNavigationResultsToMatches(
1061 const NavigationResults& navigation_results,
1062 bool is_keyword) {
[email protected]c112f0fe72013-01-18 20:30:091063 if (navigation_results.empty())
1064 return;
1065
[email protected]dab8d52d2013-03-05 07:35:281066 if (is_keyword ?
1067 has_keyword_suggested_relevance_ : has_default_suggested_relevance_) {
[email protected]c112f0fe72013-01-18 20:30:091068 for (NavigationResults::const_iterator it = navigation_results.begin();
1069 it != navigation_results.end(); ++it)
[email protected]188b50c2013-03-28 07:19:421070 matches_.push_back(NavigationToMatch(*it));
[email protected]c112f0fe72013-01-18 20:30:091071 } else {
1072 // Pick one element only in absence of the suggested relevance scores.
[email protected]6c535842012-05-15 05:20:551073 // TODO(kochi|msw): Add more navigational results if they get more
1074 // meaningful relevance values; see http://b/1170574.
[email protected]d7ad4772012-06-01 03:12:541075 // CompareScoredResults sorts by descending relevance; so use min_element.
[email protected]6c535842012-05-15 05:20:551076 NavigationResults::const_iterator result(
[email protected]d7ad4772012-06-01 03:12:541077 std::min_element(navigation_results.begin(),
[email protected]6c535842012-05-15 05:20:551078 navigation_results.end(),
1079 CompareScoredResults()));
[email protected]188b50c2013-03-28 07:19:421080 matches_.push_back(NavigationToMatch(*result));
[email protected]257ab712009-04-14 17:16:241081 }
1082}
1083
1084void SearchProvider::AddHistoryResultsToMap(const HistoryResults& results,
1085 bool is_keyword,
1086 int did_not_accept_suggestion,
1087 MatchMap* map) {
[email protected]51124552011-07-16 01:37:101088 if (results.empty())
1089 return;
1090
[email protected]d7ad4772012-06-01 03:12:541091 bool prevent_inline_autocomplete = input_.prevent_inline_autocomplete() ||
1092 (input_.type() == AutocompleteInput::URL);
[email protected]14710852013-02-05 23:45:411093 const string16& input_text =
1094 is_keyword ? keyword_input_.text() : input_.text();
[email protected]51124552011-07-16 01:37:101095 bool input_multiple_words = HasMultipleWords(input_text);
1096
[email protected]55ce8f12012-05-09 04:44:081097 SuggestResults scored_results;
1098 if (!prevent_inline_autocomplete && input_multiple_words) {
1099 // ScoreHistoryResults() allows autocompletion of multi-word, 1-visit
1100 // queries if the input also has multiple words. But if we were already
[email protected]51124552011-07-16 01:37:101101 // autocompleting a multi-word, multi-visit query, and the current input is
1102 // still a prefix of it, then changing the autocompletion suddenly feels
1103 // wrong. To detect this case, first score as if only one word has been
1104 // typed, then check for a best result that is an autocompleted, multi-word
1105 // query. If we find one, then just keep that score set.
[email protected]55ce8f12012-05-09 04:44:081106 scored_results = ScoreHistoryResults(results, prevent_inline_autocomplete,
1107 false, input_text, is_keyword);
1108 if ((scored_results[0].relevance() <
1109 AutocompleteResult::kLowestDefaultScore) ||
1110 !HasMultipleWords(scored_results[0].suggestion()))
1111 scored_results.clear(); // Didn't detect the case above, score normally.
[email protected]51124552011-07-16 01:37:101112 }
[email protected]55ce8f12012-05-09 04:44:081113 if (scored_results.empty())
1114 scored_results = ScoreHistoryResults(results, prevent_inline_autocomplete,
1115 input_multiple_words, input_text,
1116 is_keyword);
1117 for (SuggestResults::const_iterator i(scored_results.begin());
1118 i != scored_results.end(); ++i) {
1119 AddMatchToMap(i->suggestion(), input_text, i->relevance(),
[email protected]51124552011-07-16 01:37:101120 AutocompleteMatch::SEARCH_HISTORY, did_not_accept_suggestion,
[email protected]55ce8f12012-05-09 04:44:081121 is_keyword, map);
[email protected]51124552011-07-16 01:37:101122 }
1123}
1124
[email protected]55ce8f12012-05-09 04:44:081125SearchProvider::SuggestResults SearchProvider::ScoreHistoryResults(
[email protected]51124552011-07-16 01:37:101126 const HistoryResults& results,
1127 bool base_prevent_inline_autocomplete,
1128 bool input_multiple_words,
1129 const string16& input_text,
1130 bool is_keyword) {
[email protected]810ffba2012-06-12 01:07:481131 AutocompleteClassifier* classifier =
1132 AutocompleteClassifierFactory::GetForProfile(profile_);
[email protected]55ce8f12012-05-09 04:44:081133 SuggestResults scored_results;
[email protected]257ab712009-04-14 17:16:241134 for (HistoryResults::const_iterator i(results.begin()); i != results.end();
1135 ++i) {
[email protected]51124552011-07-16 01:37:101136 // Don't autocomplete multi-word queries that have only been seen once
1137 // unless the user has typed more than one word.
1138 bool prevent_inline_autocomplete = base_prevent_inline_autocomplete ||
1139 (!input_multiple_words && (i->visits < 2) && HasMultipleWords(i->term));
1140
[email protected]ea3b9a502011-04-04 14:19:371141 // Don't autocomplete search terms that would normally be treated as URLs
[email protected]51124552011-07-16 01:37:101142 // when typed. For example, if the user searched for "google.com" and types
1143 // "goog", don't autocomplete to the search term "google.com". Otherwise,
1144 // the input will look like a URL but act like a search, which is confusing.
[email protected]cc447362011-04-06 03:57:481145 // NOTE: We don't check this in the following cases:
1146 // * When inline autocomplete is disabled, we won't be inline
1147 // autocompleting this term, so we don't need to worry about confusion as
1148 // much. This also prevents calling Classify() again from inside the
1149 // classifier (which will corrupt state and likely crash), since the
[email protected]51124552011-07-16 01:37:101150 // classifier always disables inline autocomplete.
[email protected]cc447362011-04-06 03:57:481151 // * When the user has typed the whole term, the "what you typed" history
1152 // match will outrank us for URL-like inputs anyway, so we need not do
1153 // anything special.
[email protected]51124552011-07-16 01:37:101154 if (!prevent_inline_autocomplete && classifier && (i->term != input_text)) {
[email protected]ea3b9a502011-04-04 14:19:371155 AutocompleteMatch match;
[email protected]f608ea102013-03-18 15:08:091156 classifier->Classify(i->term, false, false, &match, NULL);
[email protected]2905f742011-10-13 03:51:581157 prevent_inline_autocomplete =
[email protected]749e7ae02012-09-05 18:47:461158 !AutocompleteMatch::IsSearchType(match.type);
[email protected]ea3b9a502011-04-04 14:19:371159 }
[email protected]51124552011-07-16 01:37:101160
1161 int relevance = CalculateRelevanceForHistory(i->time, is_keyword,
1162 prevent_inline_autocomplete);
[email protected]188b50c2013-03-28 07:19:421163 scored_results.push_back(SuggestResult(i->term, is_keyword, relevance));
[email protected]257ab712009-04-14 17:16:241164 }
[email protected]51124552011-07-16 01:37:101165
1166 // History returns results sorted for us. However, we may have docked some
1167 // results' scores, so things are no longer in order. Do a stable sort to get
1168 // things back in order without otherwise disturbing results with equal
1169 // scores, then force the scores to be unique, so that the order in which
1170 // they're shown is deterministic.
[email protected]55ce8f12012-05-09 04:44:081171 std::stable_sort(scored_results.begin(), scored_results.end(),
1172 CompareScoredResults());
[email protected]51124552011-07-16 01:37:101173 int last_relevance = 0;
[email protected]55ce8f12012-05-09 04:44:081174 for (SuggestResults::iterator i(scored_results.begin());
1175 i != scored_results.end(); ++i) {
1176 if ((i != scored_results.begin()) && (i->relevance() >= last_relevance))
1177 i->set_relevance(last_relevance - 1);
1178 last_relevance = i->relevance();
[email protected]51124552011-07-16 01:37:101179 }
1180
[email protected]55ce8f12012-05-09 04:44:081181 return scored_results;
[email protected]257ab712009-04-14 17:16:241182}
1183
[email protected]55ce8f12012-05-09 04:44:081184void SearchProvider::AddSuggestResultsToMap(const SuggestResults& results,
[email protected]55ce8f12012-05-09 04:44:081185 MatchMap* map) {
[email protected]55ce8f12012-05-09 04:44:081186 for (size_t i = 0; i < results.size(); ++i) {
[email protected]188b50c2013-03-28 07:19:421187 const bool is_keyword = results[i].from_keyword_provider();
1188 const string16& input = is_keyword ? keyword_input_.text() : input_.text();
1189 AddMatchToMap(results[i].suggestion(), input, results[i].relevance(),
[email protected]55ce8f12012-05-09 04:44:081190 AutocompleteMatch::SEARCH_SUGGEST, i, is_keyword, map);
[email protected]257ab712009-04-14 17:16:241191 }
initial.commit09911bf2008-07-26 23:55:291192}
1193
[email protected]382a0642012-06-06 06:13:521194int SearchProvider::GetVerbatimRelevance() const {
[email protected]dc6943b2012-06-19 06:39:561195 // Use the suggested verbatim relevance score if it is non-negative (valid),
1196 // if inline autocomplete isn't prevented (always show verbatim on backspace),
[email protected]1beee342012-06-19 22:22:281197 // and if it won't suppress verbatim, leaving no default provider matches.
1198 // Otherwise, if the default provider returned no matches and was still able
[email protected]dc6943b2012-06-19 06:39:561199 // to suppress verbatim, the user would have no search/nav matches and may be
[email protected]1beee342012-06-19 22:22:281200 // left unable to search using their default provider from the omnibox.
[email protected]dc6943b2012-06-19 06:39:561201 // Check for results on each verbatim calculation, as results from older
1202 // queries (on previous input) may be trimmed for failing to inline new input.
[email protected]dab8d52d2013-03-05 07:35:281203 if (default_verbatim_relevance_ >= 0 &&
1204 !input_.prevent_inline_autocomplete() &&
1205 (default_verbatim_relevance_ > 0 ||
[email protected]1beee342012-06-19 22:22:281206 !default_suggest_results_.empty() ||
[email protected]dc6943b2012-06-19 06:39:561207 !default_navigation_results_.empty())) {
[email protected]dab8d52d2013-03-05 07:35:281208 return default_verbatim_relevance_;
[email protected]dc6943b2012-06-19 06:39:561209 }
[email protected]382a0642012-06-06 06:13:521210 return CalculateRelevanceForVerbatim();
1211}
[email protected]d1f0a7f2012-06-05 10:26:421212
[email protected]382a0642012-06-06 06:13:521213int SearchProvider::CalculateRelevanceForVerbatim() const {
[email protected]85b8d6f2012-05-08 20:53:471214 if (!providers_.keyword_provider().empty())
[email protected]52d08b12009-10-19 18:42:361215 return 250;
[email protected]dab8d52d2013-03-05 07:35:281216 return CalculateRelevanceForVerbatimIgnoringKeywordModeState();
1217}
[email protected]52d08b12009-10-19 18:42:361218
[email protected]dab8d52d2013-03-05 07:35:281219int SearchProvider::
1220 CalculateRelevanceForVerbatimIgnoringKeywordModeState() const {
initial.commit09911bf2008-07-26 23:55:291221 switch (input_.type()) {
1222 case AutocompleteInput::UNKNOWN:
[email protected]52d08b12009-10-19 18:42:361223 case AutocompleteInput::QUERY:
1224 case AutocompleteInput::FORCED_QUERY:
[email protected]90fe2bb2013-01-15 03:42:131225 return kNonURLVerbatimRelevance;
initial.commit09911bf2008-07-26 23:55:291226
initial.commit09911bf2008-07-26 23:55:291227 case AutocompleteInput::URL:
[email protected]52d08b12009-10-19 18:42:361228 return 850;
initial.commit09911bf2008-07-26 23:55:291229
1230 default:
1231 NOTREACHED();
1232 return 0;
1233 }
1234}
1235
[email protected]dab8d52d2013-03-05 07:35:281236int SearchProvider::GetKeywordVerbatimRelevance() const {
1237 // Use the suggested verbatim relevance score if it is non-negative (valid),
1238 // if inline autocomplete isn't prevented (always show verbatim on backspace),
1239 // and if it won't suppress verbatim, leaving no keyword provider matches.
1240 // Otherwise, if the keyword provider returned no matches and was still able
1241 // to suppress verbatim, the user would have no search/nav matches and may be
1242 // left unable to search using their keyword provider from the omnibox.
1243 // Check for results on each verbatim calculation, as results from older
1244 // queries (on previous input) may be trimmed for failing to inline new input.
1245 if (keyword_verbatim_relevance_ >= 0 &&
1246 !input_.prevent_inline_autocomplete() &&
1247 (keyword_verbatim_relevance_ > 0 ||
1248 !keyword_suggest_results_.empty() ||
1249 !keyword_navigation_results_.empty())) {
1250 return keyword_verbatim_relevance_;
1251 }
1252 return CalculateRelevanceForKeywordVerbatim(
1253 keyword_input_.type(), keyword_input_.prefer_keyword());
1254}
1255
[email protected]5423e562013-02-07 03:58:451256// static
1257int SearchProvider::CalculateRelevanceForKeywordVerbatim(
1258 AutocompleteInput::Type type,
1259 bool prefer_keyword) {
1260 // This function is responsible for scoring verbatim query matches
1261 // for non-extension keywords. KeywordProvider::CalculateRelevance()
1262 // scores verbatim query matches for extension keywords, as well as
1263 // for keyword matches (i.e., suggestions of a keyword itself, not a
1264 // suggestion of a query on a keyword search engine). These two
1265 // functions are currently in sync, but there's no reason we
1266 // couldn't decide in the future to score verbatim matches
1267 // differently for extension and non-extension keywords. If you
1268 // make such a change, however, you should update this comment to
1269 // describe it, so it's clear why the functions diverge.
1270 if (prefer_keyword)
1271 return 1500;
1272 return (type == AutocompleteInput::QUERY) ? 1450 : 1100;
1273}
1274
[email protected]51124552011-07-16 01:37:101275int SearchProvider::CalculateRelevanceForHistory(
1276 const Time& time,
1277 bool is_keyword,
1278 bool prevent_inline_autocomplete) const {
[email protected]aa613d62010-11-09 20:40:181279 // The relevance of past searches falls off over time. There are two distinct
1280 // equations used. If the first equation is used (searches to the primary
[email protected]51124552011-07-16 01:37:101281 // provider that we want to inline autocomplete), the score starts at 1399 and
1282 // falls to 1300. If the second equation is used the relevance of a search 15
1283 // minutes ago is discounted 50 points, while the relevance of a search two
1284 // weeks ago is discounted 450 points.
[email protected]aa613d62010-11-09 20:40:181285 double elapsed_time = std::max((Time::Now() - time).InSecondsF(), 0.);
[email protected]188b50c2013-03-28 07:19:421286 bool is_primary_provider = is_keyword || !providers_.has_keyword_provider();
[email protected]51124552011-07-16 01:37:101287 if (is_primary_provider && !prevent_inline_autocomplete) {
[email protected]aa613d62010-11-09 20:40:181288 // Searches with the past two days get a different curve.
[email protected]51124552011-07-16 01:37:101289 const double autocomplete_time = 2 * 24 * 60 * 60;
[email protected]aa613d62010-11-09 20:40:181290 if (elapsed_time < autocomplete_time) {
[email protected]e17511f2011-07-13 14:09:181291 return (is_keyword ? 1599 : 1399) - static_cast<int>(99 *
[email protected]aa613d62010-11-09 20:40:181292 std::pow(elapsed_time / autocomplete_time, 2.5));
1293 }
1294 elapsed_time -= autocomplete_time;
1295 }
1296
[email protected]c3a4bd992010-08-18 20:25:011297 const int score_discount =
1298 static_cast<int>(6.5 * std::pow(elapsed_time, 0.3));
initial.commit09911bf2008-07-26 23:55:291299
[email protected]6c85aa02009-02-27 12:08:091300 // Don't let scores go below 0. Negative relevance scores are meaningful in
1301 // a different way.
initial.commit09911bf2008-07-26 23:55:291302 int base_score;
[email protected]51124552011-07-16 01:37:101303 if (is_primary_provider)
[email protected]52d08b12009-10-19 18:42:361304 base_score = (input_.type() == AutocompleteInput::URL) ? 750 : 1050;
[email protected]51124552011-07-16 01:37:101305 else
1306 base_score = 200;
initial.commit09911bf2008-07-26 23:55:291307 return std::max(0, base_score - score_discount);
1308}
1309
[email protected]a2fedb1e2011-01-25 15:23:361310void SearchProvider::AddMatchToMap(const string16& query_string,
1311 const string16& input_text,
initial.commit09911bf2008-07-26 23:55:291312 int relevance,
[email protected]4c1fb7ec2008-11-13 00:19:001313 AutocompleteMatch::Type type,
initial.commit09911bf2008-07-26 23:55:291314 int accepted_suggestion,
[email protected]257ab712009-04-14 17:16:241315 bool is_keyword,
initial.commit09911bf2008-07-26 23:55:291316 MatchMap* map) {
[email protected]92513682011-09-01 06:16:521317 AutocompleteMatch match(this, relevance, false, type);
initial.commit09911bf2008-07-26 23:55:291318 std::vector<size_t> content_param_offsets;
[email protected]85b8d6f2012-05-08 20:53:471319 // Bail out now if we don't actually have a valid provider.
1320 match.keyword = is_keyword ?
[email protected]3954c3a2012-04-10 20:17:551321 providers_.keyword_provider() : providers_.default_provider();
[email protected]dbff446582012-10-30 00:20:261322 const TemplateURL* provider_url = match.GetTemplateURL(profile_, false);
[email protected]85b8d6f2012-05-08 20:53:471323 if (provider_url == NULL)
1324 return;
1325
[email protected]70833262011-01-05 23:40:441326 match.contents.assign(query_string);
[email protected]fb5153c52009-07-31 19:40:331327 // We do intra-string highlighting for suggestions - the suggested segment
1328 // will be highlighted, e.g. for input_text = "you" the suggestion may be
1329 // "youtube", so we'll bold the "tube" section: you*tube*.
1330 if (input_text != query_string) {
[email protected]fb5153c52009-07-31 19:40:331331 size_t input_position = match.contents.find(input_text);
[email protected]a2fedb1e2011-01-25 15:23:361332 if (input_position == string16::npos) {
[email protected]fb5153c52009-07-31 19:40:331333 // The input text is not a substring of the query string, e.g. input
1334 // text is "slasdot" and the query string is "slashdot", so we bold the
1335 // whole thing.
1336 match.contents_class.push_back(
1337 ACMatchClassification(0, ACMatchClassification::MATCH));
[email protected]ec2379162009-06-09 23:58:171338 } else {
[email protected]fb5153c52009-07-31 19:40:331339 // TODO(beng): ACMatchClassification::MATCH now seems to just mean
1340 // "bold" this. Consider modifying the terminology.
1341 // We don't iterate over the string here annotating all matches because
1342 // it looks odd to have every occurrence of a substring that may be as
1343 // short as a single character highlighted in a query suggestion result,
1344 // e.g. for input text "s" and query string "southwest airlines", it
1345 // looks odd if both the first and last s are highlighted.
1346 if (input_position != 0) {
1347 match.contents_class.push_back(
1348 ACMatchClassification(0, ACMatchClassification::NONE));
1349 }
1350 match.contents_class.push_back(
1351 ACMatchClassification(input_position, ACMatchClassification::DIM));
1352 size_t next_fragment_position = input_position + input_text.length();
1353 if (next_fragment_position < query_string.length()) {
1354 match.contents_class.push_back(
1355 ACMatchClassification(next_fragment_position,
1356 ACMatchClassification::NONE));
1357 }
[email protected]ec2379162009-06-09 23:58:171358 }
initial.commit09911bf2008-07-26 23:55:291359 } else {
[email protected]fb5153c52009-07-31 19:40:331360 // Otherwise, we're dealing with the "default search" result which has no
[email protected]70833262011-01-05 23:40:441361 // completion.
[email protected]fb5153c52009-07-31 19:40:331362 match.contents_class.push_back(
1363 ACMatchClassification(0, ACMatchClassification::NONE));
initial.commit09911bf2008-07-26 23:55:291364 }
1365
1366 // When the user forced a query, we need to make sure all the fill_into_edit
1367 // values preserve that property. Otherwise, if the user starts editing a
1368 // suggestion, non-Search results will suddenly appear.
[email protected]8f2249b2012-08-29 02:27:241369 if (input_.type() == AutocompleteInput::FORCED_QUERY)
[email protected]a2fedb1e2011-01-25 15:23:361370 match.fill_into_edit.assign(ASCIIToUTF16("?"));
[email protected]8f2249b2012-08-29 02:27:241371 if (is_keyword)
[email protected]033f3422012-03-13 21:24:181372 match.fill_into_edit.append(match.keyword + char16(' '));
[email protected]8f2249b2012-08-29 02:27:241373 if (!input_.prevent_inline_autocomplete() &&
1374 StartsWith(query_string, input_text, false)) {
1375 match.inline_autocomplete_offset =
1376 match.fill_into_edit.length() + input_text.length();
[email protected]c0048b42009-05-04 21:47:171377 }
initial.commit09911bf2008-07-26 23:55:291378 match.fill_into_edit.append(query_string);
initial.commit09911bf2008-07-26 23:55:291379
[email protected]85b8d6f2012-05-08 20:53:471380 const TemplateURLRef& search_url = provider_url->url_ref();
[email protected]360ba052012-04-04 17:26:131381 DCHECK(search_url.SupportsReplacement());
[email protected]bca359b2012-06-24 07:53:041382 match.search_terms_args.reset(
1383 new TemplateURLRef::SearchTermsArgs(query_string));
1384 match.search_terms_args->original_query = input_text;
1385 match.search_terms_args->accepted_suggestion = accepted_suggestion;
1386 // This is the destination URL sans assisted query stats. This must be set
1387 // so the AutocompleteController can properly de-dupe; the controller will
1388 // eventually overwrite it before it reaches the user.
1389 match.destination_url =
1390 GURL(search_url.ReplaceSearchTerms(*match.search_terms_args.get()));
initial.commit09911bf2008-07-26 23:55:291391
1392 // Search results don't look like URLs.
[email protected]2905f742011-10-13 03:51:581393 match.transition = is_keyword ?
1394 content::PAGE_TRANSITION_KEYWORD : content::PAGE_TRANSITION_GENERATED;
initial.commit09911bf2008-07-26 23:55:291395
1396 // Try to add |match| to |map|. If a match for |query_string| is already in
1397 // |map|, replace it if |match| is more relevant.
1398 // NOTE: Keep this ToLower() call in sync with url_database.cc.
1399 const std::pair<MatchMap::iterator, bool> i = map->insert(
[email protected]a2fedb1e2011-01-25 15:23:361400 std::pair<string16, AutocompleteMatch>(
[email protected]503d03872011-05-06 08:36:261401 base::i18n::ToLower(query_string), match));
initial.commit09911bf2008-07-26 23:55:291402 // NOTE: We purposefully do a direct relevance comparison here instead of
1403 // using AutocompleteMatch::MoreRelevant(), so that we'll prefer "items added
1404 // first" rather than "items alphabetically first" when the scores are equal.
1405 // The only case this matters is when a user has results with the same score
1406 // that differ only by capitalization; because the history system returns
1407 // results sorted by recency, this means we'll pick the most recent such
1408 // result even if the precision of our relevance score is too low to
1409 // distinguish the two.
1410 if (!i.second && (match.relevance > i.first->second.relevance))
1411 i.first->second = match;
1412}
1413
1414AutocompleteMatch SearchProvider::NavigationToMatch(
[email protected]188b50c2013-03-28 07:19:421415 const NavigationResult& navigation) {
1416 const string16& input = navigation.from_keyword_provider() ?
1417 keyword_input_.text() : input_.text();
[email protected]55ce8f12012-05-09 04:44:081418 AutocompleteMatch match(this, navigation.relevance(), false,
[email protected]4c1fb7ec2008-11-13 00:19:001419 AutocompleteMatch::NAVSUGGEST);
[email protected]55ce8f12012-05-09 04:44:081420 match.destination_url = navigation.url();
[email protected]371dab12012-06-01 03:23:551421
1422 // First look for the user's input inside the fill_into_edit as it would be
1423 // without trimming the scheme, so we can find matches at the beginning of the
1424 // scheme.
[email protected]a1b5e862013-03-29 06:38:441425 const string16& untrimmed_fill_into_edit = navigation.formatted_url();
[email protected]371dab12012-06-01 03:23:551426 const URLPrefix* prefix =
1427 URLPrefix::BestURLPrefix(untrimmed_fill_into_edit, input);
1428 size_t match_start = (prefix == NULL) ?
1429 untrimmed_fill_into_edit.find(input) : prefix->prefix.length();
1430 size_t inline_autocomplete_offset = (prefix == NULL) ?
1431 string16::npos : (match_start + input.length());
1432 bool trim_http = !HasHTTPScheme(input) && (!prefix || (match_start != 0));
1433
1434 // Preserve the forced query '?' prefix in |match.fill_into_edit|.
1435 // Otherwise, user edits to a suggestion would show non-Search results.
1436 if (input_.type() == AutocompleteInput::FORCED_QUERY) {
1437 match.fill_into_edit = ASCIIToUTF16("?");
1438 if (inline_autocomplete_offset != string16::npos)
1439 ++inline_autocomplete_offset;
1440 }
1441
1442 const std::string languages(
1443 profile_->GetPrefs()->GetString(prefs::kAcceptLanguages));
1444 const net::FormatUrlTypes format_types =
1445 net::kFormatUrlOmitAll & ~(trim_http ? 0 : net::kFormatUrlOmitHTTP);
1446 match.fill_into_edit +=
1447 AutocompleteInput::FormattedStringWithEquivalentMeaning(navigation.url(),
1448 net::FormatUrl(navigation.url(), languages, format_types,
1449 net::UnescapeRule::SPACES, NULL, NULL,
1450 &inline_autocomplete_offset));
1451 if (!input_.prevent_inline_autocomplete())
1452 match.inline_autocomplete_offset = inline_autocomplete_offset;
1453 DCHECK((match.inline_autocomplete_offset == string16::npos) ||
1454 (match.inline_autocomplete_offset <= match.fill_into_edit.length()));
1455
1456 match.contents = net::FormatUrl(navigation.url(), languages,
1457 format_types, net::UnescapeRule::SPACES, NULL, NULL, &match_start);
1458 // If the first match in the untrimmed string was inside a scheme that we
1459 // trimmed, look for a subsequent match.
1460 if (match_start == string16::npos)
1461 match_start = match.contents.find(input);
1462 // Safe if |match_start| is npos; also safe if the input is longer than the
1463 // remaining contents after |match_start|.
1464 AutocompleteMatch::ClassifyLocationInString(match_start, input.length(),
1465 match.contents.length(), ACMatchClassification::URL,
1466 &match.contents_class);
initial.commit09911bf2008-07-26 23:55:291467
[email protected]55ce8f12012-05-09 04:44:081468 match.description = navigation.description();
[email protected]371dab12012-06-01 03:23:551469 AutocompleteMatch::ClassifyMatchInString(input, match.description,
1470 ACMatchClassification::NONE, &match.description_class);
initial.commit09911bf2008-07-26 23:55:291471 return match;
1472}
[email protected]4ab4c7c2010-11-24 04:49:341473
[email protected]d519d392013-03-27 09:24:461474bool SearchProvider::DemoteKeywordNavigationMatchesBelowTopQueryMatch() {
1475 // First, determine the maximum score of any keyword query match (verbatim or
1476 // query suggestion).
1477 int max_query_relevance = GetKeywordVerbatimRelevance();
1478 if (!keyword_suggest_results_.empty()) {
1479 // CompareScoredResults sorts by descending relevance; so use min_element
1480 // to get the highest relevance.
1481 SuggestResults::const_iterator max_suggest_it = std::min_element(
1482 keyword_suggest_results_.begin(),
1483 keyword_suggest_results_.end(),
1484 CompareScoredResults());
1485 max_query_relevance =
1486 std::max(max_suggest_it->relevance(), max_query_relevance);
1487 }
1488 // If no query is supposed to appear, then navigational matches cannot
1489 // be demoted past it. Bail.
1490 if (max_query_relevance == 0)
1491 return false;
1492 // Now we know we can enforce the minimum score constraint even after
1493 // the navigation matches are demoted. Proceed to demote the navigation
1494 // matches to enforce the query-must-come-first constraint.
1495 // Sort the keyword navigation results by decreasing relevance scores.
1496 std::stable_sort(keyword_navigation_results_.begin(),
1497 keyword_navigation_results_.end(),
1498 CompareScoredResults());
1499 // Cap the relevance score of all results.
1500 for (NavigationResults::iterator it = keyword_navigation_results_.begin();
1501 it != keyword_navigation_results_.end(); ++it) {
1502 if (it->relevance() >= max_query_relevance) {
1503 if (max_query_relevance > 0)
1504 --max_query_relevance;
1505 it->set_relevance(max_query_relevance);
1506 } else {
1507 // No later results will need to be capped.
1508 break;
1509 }
1510 }
1511 return true;
1512}
1513
[email protected]4ab4c7c2010-11-24 04:49:341514void SearchProvider::UpdateDone() {
[email protected]2cdf1172012-08-26 12:21:331515 // We're done when the timer isn't running, there are no suggest queries
[email protected]5fac3782013-03-06 09:32:311516 // pending, and we're not waiting on Instant.
[email protected]2cdf1172012-08-26 12:21:331517 done_ = (!timer_.IsRunning() && (suggest_results_pending_ == 0) &&
[email protected]165fe422013-03-27 06:34:031518 (instant_finalized_ || !chrome::IsInstantEnabled(profile_)));
[email protected]4ab4c7c2010-11-24 04:49:341519}