blob: 849d494f963edb9eef5bc7f231d3731dde5f530e [file] [log] [blame]
[email protected]e41982a72012-11-20 07:16:511// Copyright 2012 The Chromium Authors. All rights reserved.
license.botbf09a502008-08-24 00:55:552// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
initial.commit09911bf2008-07-26 23:55:294
5#include "chrome/browser/autocomplete/search_provider.h"
6
[email protected]1cb2dac2010-03-08 21:49:157#include <algorithm>
[email protected]c3a4bd992010-08-18 20:25:018#include <cmath>
[email protected]1cb2dac2010-03-08 21:49:159
[email protected]2041cf342010-02-19 03:15:5910#include "base/callback.h"
[email protected]51124552011-07-16 01:37:1011#include "base/i18n/break_iterator.h"
[email protected]503d03872011-05-06 08:36:2612#include "base/i18n/case_conversion.h"
[email protected]d6e58c6e2009-10-10 20:40:5013#include "base/i18n/icu_string_conversions.h"
[email protected]ffbec692012-02-26 20:26:4214#include "base/json/json_string_value_serializer.h"
initial.commit09911bf2008-07-26 23:55:2915#include "base/message_loop.h"
[email protected]f5b95ba92012-03-27 14:05:1916#include "base/metrics/histogram.h"
[email protected]3853a4c2013-02-11 17:15:5717#include "base/prefs/pref_service.h"
[email protected]98570e12013-06-10 19:54:2218#include "base/strings/string16.h"
19#include "base/strings/string_util.h"
[email protected]135cb802013-06-09 16:44:2020#include "base/strings/utf_string_conversions.h"
[email protected]ea3b9a502011-04-04 14:19:3721#include "chrome/browser/autocomplete/autocomplete_classifier.h"
[email protected]810ffba2012-06-12 01:07:4822#include "chrome/browser/autocomplete/autocomplete_classifier_factory.h"
[email protected]9ac40092010-10-27 23:05:2623#include "chrome/browser/autocomplete/autocomplete_match.h"
[email protected]5af9bc82012-06-29 00:53:4824#include "chrome/browser/autocomplete/autocomplete_provider_listener.h"
[email protected]73c2b1632012-07-02 22:51:3825#include "chrome/browser/autocomplete/autocomplete_result.h"
[email protected]2c812ba02011-07-14 00:23:1526#include "chrome/browser/autocomplete/keyword_provider.h"
[email protected]371dab12012-06-01 03:23:5527#include "chrome/browser/autocomplete/url_prefix.h"
[email protected]6a2c09f2013-01-25 04:50:0728#include "chrome/browser/history/history_service.h"
[email protected]9d2db762012-06-19 00:01:1029#include "chrome/browser/history/history_service_factory.h"
[email protected]10c2d692012-05-11 05:32:2330#include "chrome/browser/history/in_memory_database.h"
[email protected]ab7780792013-01-10 01:26:0931#include "chrome/browser/metrics/variations/variations_http_header_provider.h"
[email protected]f870a322009-01-16 21:47:2732#include "chrome/browser/net/url_fixer_upper.h"
[email protected]684fcc12013-03-08 22:50:0233#include "chrome/browser/omnibox/omnibox_field_trial.h"
[email protected]8ecad5e2010-12-02 21:18:3334#include "chrome/browser/profiles/profile.h"
[email protected]a7b8e43d2013-03-18 18:52:4335#include "chrome/browser/search/search.h"
[email protected]a0ad93ea2012-05-07 22:11:5336#include "chrome/browser/search_engines/search_engine_type.h"
[email protected]9899a612012-08-21 23:50:0437#include "chrome/browser/search_engines/template_url_prepopulate_data.h"
[email protected]8e5c89a2011-06-07 18:13:3338#include "chrome/browser/search_engines/template_url_service.h"
39#include "chrome/browser/search_engines/template_url_service_factory.h"
initial.commit09911bf2008-07-26 23:55:2940#include "chrome/common/pref_names.h"
[email protected]dcf7d352009-02-26 01:56:0241#include "chrome/common/url_constants.h"
[email protected]34ac8f32009-02-22 23:03:2742#include "grit/generated_resources.h"
initial.commit09911bf2008-07-26 23:55:2943#include "net/base/escape.h"
[email protected]d3cf8682f02012-02-29 23:29:3444#include "net/base/load_flags.h"
[email protected]371dab12012-06-01 03:23:5545#include "net/base/net_util.h"
[email protected]bd3b4712012-12-18 17:01:3046#include "net/http/http_request_headers.h"
[email protected]319d9e6f2009-02-18 19:47:2147#include "net/http/http_response_headers.h"
[email protected]3dc1bc42012-06-19 08:20:5348#include "net/url_request/url_fetcher.h"
[email protected]319d9e6f2009-02-18 19:47:2149#include "net/url_request/url_request_status.h"
[email protected]c051a1b2011-01-21 23:30:1750#include "ui/base/l10n/l10n_util.h"
[email protected]761fa4702013-07-02 15:25:1551#include "url/url_util.h"
initial.commit09911bf2008-07-26 23:55:2952
[email protected]bc8bb0cd2013-06-24 21:50:2353
54// Helpers --------------------------------------------------------------------
[email protected]e1acf6f2008-10-27 20:43:3355
[email protected]51124552011-07-16 01:37:1056namespace {
57
[email protected]7706a522012-08-16 17:42:2558// We keep track in a histogram how many suggest requests we send, how
59// many suggest requests we invalidate (e.g., due to a user typing
60// another character), and how many replies we receive.
61// *** ADD NEW ENUMS AFTER ALL PREVIOUSLY DEFINED ONES! ***
62// (excluding the end-of-list enum value)
63// We do not want values of existing enums to change or else it screws
64// up the statistics.
65enum SuggestRequestsHistogramValue {
66 REQUEST_SENT = 1,
67 REQUEST_INVALIDATED,
68 REPLY_RECEIVED,
69 MAX_SUGGEST_REQUEST_HISTOGRAM_VALUE
70};
71
[email protected]90fe2bb2013-01-15 03:42:1372// The verbatim score for an input which is not an URL.
73const int kNonURLVerbatimRelevance = 1300;
74
[email protected]7706a522012-08-16 17:42:2575// Increments the appropriate value in the histogram by one.
76void LogOmniboxSuggestRequest(
77 SuggestRequestsHistogramValue request_value) {
78 UMA_HISTOGRAM_ENUMERATION("Omnibox.SuggestRequests", request_value,
79 MAX_SUGGEST_REQUEST_HISTOGRAM_VALUE);
80}
81
[email protected]51124552011-07-16 01:37:1082bool HasMultipleWords(const string16& text) {
83 base::i18n::BreakIterator i(text, base::i18n::BreakIterator::BREAK_WORD);
84 bool found_word = false;
85 if (i.Init()) {
86 while (i.Advance()) {
87 if (i.IsWord()) {
88 if (found_word)
89 return true;
90 found_word = true;
91 }
92 }
93 }
94 return false;
95}
96
[email protected]d1f0a7f2012-06-05 10:26:4297} // namespace
[email protected]51124552011-07-16 01:37:1098
[email protected]033f3422012-03-13 21:24:1899
[email protected]3954c3a2012-04-10 20:17:55100// SearchProvider::Providers --------------------------------------------------
[email protected]b547666d2009-04-23 16:37:58101
[email protected]85b8d6f2012-05-08 20:53:47102SearchProvider::Providers::Providers(TemplateURLService* template_url_service)
103 : template_url_service_(template_url_service) {
104}
105
106const TemplateURL* SearchProvider::Providers::GetDefaultProviderURL() const {
107 return default_provider_.empty() ? NULL :
108 template_url_service_->GetTemplateURLForKeyword(default_provider_);
109}
110
111const TemplateURL* SearchProvider::Providers::GetKeywordProviderURL() const {
112 return keyword_provider_.empty() ? NULL :
113 template_url_service_->GetTemplateURLForKeyword(keyword_provider_);
[email protected]257ab712009-04-14 17:16:24114}
115
[email protected]3954c3a2012-04-10 20:17:55116
[email protected]bc8bb0cd2013-06-24 21:50:23117// SearchProvider::Result -----------------------------------------------------
118
119SearchProvider::Result::Result(bool from_keyword_provider,
[email protected]d30268a2013-06-25 22:31:07120 int relevance,
121 bool relevance_from_server)
[email protected]bc8bb0cd2013-06-24 21:50:23122 : from_keyword_provider_(from_keyword_provider),
[email protected]d30268a2013-06-25 22:31:07123 relevance_(relevance),
124 relevance_from_server_(relevance_from_server) {
[email protected]bc8bb0cd2013-06-24 21:50:23125}
126
127SearchProvider::Result::~Result() {
128}
129
130
131// SearchProvider::SuggestResult ----------------------------------------------
132
133SearchProvider::SuggestResult::SuggestResult(const string16& suggestion,
134 bool from_keyword_provider,
[email protected]d30268a2013-06-25 22:31:07135 int relevance,
136 bool relevance_from_server)
137 : Result(from_keyword_provider, relevance, relevance_from_server),
[email protected]bc8bb0cd2013-06-24 21:50:23138 suggestion_(suggestion) {
139}
140
141SearchProvider::SuggestResult::~SuggestResult() {
142}
143
144bool SearchProvider::SuggestResult::IsInlineable(const string16& input) const {
145 return StartsWith(suggestion_, input, false);
146}
147
148int SearchProvider::SuggestResult::CalculateRelevance(
149 const AutocompleteInput& input,
150 bool keyword_provider_requested) const {
151 if (!from_keyword_provider_ && keyword_provider_requested)
152 return 100;
153 return ((input.type() == AutocompleteInput::URL) ? 300 : 600);
154}
155
156
157// SearchProvider::NavigationResult -------------------------------------------
158
159SearchProvider::NavigationResult::NavigationResult(
160 const AutocompleteProvider& provider,
161 const GURL& url,
162 const string16& description,
163 bool from_keyword_provider,
[email protected]d30268a2013-06-25 22:31:07164 int relevance,
165 bool relevance_from_server)
166 : Result(from_keyword_provider, relevance, relevance_from_server),
[email protected]bc8bb0cd2013-06-24 21:50:23167 url_(url),
168 formatted_url_(AutocompleteInput::FormattedStringWithEquivalentMeaning(
169 url, provider.StringForURLDisplay(url, true, false))),
170 description_(description) {
171 DCHECK(url_.is_valid());
172}
173
174SearchProvider::NavigationResult::~NavigationResult() {
175}
176
177bool SearchProvider::NavigationResult::IsInlineable(
178 const string16& input) const {
179 return URLPrefix::BestURLPrefix(formatted_url_, input) != NULL;
180}
181
182int SearchProvider::NavigationResult::CalculateRelevance(
183 const AutocompleteInput& input,
184 bool keyword_provider_requested) const {
185 return (from_keyword_provider_ || !keyword_provider_requested) ? 800 : 150;
186}
187
188
189// SearchProvider::CompareScoredResults ---------------------------------------
190
191class SearchProvider::CompareScoredResults {
192 public:
193 bool operator()(const Result& a, const Result& b) {
194 // Sort in descending relevance order.
195 return a.relevance() > b.relevance();
196 }
197};
198
199
200// SearchProvider::Results ----------------------------------------------------
201
[email protected]d30268a2013-06-25 22:31:07202SearchProvider::Results::Results() : verbatim_relevance(-1) {
[email protected]bc8bb0cd2013-06-24 21:50:23203}
204
205SearchProvider::Results::~Results() {
206}
207
208void SearchProvider::Results::Clear() {
209 suggest_results.clear();
210 navigation_results.clear();
[email protected]bc8bb0cd2013-06-24 21:50:23211 verbatim_relevance = -1;
212}
213
214bool SearchProvider::Results::HasServerProvidedScores() const {
215 if (verbatim_relevance >= 0)
216 return true;
217
[email protected]d30268a2013-06-25 22:31:07218 // Right now either all results of one type will be server-scored or they will
219 // all be locally scored, but in case we change this later, we'll just check
220 // them all.
221 for (SuggestResults::const_iterator i(suggest_results.begin());
222 i != suggest_results.end(); ++i) {
223 if (i->relevance_from_server())
224 return true;
225 }
226 for (NavigationResults::const_iterator i(navigation_results.begin());
227 i != navigation_results.end(); ++i) {
228 if (i->relevance_from_server())
229 return true;
230 }
231
232 return false;
[email protected]bc8bb0cd2013-06-24 21:50:23233}
[email protected]d30268a2013-06-25 22:31:07234
235
[email protected]3954c3a2012-04-10 20:17:55236// SearchProvider -------------------------------------------------------------
237
238// static
239const int SearchProvider::kDefaultProviderURLFetcherID = 1;
[email protected]3954c3a2012-04-10 20:17:55240const int SearchProvider::kKeywordProviderURLFetcherID = 2;
[email protected]24dbf2302013-04-05 16:59:25241int SearchProvider::kMinimumTimeBetweenSuggestQueriesMs = 100;
[email protected]d30268a2013-06-25 22:31:07242const char SearchProvider::kRelevanceFromServerKey[] = "relevance_from_server";
243const char SearchProvider::kTrue[] = "true";
244const char SearchProvider::kFalse[] = "false";
[email protected]3954c3a2012-04-10 20:17:55245
[email protected]bc8bb0cd2013-06-24 21:50:23246SearchProvider::SearchProvider(AutocompleteProviderListener* listener,
247 Profile* profile)
248 : AutocompleteProvider(listener, profile,
249 AutocompleteProvider::TYPE_SEARCH),
250 providers_(TemplateURLServiceFactory::GetForProfile(profile)),
251 suggest_results_pending_(0),
[email protected]bc8bb0cd2013-06-24 21:50:23252 field_trial_triggered_(false),
253 field_trial_triggered_in_session_(false),
[email protected]d8cd76b2013-07-10 09:46:16254 omnibox_start_margin_(-1),
255 prevent_search_history_inlining_(
256 OmniboxFieldTrial::SearchHistoryPreventInlining()),
257 disable_search_history_(
258 OmniboxFieldTrial::SearchHistoryDisable()) {
[email protected]bc8bb0cd2013-06-24 21:50:23259}
260
[email protected]cb86ee6f2013-04-28 16:58:15261// static
262AutocompleteMatch SearchProvider::CreateSearchSuggestion(
[email protected]cb86ee6f2013-04-28 16:58:15263 AutocompleteProvider* autocomplete_provider,
[email protected]cb86ee6f2013-04-28 16:58:15264 int relevance,
265 AutocompleteMatch::Type type,
[email protected]bba9e632013-06-28 22:52:19266 const TemplateURL* template_url,
267 const string16& query_string,
268 const string16& input_text,
269 const AutocompleteInput& input,
[email protected]cb86ee6f2013-04-28 16:58:15270 bool is_keyword,
[email protected]bba9e632013-06-28 22:52:19271 int accepted_suggestion,
[email protected]56fa29592013-07-02 20:25:53272 int omnibox_start_margin,
273 bool append_extra_query_params) {
[email protected]cb86ee6f2013-04-28 16:58:15274 AutocompleteMatch match(autocomplete_provider, relevance, false, type);
275
[email protected]bba9e632013-06-28 22:52:19276 if (!template_url)
[email protected]cb86ee6f2013-04-28 16:58:15277 return match;
[email protected]bba9e632013-06-28 22:52:19278 match.keyword = template_url->keyword();
[email protected]cb86ee6f2013-04-28 16:58:15279
280 match.contents.assign(query_string);
281 // We do intra-string highlighting for suggestions - the suggested segment
282 // will be highlighted, e.g. for input_text = "you" the suggestion may be
283 // "youtube", so we'll bold the "tube" section: you*tube*.
284 if (input_text != query_string) {
285 size_t input_position = match.contents.find(input_text);
286 if (input_position == string16::npos) {
287 // The input text is not a substring of the query string, e.g. input
288 // text is "slasdot" and the query string is "slashdot", so we bold the
289 // whole thing.
290 match.contents_class.push_back(
291 ACMatchClassification(0, ACMatchClassification::MATCH));
292 } else {
293 // TODO(beng): ACMatchClassification::MATCH now seems to just mean
294 // "bold" this. Consider modifying the terminology.
295 // We don't iterate over the string here annotating all matches because
296 // it looks odd to have every occurrence of a substring that may be as
297 // short as a single character highlighted in a query suggestion result,
298 // e.g. for input text "s" and query string "southwest airlines", it
299 // looks odd if both the first and last s are highlighted.
300 if (input_position != 0) {
301 match.contents_class.push_back(
[email protected]4b6d916e2013-06-07 05:02:08302 ACMatchClassification(0, ACMatchClassification::MATCH));
[email protected]cb86ee6f2013-04-28 16:58:15303 }
304 match.contents_class.push_back(
[email protected]4b6d916e2013-06-07 05:02:08305 ACMatchClassification(input_position, ACMatchClassification::NONE));
[email protected]cb86ee6f2013-04-28 16:58:15306 size_t next_fragment_position = input_position + input_text.length();
307 if (next_fragment_position < query_string.length()) {
308 match.contents_class.push_back(
309 ACMatchClassification(next_fragment_position,
[email protected]4b6d916e2013-06-07 05:02:08310 ACMatchClassification::MATCH));
[email protected]cb86ee6f2013-04-28 16:58:15311 }
312 }
313 } else {
314 // Otherwise, we're dealing with the "default search" result which has no
315 // completion.
316 match.contents_class.push_back(
317 ACMatchClassification(0, ACMatchClassification::NONE));
318 }
319
320 // When the user forced a query, we need to make sure all the fill_into_edit
321 // values preserve that property. Otherwise, if the user starts editing a
322 // suggestion, non-Search results will suddenly appear.
323 if (input.type() == AutocompleteInput::FORCED_QUERY)
324 match.fill_into_edit.assign(ASCIIToUTF16("?"));
325 if (is_keyword)
326 match.fill_into_edit.append(match.keyword + char16(' '));
327 if (!input.prevent_inline_autocomplete() &&
328 StartsWith(query_string, input_text, false)) {
329 match.inline_autocomplete_offset =
330 match.fill_into_edit.length() + input_text.length();
331 }
332 match.fill_into_edit.append(query_string);
333
[email protected]bba9e632013-06-28 22:52:19334 const TemplateURLRef& search_url = template_url->url_ref();
[email protected]cb86ee6f2013-04-28 16:58:15335 DCHECK(search_url.SupportsReplacement());
336 match.search_terms_args.reset(
337 new TemplateURLRef::SearchTermsArgs(query_string));
338 match.search_terms_args->original_query = input_text;
339 match.search_terms_args->accepted_suggestion = accepted_suggestion;
[email protected]f3e46eec2013-06-11 14:46:28340 match.search_terms_args->omnibox_start_margin = omnibox_start_margin;
[email protected]56fa29592013-07-02 20:25:53341 match.search_terms_args->append_extra_query_params =
342 append_extra_query_params;
[email protected]cb86ee6f2013-04-28 16:58:15343 // This is the destination URL sans assisted query stats. This must be set
344 // so the AutocompleteController can properly de-dupe; the controller will
345 // eventually overwrite it before it reaches the user.
346 match.destination_url =
347 GURL(search_url.ReplaceSearchTerms(*match.search_terms_args.get()));
348
349 // Search results don't look like URLs.
350 match.transition = is_keyword ?
351 content::PAGE_TRANSITION_KEYWORD : content::PAGE_TRANSITION_GENERATED;
352
353 return match;
354}
355
[email protected]bc8bb0cd2013-06-24 21:50:23356void SearchProvider::AddProviderInfo(ProvidersInfo* provider_info) const {
357 provider_info->push_back(metrics::OmniboxEventProto_ProviderInfo());
358 metrics::OmniboxEventProto_ProviderInfo& new_entry = provider_info->back();
359 new_entry.set_provider(AsOmniboxEventProviderType());
360 new_entry.set_provider_done(done_);
361 std::vector<uint32> field_trial_hashes;
362 OmniboxFieldTrial::GetActiveSuggestFieldTrialHashes(&field_trial_hashes);
363 for (size_t i = 0; i < field_trial_hashes.size(); ++i) {
364 if (field_trial_triggered_)
365 new_entry.mutable_field_trial_triggered()->Add(field_trial_hashes[i]);
366 if (field_trial_triggered_in_session_) {
367 new_entry.mutable_field_trial_triggered_in_session()->Add(
368 field_trial_hashes[i]);
369 }
370 }
371}
372
373void SearchProvider::ResetSession() {
374 field_trial_triggered_in_session_ = false;
[email protected]4ab4c7c2010-11-24 04:49:34375}
376
[email protected]f3e46eec2013-06-11 14:46:28377void SearchProvider::SetOmniboxStartMargin(int omnibox_start_margin) {
378 omnibox_start_margin_ = omnibox_start_margin;
379}
380
[email protected]bc8bb0cd2013-06-24 21:50:23381SearchProvider::~SearchProvider() {
382}
383
384// static
385void SearchProvider::RemoveStaleResults(const string16& input,
386 int verbatim_relevance,
387 SuggestResults* suggest_results,
388 NavigationResults* navigation_results) {
389 DCHECK_GE(verbatim_relevance, 0);
390 // Keep pointers to the head of (the highest scoring elements of)
391 // |suggest_results| and |navigation_results|. Iterate down the lists
392 // removing non-inlineable results in order of decreasing relevance
393 // scores. Stop when the highest scoring element among those remaining
394 // is inlineable or the element is less than |verbatim_relevance|.
395 // This allows non-inlineable lower-scoring results to remain
396 // because (i) they are guaranteed to not be inlined and (ii)
397 // letting them remain reduces visual jank. For instance, as the
398 // user types the mis-spelled query "fpobar" (for foobar), the
399 // suggestion "foobar" will be suggested on every keystroke. If the
400 // SearchProvider always removes all non-inlineable results, the user will
401 // see visual jitter/jank as the result disappears and re-appears moments
402 // later as the suggest server returns results.
403 SuggestResults::iterator sug_it = suggest_results->begin();
404 NavigationResults::iterator nav_it = navigation_results->begin();
405 while ((sug_it != suggest_results->end()) ||
406 (nav_it != navigation_results->end())) {
407 const int sug_rel =
408 (sug_it != suggest_results->end()) ? sug_it->relevance() : -1;
409 const int nav_rel =
410 (nav_it != navigation_results->end()) ? nav_it->relevance() : -1;
411 if (std::max(sug_rel, nav_rel) < verbatim_relevance)
412 break;
413 if (sug_rel > nav_rel) {
414 // The current top result is a search suggestion.
415 if (sug_it->IsInlineable(input))
416 break;
417 sug_it = suggest_results->erase(sug_it);
418 } else if (sug_rel == nav_rel) {
419 // Have both results and they're tied.
420 const bool sug_inlineable = sug_it->IsInlineable(input);
421 const bool nav_inlineable = nav_it->IsInlineable(input);
422 if (!sug_inlineable)
423 sug_it = suggest_results->erase(sug_it);
424 if (!nav_inlineable)
425 nav_it = navigation_results->erase(nav_it);
426 if (sug_inlineable || nav_inlineable)
427 break;
428 } else {
429 // The current top result is a navigational suggestion.
430 if (nav_it->IsInlineable(input))
431 break;
432 nav_it = navigation_results->erase(nav_it);
433 }
434 }
435}
436
437// static
438int SearchProvider::CalculateRelevanceForKeywordVerbatim(
439 AutocompleteInput::Type type,
440 bool prefer_keyword) {
441 // This function is responsible for scoring verbatim query matches
442 // for non-extension keywords. KeywordProvider::CalculateRelevance()
443 // scores verbatim query matches for extension keywords, as well as
444 // for keyword matches (i.e., suggestions of a keyword itself, not a
445 // suggestion of a query on a keyword search engine). These two
446 // functions are currently in sync, but there's no reason we
447 // couldn't decide in the future to score verbatim matches
448 // differently for extension and non-extension keywords. If you
449 // make such a change, however, you should update this comment to
450 // describe it, so it's clear why the functions diverge.
451 if (prefer_keyword)
452 return 1500;
453 return (type == AutocompleteInput::QUERY) ? 1450 : 1100;
454}
455
initial.commit09911bf2008-07-26 23:55:29456void SearchProvider::Start(const AutocompleteInput& input,
[email protected]8deeb952008-10-09 18:21:27457 bool minimal_changes) {
[email protected]04504c242013-01-22 21:08:55458 // Do our best to load the model as early as possible. This will reduce
459 // odds of having the model not ready when really needed (a non-empty input).
460 TemplateURLService* model = providers_.template_url_service();
461 DCHECK(model);
462 model->Load();
463
initial.commit09911bf2008-07-26 23:55:29464 matches_.clear();
[email protected]618d6e62012-12-16 05:55:57465 field_trial_triggered_ = false;
initial.commit09911bf2008-07-26 23:55:29466
[email protected]6c85aa02009-02-27 12:08:09467 // Can't return search/suggest results for bogus input or without a profile.
initial.commit09911bf2008-07-26 23:55:29468 if (!profile_ || (input.type() == AutocompleteInput::INVALID)) {
[email protected]e29249dc52012-07-19 17:33:50469 Stop(false);
initial.commit09911bf2008-07-26 23:55:29470 return;
471 }
472
[email protected]14710852013-02-05 23:45:41473 keyword_input_ = input;
[email protected]257ab712009-04-14 17:16:24474 const TemplateURL* keyword_provider =
[email protected]14710852013-02-05 23:45:41475 KeywordProvider::GetSubstitutingTemplateURLForInput(model,
476 &keyword_input_);
477 if (keyword_provider == NULL)
478 keyword_input_.Clear();
479 else if (keyword_input_.text().empty())
[email protected]257ab712009-04-14 17:16:24480 keyword_provider = NULL;
[email protected]257ab712009-04-14 17:16:24481
[email protected]85b8d6f2012-05-08 20:53:47482 const TemplateURL* default_provider = model->GetDefaultSearchProvider();
[email protected]9b74ab52012-03-30 16:08:07483 if (default_provider && !default_provider->SupportsReplacement())
[email protected]257ab712009-04-14 17:16:24484 default_provider = NULL;
485
486 if (keyword_provider == default_provider)
[email protected]e17511f2011-07-13 14:09:18487 default_provider = NULL; // No use in querying the same provider twice.
[email protected]257ab712009-04-14 17:16:24488
489 if (!default_provider && !keyword_provider) {
490 // No valid providers.
[email protected]e29249dc52012-07-19 17:33:50491 Stop(false);
initial.commit09911bf2008-07-26 23:55:29492 return;
493 }
494
495 // If we're still running an old query but have since changed the query text
[email protected]257ab712009-04-14 17:16:24496 // or the providers, abort the query.
[email protected]85b8d6f2012-05-08 20:53:47497 string16 default_provider_keyword(default_provider ?
498 default_provider->keyword() : string16());
499 string16 keyword_provider_keyword(keyword_provider ?
500 keyword_provider->keyword() : string16());
[email protected]9e789742011-01-10 23:27:32501 if (!minimal_changes ||
[email protected]85b8d6f2012-05-08 20:53:47502 !providers_.equal(default_provider_keyword, keyword_provider_keyword)) {
[email protected]bb900e02013-03-14 14:15:29503 // Cancel any in-flight suggest requests.
[email protected]e1290ee62013-06-26 18:31:15504 if (!done_)
[email protected]e29249dc52012-07-19 17:33:50505 Stop(false);
[email protected]257ab712009-04-14 17:16:24506 }
initial.commit09911bf2008-07-26 23:55:29507
[email protected]85b8d6f2012-05-08 20:53:47508 providers_.set(default_provider_keyword, keyword_provider_keyword);
initial.commit09911bf2008-07-26 23:55:29509
510 if (input.text().empty()) {
511 // User typed "?" alone. Give them a placeholder result indicating what
512 // this syntax does.
[email protected]257ab712009-04-14 17:16:24513 if (default_provider) {
[email protected]69c579e2010-04-23 20:01:00514 AutocompleteMatch match;
515 match.provider = this;
[email protected]a2fedb1e2011-01-25 15:23:36516 match.contents.assign(l10n_util::GetStringUTF16(IDS_EMPTY_KEYWORD_VALUE));
[email protected]257ab712009-04-14 17:16:24517 match.contents_class.push_back(
[email protected]2c33dd22010-02-11 21:46:35518 ACMatchClassification(0, ACMatchClassification::NONE));
[email protected]85b8d6f2012-05-08 20:53:47519 match.keyword = providers_.default_provider();
[email protected]257ab712009-04-14 17:16:24520 matches_.push_back(match);
521 }
[email protected]e29249dc52012-07-19 17:33:50522 Stop(false);
initial.commit09911bf2008-07-26 23:55:29523 return;
524 }
525
526 input_ = input;
527
[email protected]e1290ee62013-06-26 18:31:15528 DoHistoryQuery(minimal_changes);
529 StartOrStopSuggestQuery(minimal_changes);
[email protected]344946a12012-12-20 12:03:42530 UpdateMatches();
initial.commit09911bf2008-07-26 23:55:29531}
532
[email protected]e29249dc52012-07-19 17:33:50533void SearchProvider::Stop(bool clear_cached_results) {
initial.commit09911bf2008-07-26 23:55:29534 StopSuggest();
535 done_ = true;
[email protected]e29249dc52012-07-19 17:33:50536
537 if (clear_cached_results)
[email protected]71b46152013-05-03 16:39:20538 ClearAllResults();
initial.commit09911bf2008-07-26 23:55:29539}
540
[email protected]10c2d692012-05-11 05:32:23541void SearchProvider::OnURLFetchComplete(const net::URLFetcher* source) {
initial.commit09911bf2008-07-26 23:55:29542 DCHECK(!done_);
[email protected]257ab712009-04-14 17:16:24543 suggest_results_pending_--;
[email protected]7706a522012-08-16 17:42:25544 LogOmniboxSuggestRequest(REPLY_RECEIVED);
[email protected]1cb2dac2010-03-08 21:49:15545 DCHECK_GE(suggest_results_pending_, 0); // Should never go negative.
[email protected]ec9207d32008-09-26 00:51:06546 const net::HttpResponseHeaders* const response_headers =
[email protected]7cc6e5632011-10-25 17:56:12547 source->GetResponseHeaders();
[email protected]c530c852011-10-24 18:18:34548 std::string json_data;
549 source->GetResponseAsString(&json_data);
[email protected]6c85aa02009-02-27 12:08:09550 // JSON is supposed to be UTF-8, but some suggest service providers send JSON
551 // files in non-UTF-8 encodings. The actual encoding is usually specified in
552 // the Content-Type header field.
[email protected]ec9207d32008-09-26 00:51:06553 if (response_headers) {
554 std::string charset;
555 if (response_headers->GetCharset(&charset)) {
[email protected]a2fedb1e2011-01-25 15:23:36556 string16 data_16;
[email protected]ec9207d32008-09-26 00:51:06557 // TODO(jungshik): Switch to CodePageToUTF8 after it's added.
[email protected]c530c852011-10-24 18:18:34558 if (base::CodepageToUTF16(json_data, charset.c_str(),
[email protected]a2fedb1e2011-01-25 15:23:36559 base::OnStringConversionError::FAIL,
560 &data_16))
561 json_data = UTF16ToUTF8(data_16);
[email protected]ec9207d32008-09-26 00:51:06562 }
563 }
564
[email protected]d7ad4772012-06-01 03:12:54565 const bool is_keyword = (source == keyword_fetcher_.get());
[email protected]f2916ea2013-01-26 02:20:14566 // Ensure the request succeeded and that the provider used is still available.
567 // A verbatim match cannot be generated without this provider, causing errors.
[email protected]013e9a02012-05-18 20:27:10568 const bool request_succeeded =
[email protected]bc8bb0cd2013-06-24 21:50:23569 source->GetStatus().is_success() && (source->GetResponseCode() == 200) &&
570 (is_keyword ?
571 providers_.GetKeywordProviderURL() :
572 providers_.GetDefaultProviderURL());
[email protected]a0ad93ea2012-05-07 22:11:53573
574 // Record response time for suggest requests sent to Google. We care
575 // only about the common case: the Google default provider used in
576 // non-keyword mode.
[email protected]85b8d6f2012-05-08 20:53:47577 const TemplateURL* default_url = providers_.GetDefaultProviderURL();
[email protected]55ce8f12012-05-09 04:44:08578 if (!is_keyword && default_url &&
[email protected]9899a612012-08-21 23:50:04579 (TemplateURLPrepopulateData::GetEngineType(default_url->url()) ==
580 SEARCH_ENGINE_GOOGLE)) {
[email protected]bc8bb0cd2013-06-24 21:50:23581 const base::TimeDelta elapsed_time =
[email protected]013e9a02012-05-18 20:27:10582 base::TimeTicks::Now() - time_suggest_request_sent_;
583 if (request_succeeded) {
584 UMA_HISTOGRAM_TIMES("Omnibox.SuggestRequest.Success.GoogleResponseTime",
585 elapsed_time);
586 } else {
587 UMA_HISTOGRAM_TIMES("Omnibox.SuggestRequest.Failure.GoogleResponseTime",
588 elapsed_time);
589 }
[email protected]b4cebf82008-12-29 19:59:08590 }
591
[email protected]d7ad4772012-06-01 03:12:54592 bool results_updated = false;
593 if (request_succeeded) {
594 JSONStringValueSerializer deserializer(json_data);
595 deserializer.set_allow_trailing_comma(true);
596 scoped_ptr<Value> data(deserializer.Deserialize(NULL, NULL));
597 results_updated = data.get() && ParseSuggestResults(data.get(), is_keyword);
598 }
599
[email protected]344946a12012-12-20 12:03:42600 UpdateMatches();
[email protected]d7ad4772012-06-01 03:12:54601 if (done_ || results_updated)
602 listener_->OnProviderUpdate(results_updated);
initial.commit09911bf2008-07-26 23:55:29603}
604
[email protected]bc8bb0cd2013-06-24 21:50:23605void SearchProvider::Run() {
606 // Start a new request with the current input.
607 suggest_results_pending_ = 0;
608 time_suggest_request_sent_ = base::TimeTicks::Now();
[email protected]abe441e2013-05-06 12:35:05609
[email protected]bc8bb0cd2013-06-24 21:50:23610 default_fetcher_.reset(CreateSuggestFetcher(kDefaultProviderURLFetcherID,
611 providers_.GetDefaultProviderURL(), input_));
612 keyword_fetcher_.reset(CreateSuggestFetcher(kKeywordProviderURLFetcherID,
613 providers_.GetKeywordProviderURL(), keyword_input_));
614
615 // Both the above can fail if the providers have been modified or deleted
616 // since the query began.
617 if (suggest_results_pending_ == 0) {
618 UpdateDone();
619 // We only need to update the listener if we're actually done.
620 if (done_)
621 listener_->OnProviderUpdate(false);
622 }
[email protected]601858c02010-09-01 17:08:20623}
624
[email protected]8d457132010-11-04 18:13:40625void SearchProvider::DoHistoryQuery(bool minimal_changes) {
626 // The history query results are synchronous, so if minimal_changes is true,
627 // we still have the last results and don't need to do anything.
628 if (minimal_changes)
initial.commit09911bf2008-07-26 23:55:29629 return;
630
[email protected]8d457132010-11-04 18:13:40631 keyword_history_results_.clear();
632 default_history_results_.clear();
initial.commit09911bf2008-07-26 23:55:29633
[email protected]d8cd76b2013-07-10 09:46:16634 if (disable_search_history_)
635 return;
636
[email protected]8d457132010-11-04 18:13:40637 HistoryService* const history_service =
[email protected]9d2db762012-06-19 00:01:10638 HistoryServiceFactory::GetForProfile(profile_, Profile::EXPLICIT_ACCESS);
[email protected]8d457132010-11-04 18:13:40639 history::URLDatabase* url_db = history_service ?
640 history_service->InMemoryDatabase() : NULL;
641 if (!url_db)
initial.commit09911bf2008-07-26 23:55:29642 return;
643
[email protected]51124552011-07-16 01:37:10644 // Request history for both the keyword and default provider. We grab many
645 // more matches than we'll ultimately clamp to so that if there are several
646 // recent multi-word matches who scores are lowered (see
647 // AddHistoryResultsToMap()), they won't crowd out older, higher-scoring
648 // matches. Note that this doesn't fix the problem entirely, but merely
649 // limits it to cases with a very large number of such multi-word matches; for
650 // now, this seems OK compared with the complexity of a real fix, which would
651 // require multiple searches and tracking of "single- vs. multi-word" in the
652 // database.
653 int num_matches = kMaxMatches * 5;
[email protected]85b8d6f2012-05-08 20:53:47654 const TemplateURL* default_url = providers_.GetDefaultProviderURL();
655 if (default_url) {
656 url_db->GetMostRecentKeywordSearchTerms(default_url->id(), input_.text(),
657 num_matches, &default_history_results_);
[email protected]257ab712009-04-14 17:16:24658 }
[email protected]85b8d6f2012-05-08 20:53:47659 const TemplateURL* keyword_url = providers_.GetKeywordProviderURL();
660 if (keyword_url) {
661 url_db->GetMostRecentKeywordSearchTerms(keyword_url->id(),
[email protected]14710852013-02-05 23:45:41662 keyword_input_.text(), num_matches, &keyword_history_results_);
[email protected]3954c3a2012-04-10 20:17:55663 }
initial.commit09911bf2008-07-26 23:55:29664}
665
[email protected]6dc950f2012-07-16 19:49:08666void SearchProvider::StartOrStopSuggestQuery(bool minimal_changes) {
[email protected]83c726482008-09-10 06:36:34667 if (!IsQuerySuitableForSuggest()) {
initial.commit09911bf2008-07-26 23:55:29668 StopSuggest();
[email protected]71b46152013-05-03 16:39:20669 ClearAllResults();
initial.commit09911bf2008-07-26 23:55:29670 return;
671 }
672
673 // For the minimal_changes case, if we finished the previous query and still
674 // have its results, or are allowed to keep running it, just do that, rather
675 // than starting a new query.
676 if (minimal_changes &&
[email protected]cc1526e2013-05-17 04:04:24677 (!default_results_.suggest_results.empty() ||
678 !default_results_.navigation_results.empty() ||
679 !keyword_results_.suggest_results.empty() ||
680 !keyword_results_.navigation_results.empty() ||
[email protected]ea3b9a502011-04-04 14:19:37681 (!done_ &&
682 input_.matches_requested() == AutocompleteInput::ALL_MATCHES)))
initial.commit09911bf2008-07-26 23:55:29683 return;
684
685 // We can't keep running any previous query, so halt it.
686 StopSuggest();
[email protected]d1f0a7f2012-06-05 10:26:42687
688 // Remove existing results that cannot inline autocomplete the new input.
[email protected]71b46152013-05-03 16:39:20689 RemoveAllStaleResults();
initial.commit09911bf2008-07-26 23:55:29690
691 // We can't start a new query if we're only allowed synchronous results.
[email protected]ea3b9a502011-04-04 14:19:37692 if (input_.matches_requested() != AutocompleteInput::ALL_MATCHES)
initial.commit09911bf2008-07-26 23:55:29693 return;
694
[email protected]24dbf2302013-04-05 16:59:25695 // To avoid flooding the suggest server, don't send a query until at
696 // least 100 ms since the last query.
[email protected]515ffa942012-11-27 20:18:24697 base::TimeTicks next_suggest_time(time_suggest_request_sent_ +
[email protected]bc8bb0cd2013-06-24 21:50:23698 base::TimeDelta::FromMilliseconds(kMinimumTimeBetweenSuggestQueriesMs));
[email protected]515ffa942012-11-27 20:18:24699 base::TimeTicks now(base::TimeTicks::Now());
700 if (now >= next_suggest_time) {
701 Run();
702 return;
703 }
704 timer_.Start(FROM_HERE, next_suggest_time - now, this, &SearchProvider::Run);
initial.commit09911bf2008-07-26 23:55:29705}
706
[email protected]83c726482008-09-10 06:36:34707bool SearchProvider::IsQuerySuitableForSuggest() const {
[email protected]3954c3a2012-04-10 20:17:55708 // Don't run Suggest in incognito mode, if the engine doesn't support it, or
709 // if the user has disabled it.
[email protected]85b8d6f2012-05-08 20:53:47710 const TemplateURL* default_url = providers_.GetDefaultProviderURL();
711 const TemplateURL* keyword_url = providers_.GetKeywordProviderURL();
[email protected]83c726482008-09-10 06:36:34712 if (profile_->IsOffTheRecord() ||
[email protected]85b8d6f2012-05-08 20:53:47713 ((!default_url || default_url->suggestions_url().empty()) &&
714 (!keyword_url || keyword_url->suggestions_url().empty())) ||
[email protected]83c726482008-09-10 06:36:34715 !profile_->GetPrefs()->GetBoolean(prefs::kSearchSuggestEnabled))
716 return false;
717
[email protected]cac59d32010-08-09 23:23:14718 // If the input type might be a URL, we take extra care so that private data
[email protected]83c726482008-09-10 06:36:34719 // isn't sent to the server.
[email protected]83c726482008-09-10 06:36:34720
[email protected]cac59d32010-08-09 23:23:14721 // FORCED_QUERY means the user is explicitly asking us to search for this, so
722 // we assume it isn't a URL and/or there isn't private data.
723 if (input_.type() == AutocompleteInput::FORCED_QUERY)
724 return true;
[email protected]83c726482008-09-10 06:36:34725
[email protected]f608ea102013-03-18 15:08:09726 // Next we check the scheme. If this is UNKNOWN/URL with a scheme that isn't
727 // http/https/ftp, we shouldn't send it. Sending things like file: and data:
728 // is both a waste of time and a disclosure of potentially private, local
729 // data. Other "schemes" may actually be usernames, and we don't want to send
730 // passwords. If the scheme is OK, we still need to check other cases below.
731 // If this is QUERY, then the presence of these schemes means the user
732 // explicitly typed one, and thus this is probably a URL that's being entered
733 // and happens to currently be invalid -- in which case we again want to run
734 // our checks below. Other QUERY cases are less likely to be URLs and thus we
735 // assume we're OK.
[email protected]a2fedb1e2011-01-25 15:23:36736 if (!LowerCaseEqualsASCII(input_.scheme(), chrome::kHttpScheme) &&
737 !LowerCaseEqualsASCII(input_.scheme(), chrome::kHttpsScheme) &&
738 !LowerCaseEqualsASCII(input_.scheme(), chrome::kFtpScheme))
[email protected]cac59d32010-08-09 23:23:14739 return (input_.type() == AutocompleteInput::QUERY);
740
741 // Don't send URLs with usernames, queries or refs. Some of these are
742 // private, and the Suggest server is unlikely to have any useful results
743 // for any of them. Also don't send URLs with ports, as we may initially
744 // think that a username + password is a host + port (and we don't want to
745 // send usernames/passwords), and even if the port really is a port, the
746 // server is once again unlikely to have and useful results.
747 const url_parse::Parsed& parts = input_.parts();
748 if (parts.username.is_nonempty() || parts.port.is_nonempty() ||
749 parts.query.is_nonempty() || parts.ref.is_nonempty())
750 return false;
751
752 // Don't send anything for https except the hostname. Hostnames are OK
753 // because they are visible when the TCP connection is established, but the
754 // specific path may reveal private information.
[email protected]a2fedb1e2011-01-25 15:23:36755 if (LowerCaseEqualsASCII(input_.scheme(), chrome::kHttpsScheme) &&
756 parts.path.is_nonempty())
[email protected]cac59d32010-08-09 23:23:14757 return false;
[email protected]83c726482008-09-10 06:36:34758
759 return true;
760}
761
initial.commit09911bf2008-07-26 23:55:29762void SearchProvider::StopSuggest() {
[email protected]7706a522012-08-16 17:42:25763 // Increment the appropriate field in the histogram by the number of
764 // pending requests that were invalidated.
765 for (int i = 0; i < suggest_results_pending_; i++)
766 LogOmniboxSuggestRequest(REQUEST_INVALIDATED);
[email protected]257ab712009-04-14 17:16:24767 suggest_results_pending_ = 0;
[email protected]2d316662008-09-03 18:18:14768 timer_.Stop();
[email protected]257ab712009-04-14 17:16:24769 // Stop any in-progress URL fetches.
770 keyword_fetcher_.reset();
771 default_fetcher_.reset();
[email protected]55ce8f12012-05-09 04:44:08772}
773
[email protected]71b46152013-05-03 16:39:20774void SearchProvider::ClearAllResults() {
[email protected]cc1526e2013-05-17 04:04:24775 keyword_results_.Clear();
776 default_results_.Clear();
[email protected]1e1550e2013-05-02 17:37:51777}
778
[email protected]71b46152013-05-03 16:39:20779void SearchProvider::RemoveAllStaleResults() {
[email protected]1e1550e2013-05-02 17:37:51780 // In theory it would be better to run an algorithm like that in
781 // RemoveStaleResults(...) below that uses all four results lists
782 // and both verbatim scores at once. However, that will be much
783 // more complicated for little obvious gain. For code simplicity
784 // and ease in reasoning about the invariants involved, this code
785 // removes stales results from the keyword provider and default
786 // provider independently.
[email protected]d30268a2013-06-25 22:31:07787 RemoveStaleResults(input_.text(), GetVerbatimRelevance(NULL),
[email protected]cc1526e2013-05-17 04:04:24788 &default_results_.suggest_results,
789 &default_results_.navigation_results);
[email protected]1e1550e2013-05-02 17:37:51790 if (!keyword_input_.text().empty()) {
[email protected]d30268a2013-06-25 22:31:07791 RemoveStaleResults(keyword_input_.text(), GetKeywordVerbatimRelevance(NULL),
[email protected]cc1526e2013-05-17 04:04:24792 &keyword_results_.suggest_results,
793 &keyword_results_.navigation_results);
[email protected]1e1550e2013-05-02 17:37:51794 } else {
795 // User is either in keyword mode with a blank input or out of
796 // keyword mode entirely.
[email protected]cc1526e2013-05-17 04:04:24797 keyword_results_.Clear();
[email protected]1e1550e2013-05-02 17:37:51798 }
[email protected]d1f0a7f2012-06-05 10:26:42799}
800
[email protected]d1f0a7f2012-06-05 10:26:42801void SearchProvider::ApplyCalculatedRelevance() {
[email protected]cc1526e2013-05-17 04:04:24802 ApplyCalculatedSuggestRelevance(&keyword_results_.suggest_results);
803 ApplyCalculatedSuggestRelevance(&default_results_.suggest_results);
804 ApplyCalculatedNavigationRelevance(&keyword_results_.navigation_results);
805 ApplyCalculatedNavigationRelevance(&default_results_.navigation_results);
[email protected]cc1526e2013-05-17 04:04:24806 default_results_.verbatim_relevance = -1;
807 keyword_results_.verbatim_relevance = -1;
[email protected]d1f0a7f2012-06-05 10:26:42808}
809
[email protected]188b50c2013-03-28 07:19:42810void SearchProvider::ApplyCalculatedSuggestRelevance(SuggestResults* list) {
[email protected]d1f0a7f2012-06-05 10:26:42811 for (size_t i = 0; i < list->size(); ++i) {
[email protected]188b50c2013-03-28 07:19:42812 SuggestResult& result = (*list)[i];
813 result.set_relevance(
814 result.CalculateRelevance(input_, providers_.has_keyword_provider()) +
815 (list->size() - i - 1));
[email protected]d30268a2013-06-25 22:31:07816 result.set_relevance_from_server(false);
[email protected]d1f0a7f2012-06-05 10:26:42817 }
818}
819
[email protected]188b50c2013-03-28 07:19:42820void SearchProvider::ApplyCalculatedNavigationRelevance(
821 NavigationResults* list) {
[email protected]d1f0a7f2012-06-05 10:26:42822 for (size_t i = 0; i < list->size(); ++i) {
[email protected]188b50c2013-03-28 07:19:42823 NavigationResult& result = (*list)[i];
824 result.set_relevance(
825 result.CalculateRelevance(input_, providers_.has_keyword_provider()) +
826 (list->size() - i - 1));
[email protected]d30268a2013-06-25 22:31:07827 result.set_relevance_from_server(false);
[email protected]d1f0a7f2012-06-05 10:26:42828 }
829}
830
[email protected]15fb2aa2012-05-22 22:52:59831net::URLFetcher* SearchProvider::CreateSuggestFetcher(
[email protected]7cc6e5632011-10-25 17:56:12832 int id,
[email protected]9ff91722012-09-07 05:29:12833 const TemplateURL* template_url,
[email protected]14710852013-02-05 23:45:41834 const AutocompleteInput& input) {
[email protected]9ff91722012-09-07 05:29:12835 if (!template_url || template_url->suggestions_url().empty())
836 return NULL;
837
838 // Bail if the suggestion URL is invalid with the given replacements.
[email protected]14710852013-02-05 23:45:41839 TemplateURLRef::SearchTermsArgs search_term_args(input.text());
840 search_term_args.cursor_position = input.cursor_position();
[email protected]9ff91722012-09-07 05:29:12841 GURL suggest_url(template_url->suggestions_url_ref().ReplaceSearchTerms(
[email protected]00790562012-12-14 09:57:16842 search_term_args));
[email protected]9ff91722012-09-07 05:29:12843 if (!suggest_url.is_valid())
844 return NULL;
845
846 suggest_results_pending_++;
847 LogOmniboxSuggestRequest(REQUEST_SENT);
848
849 net::URLFetcher* fetcher =
850 net::URLFetcher::Create(id, suggest_url, net::URLFetcher::GET, this);
[email protected]7cc6e5632011-10-25 17:56:12851 fetcher->SetRequestContext(profile_->GetRequestContext());
[email protected]d3cf8682f02012-02-29 23:29:34852 fetcher->SetLoadFlags(net::LOAD_DO_NOT_SAVE_COOKIES);
[email protected]bd3b4712012-12-18 17:01:30853 // Add Chrome experiment state to the request headers.
854 net::HttpRequestHeaders headers;
[email protected]ab7780792013-01-10 01:26:09855 chrome_variations::VariationsHttpHeaderProvider::GetInstance()->AppendHeaders(
[email protected]bd3b4712012-12-18 17:01:30856 fetcher->GetOriginalURL(), profile_->IsOffTheRecord(), false, &headers);
857 fetcher->SetExtraRequestHeaders(headers.ToString());
[email protected]257ab712009-04-14 17:16:24858 fetcher->Start();
859 return fetcher;
860}
861
[email protected]d7ad4772012-06-01 03:12:54862bool SearchProvider::ParseSuggestResults(Value* root_val, bool is_keyword) {
[email protected]d7ad4772012-06-01 03:12:54863 string16 query;
864 ListValue* root_list = NULL;
[email protected]cc1526e2013-05-17 04:04:24865 ListValue* results_list = NULL;
[email protected]14710852013-02-05 23:45:41866 const string16& input_text =
867 is_keyword ? keyword_input_.text() : input_.text();
[email protected]d7ad4772012-06-01 03:12:54868 if (!root_val->GetAsList(&root_list) || !root_list->GetString(0, &query) ||
[email protected]cc1526e2013-05-17 04:04:24869 (query != input_text) || !root_list->GetList(1, &results_list))
initial.commit09911bf2008-07-26 23:55:29870 return false;
871
[email protected]55ce8f12012-05-09 04:44:08872 // 3rd element: Description list.
[email protected]d7ad4772012-06-01 03:12:54873 ListValue* descriptions = NULL;
874 root_list->GetList(2, &descriptions);
initial.commit09911bf2008-07-26 23:55:29875
[email protected]55ce8f12012-05-09 04:44:08876 // 4th element: Disregard the query URL list for now.
initial.commit09911bf2008-07-26 23:55:29877
[email protected]d1f0a7f2012-06-05 10:26:42878 // Reset suggested relevance information from the default provider.
[email protected]cc1526e2013-05-17 04:04:24879 Results* results = is_keyword ? &keyword_results_ : &default_results_;
[email protected]cc1526e2013-05-17 04:04:24880 results->verbatim_relevance = -1;
[email protected]d1f0a7f2012-06-05 10:26:42881
[email protected]55ce8f12012-05-09 04:44:08882 // 5th element: Optional key-value pairs from the Suggest server.
[email protected]d7ad4772012-06-01 03:12:54883 ListValue* types = NULL;
[email protected]d1f0a7f2012-06-05 10:26:42884 ListValue* relevances = NULL;
885 DictionaryValue* extras = NULL;
886 if (root_list->GetDictionary(4, &extras)) {
887 extras->GetList("google:suggesttype", &types);
888
[email protected]eb8330d2013-06-15 00:55:08889 // Discard this list if its size does not match that of the suggestions.
890 if (extras->GetList("google:suggestrelevance", &relevances) &&
891 relevances->GetSize() != results_list->GetSize())
892 relevances = NULL;
893 extras->GetInteger("google:verbatimrelevance",
894 &results->verbatim_relevance);
[email protected]618d6e62012-12-16 05:55:57895
896 // Check if the active suggest field trial (if any) has triggered either
897 // for the default provider or keyword provider.
898 bool triggered = false;
899 extras->GetBoolean("google:fieldtrialtriggered", &triggered);
900 field_trial_triggered_ |= triggered;
901 field_trial_triggered_in_session_ |= triggered;
initial.commit09911bf2008-07-26 23:55:29902 }
903
[email protected]d1f0a7f2012-06-05 10:26:42904 // Clear the previous results now that new results are available.
[email protected]cc1526e2013-05-17 04:04:24905 results->suggest_results.clear();
906 results->navigation_results.clear();
[email protected]d1f0a7f2012-06-05 10:26:42907
908 string16 result, title;
909 std::string type;
910 int relevance = -1;
[email protected]cc1526e2013-05-17 04:04:24911 for (size_t index = 0; results_list->GetString(index, &result); ++index) {
[email protected]8e81f5092010-09-29 23:19:40912 // Google search may return empty suggestions for weird input characters,
[email protected]55ce8f12012-05-09 04:44:08913 // they make no sense at all and can cause problems in our code.
[email protected]d7ad4772012-06-01 03:12:54914 if (result.empty())
[email protected]8e81f5092010-09-29 23:19:40915 continue;
916
[email protected]d1f0a7f2012-06-05 10:26:42917 // Apply valid suggested relevance scores; discard invalid lists.
918 if (relevances != NULL && !relevances->GetInteger(index, &relevance))
919 relevances = NULL;
[email protected]d7ad4772012-06-01 03:12:54920 if (types && types->GetString(index, &type) && (type == "NAVIGATION")) {
[email protected]d1f0a7f2012-06-05 10:26:42921 // Do not blindly trust the URL coming from the server to be valid.
922 GURL url(URLFixerUpper::FixupURL(UTF16ToUTF8(result), std::string()));
923 if (url.is_valid()) {
924 if (descriptions != NULL)
925 descriptions->GetString(index, &title);
[email protected]d30268a2013-06-25 22:31:07926 results->navigation_results.push_back(NavigationResult(
927 *this, url, title, is_keyword, relevance, true));
initial.commit09911bf2008-07-26 23:55:29928 }
929 } else {
[email protected]d1f0a7f2012-06-05 10:26:42930 // TODO(kochi): Improve calculator result presentation.
[email protected]cc1526e2013-05-17 04:04:24931 results->suggest_results.push_back(
[email protected]d30268a2013-06-25 22:31:07932 SuggestResult(result, is_keyword, relevance, true));
initial.commit09911bf2008-07-26 23:55:29933 }
934 }
935
[email protected]d1f0a7f2012-06-05 10:26:42936 // Apply calculated relevance scores if a valid list was not provided.
937 if (relevances == NULL) {
[email protected]cc1526e2013-05-17 04:04:24938 ApplyCalculatedSuggestRelevance(&results->suggest_results);
939 ApplyCalculatedNavigationRelevance(&results->navigation_results);
[email protected]d1f0a7f2012-06-05 10:26:42940 }
[email protected]9dfb4d362013-04-05 02:15:12941 // Keep the result lists sorted.
942 const CompareScoredResults comparator = CompareScoredResults();
[email protected]cc1526e2013-05-17 04:04:24943 std::stable_sort(results->suggest_results.begin(),
944 results->suggest_results.end(),
[email protected]9dfb4d362013-04-05 02:15:12945 comparator);
[email protected]cc1526e2013-05-17 04:04:24946 std::stable_sort(results->navigation_results.begin(),
947 results->navigation_results.end(),
[email protected]9dfb4d362013-04-05 02:15:12948 comparator);
[email protected]d1f0a7f2012-06-05 10:26:42949 return true;
initial.commit09911bf2008-07-26 23:55:29950}
951
[email protected]344946a12012-12-20 12:03:42952void SearchProvider::ConvertResultsToAutocompleteMatches() {
initial.commit09911bf2008-07-26 23:55:29953 // Convert all the results to matches and add them to a map, so we can keep
954 // the most relevant match for each result.
955 MatchMap map;
[email protected]bc8bb0cd2013-06-24 21:50:23956 const base::Time no_time;
[email protected]cc1526e2013-05-17 04:04:24957 int did_not_accept_keyword_suggestion =
958 keyword_results_.suggest_results.empty() ?
initial.commit09911bf2008-07-26 23:55:29959 TemplateURLRef::NO_SUGGESTIONS_AVAILABLE :
960 TemplateURLRef::NO_SUGGESTION_CHOSEN;
initial.commit09911bf2008-07-26 23:55:29961
[email protected]d30268a2013-06-25 22:31:07962 bool relevance_from_server;
963 int verbatim_relevance = GetVerbatimRelevance(&relevance_from_server);
[email protected]cc1526e2013-05-17 04:04:24964 int did_not_accept_default_suggestion =
965 default_results_.suggest_results.empty() ?
[email protected]55ce8f12012-05-09 04:44:08966 TemplateURLRef::NO_SUGGESTIONS_AVAILABLE :
967 TemplateURLRef::NO_SUGGESTION_CHOSEN;
[email protected]d1f0a7f2012-06-05 10:26:42968 if (verbatim_relevance > 0) {
969 AddMatchToMap(input_.text(), input_.text(), verbatim_relevance,
[email protected]d30268a2013-06-25 22:31:07970 relevance_from_server,
[email protected]b7f64d742013-05-21 04:04:04971 AutocompleteMatchType::SEARCH_WHAT_YOU_TYPED,
[email protected]d1f0a7f2012-06-05 10:26:42972 did_not_accept_default_suggestion, false, &map);
973 }
[email protected]5423e562013-02-07 03:58:45974 if (!keyword_input_.text().empty()) {
975 const TemplateURL* keyword_url = providers_.GetKeywordProviderURL();
976 // We only create the verbatim search query match for a keyword
977 // if it's not an extension keyword. Extension keywords are handled
978 // in KeywordProvider::Start(). (Extensions are complicated...)
979 // Note: in this provider, SEARCH_OTHER_ENGINE must correspond
980 // to the keyword verbatim search query. Do not create other matches
981 // of type SEARCH_OTHER_ENGINE.
982 if (keyword_url && !keyword_url->IsExtensionKeyword()) {
[email protected]d30268a2013-06-25 22:31:07983 bool keyword_relevance_from_server;
984 const int keyword_verbatim_relevance =
985 GetKeywordVerbatimRelevance(&keyword_relevance_from_server);
[email protected]dab8d52d2013-03-05 07:35:28986 if (keyword_verbatim_relevance > 0) {
987 AddMatchToMap(keyword_input_.text(), keyword_input_.text(),
[email protected]d30268a2013-06-25 22:31:07988 keyword_verbatim_relevance, keyword_relevance_from_server,
[email protected]b7f64d742013-05-21 04:04:04989 AutocompleteMatchType::SEARCH_OTHER_ENGINE,
[email protected]dab8d52d2013-03-05 07:35:28990 did_not_accept_keyword_suggestion, true, &map);
991 }
[email protected]5423e562013-02-07 03:58:45992 }
993 }
[email protected]257ab712009-04-14 17:16:24994 AddHistoryResultsToMap(keyword_history_results_, true,
995 did_not_accept_keyword_suggestion, &map);
996 AddHistoryResultsToMap(default_history_results_, false,
997 did_not_accept_default_suggestion, &map);
998
[email protected]cc1526e2013-05-17 04:04:24999 AddSuggestResultsToMap(keyword_results_.suggest_results, &map);
1000 AddSuggestResultsToMap(default_results_.suggest_results, &map);
initial.commit09911bf2008-07-26 23:55:291001
[email protected]d30268a2013-06-25 22:31:071002 ACMatches matches;
initial.commit09911bf2008-07-26 23:55:291003 for (MatchMap::const_iterator i(map.begin()); i != map.end(); ++i)
[email protected]d30268a2013-06-25 22:31:071004 matches.push_back(i->second);
initial.commit09911bf2008-07-26 23:55:291005
[email protected]d30268a2013-06-25 22:31:071006 AddNavigationResultsToMatches(keyword_results_.navigation_results, &matches);
1007 AddNavigationResultsToMatches(default_results_.navigation_results, &matches);
initial.commit09911bf2008-07-26 23:55:291008
[email protected]d30268a2013-06-25 22:31:071009 // Now add the most relevant matches to |matches_|. We take up to kMaxMatches
1010 // suggest/navsuggest matches, regardless of origin. If Instant Extended is
1011 // enabled and we have server-provided (and thus hopefully more accurate)
1012 // scores for some suggestions, we allow more of those, until we reach
1013 // AutocompleteResult::kMaxMatches total matches (that is, enough to fill the
1014 // whole popup).
1015 //
1016 // We will always return any verbatim matches, no matter how we obtained their
1017 // scores, unless we have already accepted AutocompleteResult::kMaxMatches
1018 // higher-scoring matches under the conditions above.
1019 std::sort(matches.begin(), matches.end(), &AutocompleteMatch::MoreRelevant);
1020 matches_.clear();
[email protected]3723e6e2012-06-11 21:06:561021
[email protected]d30268a2013-06-25 22:31:071022 size_t num_suggestions = 0;
1023 for (ACMatches::const_iterator i(matches.begin());
1024 (i != matches.end()) &&
1025 (matches_.size() < AutocompleteResult::kMaxMatches);
1026 ++i) {
1027 // SEARCH_OTHER_ENGINE is only used in the SearchProvider for the keyword
1028 // verbatim result, so this condition basically means "if this match is a
1029 // suggestion of some sort".
1030 if ((i->type != AutocompleteMatchType::SEARCH_WHAT_YOU_TYPED) &&
1031 (i->type != AutocompleteMatchType::SEARCH_OTHER_ENGINE)) {
1032 // If we've already hit the limit on non-server-scored suggestions, and
1033 // this isn't a server-scored suggestion we can add, skip it.
1034 if ((num_suggestions >= kMaxMatches) &&
1035 (!chrome::IsInstantExtendedAPIEnabled() ||
1036 (i->GetAdditionalInfo(kRelevanceFromServerKey) != kTrue))) {
1037 continue;
1038 }
1039
1040 ++num_suggestions;
1041 }
1042
1043 matches_.push_back(*i);
1044 }
[email protected]344946a12012-12-20 12:03:421045}
1046
[email protected]9dfb4d362013-04-05 02:15:121047bool SearchProvider::IsTopMatchNavigationInKeywordMode() const {
1048 return (!providers_.keyword_provider().empty() &&
[email protected]b7f64d742013-05-21 04:04:041049 (matches_.front().type == AutocompleteMatchType::NAVSUGGEST));
[email protected]9dfb4d362013-04-05 02:15:121050}
1051
[email protected]344946a12012-12-20 12:03:421052bool SearchProvider::IsTopMatchScoreTooLow() const {
[email protected]dab8d52d2013-03-05 07:35:281053 // Here we use CalculateRelevanceForVerbatimIgnoringKeywordModeState()
1054 // rather than CalculateRelevanceForVerbatim() because the latter returns
1055 // a very low score (250) if keyword mode is active. This is because
1056 // when keyword mode is active the user probably wants the keyword matches,
1057 // not matches from the default provider. Hence, we use the version of
1058 // the function that ignores whether keyword mode is active. This allows
1059 // SearchProvider to maintain its contract with the AutocompleteController
1060 // that it will always provide an inlineable match with a reasonable
1061 // score.
1062 return matches_.front().relevance <
1063 CalculateRelevanceForVerbatimIgnoringKeywordModeState();
[email protected]344946a12012-12-20 12:03:421064}
1065
[email protected]fb95251e2013-07-17 14:52:241066bool SearchProvider::IsTopMatchSearchWithURLInput() const {
[email protected]344946a12012-12-20 12:03:421067 return input_.type() == AutocompleteInput::URL &&
1068 matches_.front().relevance > CalculateRelevanceForVerbatim() &&
[email protected]fb95251e2013-07-17 14:52:241069 matches_.front().type != AutocompleteMatchType::NAVSUGGEST;
[email protected]344946a12012-12-20 12:03:421070}
1071
1072bool SearchProvider::IsTopMatchNotInlinable() const {
[email protected]5423e562013-02-07 03:58:451073 // Note: this test assumes the SEARCH_OTHER_ENGINE match corresponds to
1074 // the verbatim search query on the keyword engine. SearchProvider should
1075 // not create any other match of type SEARCH_OTHER_ENGINE.
[email protected]b7f64d742013-05-21 04:04:041076 return
1077 matches_.front().type != AutocompleteMatchType::SEARCH_WHAT_YOU_TYPED &&
[email protected]b7f64d742013-05-21 04:04:041078 matches_.front().type != AutocompleteMatchType::SEARCH_OTHER_ENGINE &&
1079 matches_.front().inline_autocomplete_offset == string16::npos &&
1080 matches_.front().fill_into_edit != input_.text();
[email protected]344946a12012-12-20 12:03:421081}
1082
1083void SearchProvider::UpdateMatches() {
1084 ConvertResultsToAutocompleteMatches();
initial.commit09911bf2008-07-26 23:55:291085
[email protected]382a0642012-06-06 06:13:521086 // Check constraints that may be violated by suggested relevances.
[email protected]344946a12012-12-20 12:03:421087 if (!matches_.empty() &&
[email protected]bc8bb0cd2013-06-24 21:50:231088 (default_results_.HasServerProvidedScores() ||
1089 keyword_results_.HasServerProvidedScores())) {
[email protected]9dfb4d362013-04-05 02:15:121090 // These blocks attempt to repair undesirable behavior by suggested
[email protected]344946a12012-12-20 12:03:421091 // relevances with minimal impact, preserving other suggested relevances.
[email protected]9dfb4d362013-04-05 02:15:121092 if (IsTopMatchNavigationInKeywordMode()) {
1093 // Correct the suggested relevance scores if the top match is a
1094 // navigation in keyword mode, since inlining a navigation match
1095 // would break the user out of keyword mode. By the way, if the top
1096 // match is a non-keyword match (query or navsuggestion) in keyword
1097 // mode, the user would also break out of keyword mode. However,
1098 // that situation is impossible given the current scoring paradigm
1099 // and the fact that only one search engine (Google) provides suggested
1100 // relevance scores at this time.
1101 DemoteKeywordNavigationMatchesPastTopQuery();
1102 ConvertResultsToAutocompleteMatches();
1103 DCHECK(!IsTopMatchNavigationInKeywordMode());
1104 }
[email protected]344946a12012-12-20 12:03:421105 if (IsTopMatchScoreTooLow()) {
[email protected]1beee342012-06-19 22:22:281106 // Disregard the suggested verbatim relevance if the top score is below
1107 // the usual verbatim value. For example, a BarProvider may rely on
1108 // SearchProvider's verbatim or inlineable matches for input "foo" to
1109 // always outrank its own lowly-ranked non-inlineable "bar" match.
[email protected]cc1526e2013-05-17 04:04:241110 default_results_.verbatim_relevance = -1;
1111 keyword_results_.verbatim_relevance = -1;
[email protected]344946a12012-12-20 12:03:421112 ConvertResultsToAutocompleteMatches();
[email protected]e6acd002012-06-16 22:27:471113 }
[email protected]fb95251e2013-07-17 14:52:241114 if (IsTopMatchSearchWithURLInput()) {
[email protected]e6acd002012-06-16 22:27:471115 // Disregard the suggested search and verbatim relevances if the input
1116 // type is URL and the top match is a highly-ranked search suggestion.
1117 // For example, prevent a search for "foo.com" from outranking another
1118 // provider's navigation for "foo.com" or "foo.com/url_from_history".
[email protected]cc1526e2013-05-17 04:04:241119 ApplyCalculatedSuggestRelevance(&keyword_results_.suggest_results);
1120 ApplyCalculatedSuggestRelevance(&default_results_.suggest_results);
1121 default_results_.verbatim_relevance = -1;
1122 keyword_results_.verbatim_relevance = -1;
[email protected]344946a12012-12-20 12:03:421123 ConvertResultsToAutocompleteMatches();
[email protected]382a0642012-06-06 06:13:521124 }
[email protected]344946a12012-12-20 12:03:421125 if (IsTopMatchNotInlinable()) {
[email protected]d30268a2013-06-25 22:31:071126 // Disregard suggested relevances if the top match is not a verbatim match
1127 // or inlinable. For example, input "foo" should not invoke a search for
1128 // "bar", which would happen if the "bar" search match outranked all other
1129 // matches.
[email protected]344946a12012-12-20 12:03:421130 ApplyCalculatedRelevance();
1131 ConvertResultsToAutocompleteMatches();
[email protected]382a0642012-06-06 06:13:521132 }
[email protected]9dfb4d362013-04-05 02:15:121133 DCHECK(!IsTopMatchNavigationInKeywordMode());
[email protected]344946a12012-12-20 12:03:421134 DCHECK(!IsTopMatchScoreTooLow());
[email protected]fb95251e2013-07-17 14:52:241135 DCHECK(!IsTopMatchSearchWithURLInput());
[email protected]344946a12012-12-20 12:03:421136 DCHECK(!IsTopMatchNotInlinable());
[email protected]d1f0a7f2012-06-05 10:26:421137 }
1138
[email protected]cc63dea2008-08-21 20:56:311139 UpdateStarredStateOfMatches();
[email protected]4ab4c7c2010-11-24 04:49:341140 UpdateDone();
[email protected]257ab712009-04-14 17:16:241141}
1142
1143void SearchProvider::AddNavigationResultsToMatches(
[email protected]d30268a2013-06-25 22:31:071144 const NavigationResults& navigation_results,
1145 ACMatches* matches) {
[email protected]bc8bb0cd2013-06-24 21:50:231146 for (NavigationResults::const_iterator it = navigation_results.begin();
1147 it != navigation_results.end(); ++it) {
[email protected]d30268a2013-06-25 22:31:071148 matches->push_back(NavigationToMatch(*it));
[email protected]bc8bb0cd2013-06-24 21:50:231149 // In the absence of suggested relevance scores, use only the single
1150 // highest-scoring result. (The results are already sorted by relevance.)
[email protected]d30268a2013-06-25 22:31:071151 if (!it->relevance_from_server())
[email protected]bc8bb0cd2013-06-24 21:50:231152 return;
[email protected]257ab712009-04-14 17:16:241153 }
1154}
1155
1156void SearchProvider::AddHistoryResultsToMap(const HistoryResults& results,
1157 bool is_keyword,
1158 int did_not_accept_suggestion,
1159 MatchMap* map) {
[email protected]51124552011-07-16 01:37:101160 if (results.empty())
1161 return;
1162
[email protected]d7ad4772012-06-01 03:12:541163 bool prevent_inline_autocomplete = input_.prevent_inline_autocomplete() ||
1164 (input_.type() == AutocompleteInput::URL);
[email protected]14710852013-02-05 23:45:411165 const string16& input_text =
1166 is_keyword ? keyword_input_.text() : input_.text();
[email protected]51124552011-07-16 01:37:101167 bool input_multiple_words = HasMultipleWords(input_text);
1168
[email protected]55ce8f12012-05-09 04:44:081169 SuggestResults scored_results;
1170 if (!prevent_inline_autocomplete && input_multiple_words) {
1171 // ScoreHistoryResults() allows autocompletion of multi-word, 1-visit
1172 // queries if the input also has multiple words. But if we were already
[email protected]51124552011-07-16 01:37:101173 // autocompleting a multi-word, multi-visit query, and the current input is
1174 // still a prefix of it, then changing the autocompletion suddenly feels
1175 // wrong. To detect this case, first score as if only one word has been
1176 // typed, then check for a best result that is an autocompleted, multi-word
1177 // query. If we find one, then just keep that score set.
[email protected]55ce8f12012-05-09 04:44:081178 scored_results = ScoreHistoryResults(results, prevent_inline_autocomplete,
1179 false, input_text, is_keyword);
[email protected]9dfb4d362013-04-05 02:15:121180 if ((scored_results.front().relevance() <
[email protected]55ce8f12012-05-09 04:44:081181 AutocompleteResult::kLowestDefaultScore) ||
[email protected]9dfb4d362013-04-05 02:15:121182 !HasMultipleWords(scored_results.front().suggestion()))
[email protected]55ce8f12012-05-09 04:44:081183 scored_results.clear(); // Didn't detect the case above, score normally.
[email protected]51124552011-07-16 01:37:101184 }
[email protected]55ce8f12012-05-09 04:44:081185 if (scored_results.empty())
1186 scored_results = ScoreHistoryResults(results, prevent_inline_autocomplete,
1187 input_multiple_words, input_text,
1188 is_keyword);
1189 for (SuggestResults::const_iterator i(scored_results.begin());
1190 i != scored_results.end(); ++i) {
[email protected]d30268a2013-06-25 22:31:071191 AddMatchToMap(i->suggestion(), input_text, i->relevance(), false,
[email protected]b7f64d742013-05-21 04:04:041192 AutocompleteMatchType::SEARCH_HISTORY,
1193 did_not_accept_suggestion,
[email protected]55ce8f12012-05-09 04:44:081194 is_keyword, map);
[email protected]51124552011-07-16 01:37:101195 }
1196}
1197
[email protected]55ce8f12012-05-09 04:44:081198SearchProvider::SuggestResults SearchProvider::ScoreHistoryResults(
[email protected]51124552011-07-16 01:37:101199 const HistoryResults& results,
1200 bool base_prevent_inline_autocomplete,
1201 bool input_multiple_words,
1202 const string16& input_text,
1203 bool is_keyword) {
[email protected]810ffba2012-06-12 01:07:481204 AutocompleteClassifier* classifier =
1205 AutocompleteClassifierFactory::GetForProfile(profile_);
[email protected]55ce8f12012-05-09 04:44:081206 SuggestResults scored_results;
[email protected]257ab712009-04-14 17:16:241207 for (HistoryResults::const_iterator i(results.begin()); i != results.end();
1208 ++i) {
[email protected]51124552011-07-16 01:37:101209 // Don't autocomplete multi-word queries that have only been seen once
1210 // unless the user has typed more than one word.
1211 bool prevent_inline_autocomplete = base_prevent_inline_autocomplete ||
1212 (!input_multiple_words && (i->visits < 2) && HasMultipleWords(i->term));
1213
[email protected]ea3b9a502011-04-04 14:19:371214 // Don't autocomplete search terms that would normally be treated as URLs
[email protected]51124552011-07-16 01:37:101215 // when typed. For example, if the user searched for "google.com" and types
1216 // "goog", don't autocomplete to the search term "google.com". Otherwise,
1217 // the input will look like a URL but act like a search, which is confusing.
[email protected]cc447362011-04-06 03:57:481218 // NOTE: We don't check this in the following cases:
1219 // * When inline autocomplete is disabled, we won't be inline
1220 // autocompleting this term, so we don't need to worry about confusion as
1221 // much. This also prevents calling Classify() again from inside the
1222 // classifier (which will corrupt state and likely crash), since the
[email protected]51124552011-07-16 01:37:101223 // classifier always disables inline autocomplete.
[email protected]cc447362011-04-06 03:57:481224 // * When the user has typed the whole term, the "what you typed" history
1225 // match will outrank us for URL-like inputs anyway, so we need not do
1226 // anything special.
[email protected]51124552011-07-16 01:37:101227 if (!prevent_inline_autocomplete && classifier && (i->term != input_text)) {
[email protected]ea3b9a502011-04-04 14:19:371228 AutocompleteMatch match;
[email protected]f608ea102013-03-18 15:08:091229 classifier->Classify(i->term, false, false, &match, NULL);
[email protected]2905f742011-10-13 03:51:581230 prevent_inline_autocomplete =
[email protected]749e7ae02012-09-05 18:47:461231 !AutocompleteMatch::IsSearchType(match.type);
[email protected]ea3b9a502011-04-04 14:19:371232 }
[email protected]51124552011-07-16 01:37:101233
1234 int relevance = CalculateRelevanceForHistory(i->time, is_keyword,
1235 prevent_inline_autocomplete);
[email protected]d30268a2013-06-25 22:31:071236 scored_results.push_back(
1237 SuggestResult(i->term, is_keyword, relevance, false));
[email protected]257ab712009-04-14 17:16:241238 }
[email protected]51124552011-07-16 01:37:101239
1240 // History returns results sorted for us. However, we may have docked some
1241 // results' scores, so things are no longer in order. Do a stable sort to get
1242 // things back in order without otherwise disturbing results with equal
1243 // scores, then force the scores to be unique, so that the order in which
1244 // they're shown is deterministic.
[email protected]55ce8f12012-05-09 04:44:081245 std::stable_sort(scored_results.begin(), scored_results.end(),
1246 CompareScoredResults());
[email protected]51124552011-07-16 01:37:101247 int last_relevance = 0;
[email protected]55ce8f12012-05-09 04:44:081248 for (SuggestResults::iterator i(scored_results.begin());
1249 i != scored_results.end(); ++i) {
1250 if ((i != scored_results.begin()) && (i->relevance() >= last_relevance))
1251 i->set_relevance(last_relevance - 1);
1252 last_relevance = i->relevance();
[email protected]51124552011-07-16 01:37:101253 }
1254
[email protected]55ce8f12012-05-09 04:44:081255 return scored_results;
[email protected]257ab712009-04-14 17:16:241256}
1257
[email protected]55ce8f12012-05-09 04:44:081258void SearchProvider::AddSuggestResultsToMap(const SuggestResults& results,
[email protected]55ce8f12012-05-09 04:44:081259 MatchMap* map) {
[email protected]55ce8f12012-05-09 04:44:081260 for (size_t i = 0; i < results.size(); ++i) {
[email protected]188b50c2013-03-28 07:19:421261 const bool is_keyword = results[i].from_keyword_provider();
1262 const string16& input = is_keyword ? keyword_input_.text() : input_.text();
1263 AddMatchToMap(results[i].suggestion(), input, results[i].relevance(),
[email protected]d30268a2013-06-25 22:31:071264 results[i].relevance_from_server(),
[email protected]b7f64d742013-05-21 04:04:041265 AutocompleteMatchType::SEARCH_SUGGEST, i, is_keyword, map);
[email protected]257ab712009-04-14 17:16:241266 }
initial.commit09911bf2008-07-26 23:55:291267}
1268
[email protected]d30268a2013-06-25 22:31:071269int SearchProvider::GetVerbatimRelevance(bool* relevance_from_server) const {
[email protected]dc6943b2012-06-19 06:39:561270 // Use the suggested verbatim relevance score if it is non-negative (valid),
1271 // if inline autocomplete isn't prevented (always show verbatim on backspace),
[email protected]1beee342012-06-19 22:22:281272 // and if it won't suppress verbatim, leaving no default provider matches.
1273 // Otherwise, if the default provider returned no matches and was still able
[email protected]dc6943b2012-06-19 06:39:561274 // to suppress verbatim, the user would have no search/nav matches and may be
[email protected]1beee342012-06-19 22:22:281275 // left unable to search using their default provider from the omnibox.
[email protected]dc6943b2012-06-19 06:39:561276 // Check for results on each verbatim calculation, as results from older
1277 // queries (on previous input) may be trimmed for failing to inline new input.
[email protected]bc8bb0cd2013-06-24 21:50:231278 bool use_server_relevance =
1279 (default_results_.verbatim_relevance >= 0) &&
[email protected]dab8d52d2013-03-05 07:35:281280 !input_.prevent_inline_autocomplete() &&
[email protected]bc8bb0cd2013-06-24 21:50:231281 ((default_results_.verbatim_relevance > 0) ||
[email protected]cc1526e2013-05-17 04:04:241282 !default_results_.suggest_results.empty() ||
[email protected]bc8bb0cd2013-06-24 21:50:231283 !default_results_.navigation_results.empty());
[email protected]d30268a2013-06-25 22:31:071284 if (relevance_from_server)
1285 *relevance_from_server = use_server_relevance;
[email protected]bc8bb0cd2013-06-24 21:50:231286 return use_server_relevance ?
1287 default_results_.verbatim_relevance : CalculateRelevanceForVerbatim();
[email protected]382a0642012-06-06 06:13:521288}
[email protected]d1f0a7f2012-06-05 10:26:421289
[email protected]382a0642012-06-06 06:13:521290int SearchProvider::CalculateRelevanceForVerbatim() const {
[email protected]85b8d6f2012-05-08 20:53:471291 if (!providers_.keyword_provider().empty())
[email protected]52d08b12009-10-19 18:42:361292 return 250;
[email protected]dab8d52d2013-03-05 07:35:281293 return CalculateRelevanceForVerbatimIgnoringKeywordModeState();
1294}
[email protected]52d08b12009-10-19 18:42:361295
[email protected]dab8d52d2013-03-05 07:35:281296int SearchProvider::
1297 CalculateRelevanceForVerbatimIgnoringKeywordModeState() const {
initial.commit09911bf2008-07-26 23:55:291298 switch (input_.type()) {
1299 case AutocompleteInput::UNKNOWN:
[email protected]52d08b12009-10-19 18:42:361300 case AutocompleteInput::QUERY:
1301 case AutocompleteInput::FORCED_QUERY:
[email protected]90fe2bb2013-01-15 03:42:131302 return kNonURLVerbatimRelevance;
initial.commit09911bf2008-07-26 23:55:291303
initial.commit09911bf2008-07-26 23:55:291304 case AutocompleteInput::URL:
[email protected]52d08b12009-10-19 18:42:361305 return 850;
initial.commit09911bf2008-07-26 23:55:291306
1307 default:
1308 NOTREACHED();
1309 return 0;
1310 }
1311}
1312
[email protected]d30268a2013-06-25 22:31:071313int SearchProvider::GetKeywordVerbatimRelevance(
1314 bool* relevance_from_server) const {
[email protected]dab8d52d2013-03-05 07:35:281315 // Use the suggested verbatim relevance score if it is non-negative (valid),
1316 // if inline autocomplete isn't prevented (always show verbatim on backspace),
1317 // and if it won't suppress verbatim, leaving no keyword provider matches.
1318 // Otherwise, if the keyword provider returned no matches and was still able
1319 // to suppress verbatim, the user would have no search/nav matches and may be
1320 // left unable to search using their keyword provider from the omnibox.
1321 // Check for results on each verbatim calculation, as results from older
1322 // queries (on previous input) may be trimmed for failing to inline new input.
[email protected]bc8bb0cd2013-06-24 21:50:231323 bool use_server_relevance =
1324 (keyword_results_.verbatim_relevance >= 0) &&
[email protected]dab8d52d2013-03-05 07:35:281325 !input_.prevent_inline_autocomplete() &&
[email protected]bc8bb0cd2013-06-24 21:50:231326 ((keyword_results_.verbatim_relevance > 0) ||
[email protected]cc1526e2013-05-17 04:04:241327 !keyword_results_.suggest_results.empty() ||
[email protected]bc8bb0cd2013-06-24 21:50:231328 !keyword_results_.navigation_results.empty());
[email protected]d30268a2013-06-25 22:31:071329 if (relevance_from_server)
1330 *relevance_from_server = use_server_relevance;
[email protected]bc8bb0cd2013-06-24 21:50:231331 return use_server_relevance ?
1332 keyword_results_.verbatim_relevance :
1333 CalculateRelevanceForKeywordVerbatim(keyword_input_.type(),
1334 keyword_input_.prefer_keyword());
[email protected]5423e562013-02-07 03:58:451335}
1336
[email protected]51124552011-07-16 01:37:101337int SearchProvider::CalculateRelevanceForHistory(
[email protected]bc8bb0cd2013-06-24 21:50:231338 const base::Time& time,
[email protected]51124552011-07-16 01:37:101339 bool is_keyword,
1340 bool prevent_inline_autocomplete) const {
[email protected]aa613d62010-11-09 20:40:181341 // The relevance of past searches falls off over time. There are two distinct
1342 // equations used. If the first equation is used (searches to the primary
[email protected]d8cd76b2013-07-10 09:46:161343 // provider that we want to inline autocomplete), the score is in the range
1344 // 1300-1599 (unless |prevent_search_history_inlining_|, in which case
1345 // it's in the range 1200-1299). If the second equation is used the
1346 // relevance of a search 15 minutes ago is discounted 50 points, while the
1347 // relevance of a search two weeks ago is discounted 450 points.
[email protected]bc8bb0cd2013-06-24 21:50:231348 double elapsed_time = std::max((base::Time::Now() - time).InSecondsF(), 0.0);
[email protected]188b50c2013-03-28 07:19:421349 bool is_primary_provider = is_keyword || !providers_.has_keyword_provider();
[email protected]51124552011-07-16 01:37:101350 if (is_primary_provider && !prevent_inline_autocomplete) {
[email protected]aa613d62010-11-09 20:40:181351 // Searches with the past two days get a different curve.
[email protected]51124552011-07-16 01:37:101352 const double autocomplete_time = 2 * 24 * 60 * 60;
[email protected]aa613d62010-11-09 20:40:181353 if (elapsed_time < autocomplete_time) {
[email protected]d8cd76b2013-07-10 09:46:161354 int max_score = is_keyword ? 1599 : 1399;
1355 if (prevent_search_history_inlining_)
1356 max_score = 1299;
1357 return max_score - static_cast<int>(99 *
[email protected]aa613d62010-11-09 20:40:181358 std::pow(elapsed_time / autocomplete_time, 2.5));
1359 }
1360 elapsed_time -= autocomplete_time;
1361 }
1362
[email protected]c3a4bd992010-08-18 20:25:011363 const int score_discount =
1364 static_cast<int>(6.5 * std::pow(elapsed_time, 0.3));
initial.commit09911bf2008-07-26 23:55:291365
[email protected]6c85aa02009-02-27 12:08:091366 // Don't let scores go below 0. Negative relevance scores are meaningful in
1367 // a different way.
initial.commit09911bf2008-07-26 23:55:291368 int base_score;
[email protected]51124552011-07-16 01:37:101369 if (is_primary_provider)
[email protected]52d08b12009-10-19 18:42:361370 base_score = (input_.type() == AutocompleteInput::URL) ? 750 : 1050;
[email protected]51124552011-07-16 01:37:101371 else
1372 base_score = 200;
initial.commit09911bf2008-07-26 23:55:291373 return std::max(0, base_score - score_discount);
1374}
1375
[email protected]a2fedb1e2011-01-25 15:23:361376void SearchProvider::AddMatchToMap(const string16& query_string,
1377 const string16& input_text,
initial.commit09911bf2008-07-26 23:55:291378 int relevance,
[email protected]d30268a2013-06-25 22:31:071379 bool relevance_from_server,
[email protected]4c1fb7ec2008-11-13 00:19:001380 AutocompleteMatch::Type type,
initial.commit09911bf2008-07-26 23:55:291381 int accepted_suggestion,
[email protected]257ab712009-04-14 17:16:241382 bool is_keyword,
initial.commit09911bf2008-07-26 23:55:291383 MatchMap* map) {
[email protected]bba9e632013-06-28 22:52:191384 const TemplateURL* template_url = is_keyword ?
1385 providers_.GetKeywordProviderURL() : providers_.GetDefaultProviderURL();
1386 AutocompleteMatch match = CreateSearchSuggestion(this, relevance, type,
1387 template_url, query_string, input_text, input_, is_keyword,
[email protected]56fa29592013-07-02 20:25:531388 accepted_suggestion, omnibox_start_margin_,
1389 !is_keyword || providers_.default_provider().empty());
[email protected]cb86ee6f2013-04-28 16:58:151390 if (!match.destination_url.is_valid())
[email protected]85b8d6f2012-05-08 20:53:471391 return;
[email protected]d30268a2013-06-25 22:31:071392 match.RecordAdditionalInfo(kRelevanceFromServerKey,
1393 relevance_from_server ? kTrue : kFalse);
[email protected]85b8d6f2012-05-08 20:53:471394
initial.commit09911bf2008-07-26 23:55:291395 // Try to add |match| to |map|. If a match for |query_string| is already in
1396 // |map|, replace it if |match| is more relevant.
1397 // NOTE: Keep this ToLower() call in sync with url_database.cc.
[email protected]bc8bb0cd2013-06-24 21:50:231398 const std::pair<MatchMap::iterator, bool> i(
1399 map->insert(std::make_pair(base::i18n::ToLower(query_string), match)));
initial.commit09911bf2008-07-26 23:55:291400 // NOTE: We purposefully do a direct relevance comparison here instead of
1401 // using AutocompleteMatch::MoreRelevant(), so that we'll prefer "items added
1402 // first" rather than "items alphabetically first" when the scores are equal.
1403 // The only case this matters is when a user has results with the same score
1404 // that differ only by capitalization; because the history system returns
1405 // results sorted by recency, this means we'll pick the most recent such
1406 // result even if the precision of our relevance score is too low to
1407 // distinguish the two.
1408 if (!i.second && (match.relevance > i.first->second.relevance))
1409 i.first->second = match;
1410}
1411
1412AutocompleteMatch SearchProvider::NavigationToMatch(
[email protected]188b50c2013-03-28 07:19:421413 const NavigationResult& navigation) {
1414 const string16& input = navigation.from_keyword_provider() ?
1415 keyword_input_.text() : input_.text();
[email protected]55ce8f12012-05-09 04:44:081416 AutocompleteMatch match(this, navigation.relevance(), false,
[email protected]b7f64d742013-05-21 04:04:041417 AutocompleteMatchType::NAVSUGGEST);
[email protected]55ce8f12012-05-09 04:44:081418 match.destination_url = navigation.url();
[email protected]371dab12012-06-01 03:23:551419
1420 // First look for the user's input inside the fill_into_edit as it would be
1421 // without trimming the scheme, so we can find matches at the beginning of the
1422 // scheme.
[email protected]a1b5e862013-03-29 06:38:441423 const string16& untrimmed_fill_into_edit = navigation.formatted_url();
[email protected]371dab12012-06-01 03:23:551424 const URLPrefix* prefix =
1425 URLPrefix::BestURLPrefix(untrimmed_fill_into_edit, input);
1426 size_t match_start = (prefix == NULL) ?
1427 untrimmed_fill_into_edit.find(input) : prefix->prefix.length();
1428 size_t inline_autocomplete_offset = (prefix == NULL) ?
1429 string16::npos : (match_start + input.length());
1430 bool trim_http = !HasHTTPScheme(input) && (!prefix || (match_start != 0));
1431
1432 // Preserve the forced query '?' prefix in |match.fill_into_edit|.
1433 // Otherwise, user edits to a suggestion would show non-Search results.
1434 if (input_.type() == AutocompleteInput::FORCED_QUERY) {
1435 match.fill_into_edit = ASCIIToUTF16("?");
1436 if (inline_autocomplete_offset != string16::npos)
1437 ++inline_autocomplete_offset;
1438 }
1439
1440 const std::string languages(
1441 profile_->GetPrefs()->GetString(prefs::kAcceptLanguages));
1442 const net::FormatUrlTypes format_types =
1443 net::kFormatUrlOmitAll & ~(trim_http ? 0 : net::kFormatUrlOmitHTTP);
1444 match.fill_into_edit +=
1445 AutocompleteInput::FormattedStringWithEquivalentMeaning(navigation.url(),
1446 net::FormatUrl(navigation.url(), languages, format_types,
1447 net::UnescapeRule::SPACES, NULL, NULL,
1448 &inline_autocomplete_offset));
1449 if (!input_.prevent_inline_autocomplete())
1450 match.inline_autocomplete_offset = inline_autocomplete_offset;
1451 DCHECK((match.inline_autocomplete_offset == string16::npos) ||
1452 (match.inline_autocomplete_offset <= match.fill_into_edit.length()));
1453
1454 match.contents = net::FormatUrl(navigation.url(), languages,
1455 format_types, net::UnescapeRule::SPACES, NULL, NULL, &match_start);
1456 // If the first match in the untrimmed string was inside a scheme that we
1457 // trimmed, look for a subsequent match.
1458 if (match_start == string16::npos)
1459 match_start = match.contents.find(input);
1460 // Safe if |match_start| is npos; also safe if the input is longer than the
1461 // remaining contents after |match_start|.
1462 AutocompleteMatch::ClassifyLocationInString(match_start, input.length(),
1463 match.contents.length(), ACMatchClassification::URL,
1464 &match.contents_class);
initial.commit09911bf2008-07-26 23:55:291465
[email protected]55ce8f12012-05-09 04:44:081466 match.description = navigation.description();
[email protected]371dab12012-06-01 03:23:551467 AutocompleteMatch::ClassifyMatchInString(input, match.description,
1468 ACMatchClassification::NONE, &match.description_class);
[email protected]d30268a2013-06-25 22:31:071469
1470 match.RecordAdditionalInfo(
1471 kRelevanceFromServerKey,
1472 navigation.relevance_from_server() ? kTrue : kFalse);
1473
initial.commit09911bf2008-07-26 23:55:291474 return match;
1475}
[email protected]4ab4c7c2010-11-24 04:49:341476
[email protected]9dfb4d362013-04-05 02:15:121477void SearchProvider::DemoteKeywordNavigationMatchesPastTopQuery() {
[email protected]d519d392013-03-27 09:24:461478 // First, determine the maximum score of any keyword query match (verbatim or
1479 // query suggestion).
[email protected]d30268a2013-06-25 22:31:071480 bool relevance_from_server;
1481 int max_query_relevance = GetKeywordVerbatimRelevance(&relevance_from_server);
[email protected]cc1526e2013-05-17 04:04:241482 if (!keyword_results_.suggest_results.empty()) {
[email protected]d30268a2013-06-25 22:31:071483 const SuggestResult& top_keyword = keyword_results_.suggest_results.front();
1484 const int suggest_relevance = top_keyword.relevance();
1485 if (suggest_relevance > max_query_relevance) {
1486 max_query_relevance = suggest_relevance;
1487 relevance_from_server = top_keyword.relevance_from_server();
1488 } else if (suggest_relevance == max_query_relevance) {
1489 relevance_from_server |= top_keyword.relevance_from_server();
1490 }
[email protected]d519d392013-03-27 09:24:461491 }
1492 // If no query is supposed to appear, then navigational matches cannot
[email protected]9dfb4d362013-04-05 02:15:121493 // be demoted past it. Get rid of suggested relevance scores for
1494 // navsuggestions and introduce the verbatim results again. The keyword
1495 // verbatim match will outscore the navsuggest matches.
1496 if (max_query_relevance == 0) {
[email protected]cc1526e2013-05-17 04:04:241497 ApplyCalculatedNavigationRelevance(&keyword_results_.navigation_results);
1498 ApplyCalculatedNavigationRelevance(&default_results_.navigation_results);
1499 keyword_results_.verbatim_relevance = -1;
1500 default_results_.verbatim_relevance = -1;
[email protected]9dfb4d362013-04-05 02:15:121501 return;
1502 }
[email protected]d519d392013-03-27 09:24:461503 // Now we know we can enforce the minimum score constraint even after
1504 // the navigation matches are demoted. Proceed to demote the navigation
1505 // matches to enforce the query-must-come-first constraint.
[email protected]d519d392013-03-27 09:24:461506 // Cap the relevance score of all results.
[email protected]cc1526e2013-05-17 04:04:241507 for (NavigationResults::iterator it =
1508 keyword_results_.navigation_results.begin();
1509 it != keyword_results_.navigation_results.end(); ++it) {
[email protected]9dfb4d362013-04-05 02:15:121510 if (it->relevance() < max_query_relevance)
1511 return;
1512 max_query_relevance = std::max(max_query_relevance - 1, 0);
1513 it->set_relevance(max_query_relevance);
[email protected]d30268a2013-06-25 22:31:071514 it->set_relevance_from_server(relevance_from_server);
[email protected]d519d392013-03-27 09:24:461515 }
[email protected]d519d392013-03-27 09:24:461516}
1517
[email protected]4ab4c7c2010-11-24 04:49:341518void SearchProvider::UpdateDone() {
[email protected]2cdf1172012-08-26 12:21:331519 // We're done when the timer isn't running, there are no suggest queries
[email protected]5fac3782013-03-06 09:32:311520 // pending, and we're not waiting on Instant.
[email protected]e1290ee62013-06-26 18:31:151521 done_ = !timer_.IsRunning() && (suggest_results_pending_ == 0);
[email protected]4ab4c7c2010-11-24 04:49:341522}